ActiveRecord::Base.with_failsave

ActiveRecord::Base.with_failsave

2008/02/13 4:28am

failmalloc の精神で、必ず失敗する ActiveRecord::Base#save を書いてみた。

class ActiveRecord::Base
  def create_or_update_with_fail; false end
  alias_method :create_or_update_without_fail, :create_or_update

  # ブロックが与えられた場合はブロックを実行し、そのあいだは save! や save が必ず失敗する
  #
  # ActiveRecord::Base.with_failsave do
  # ...
  # end
  #
  def self.with_failsave
    alias_method :create_or_update, :create_or_update_with_fail
    yield
    alias_method :create_or_update, :create_or_update_without_fail
  end
end

テストコードで以下のように使うのが目的

assert_nothing_raised{ model.save! }
ActiveRecord::Base.with_failsave do
  assert_raise(ActiveRecord::RecordNotSaved){ model.save! }
end

これで例外処理コードのカバレッジも稼げるよ!