0

I have two models:

class Region < ActiveRecord::Base
  has_one :acol, :dependent => :nullify
  before_destroy :check_acol_presence
private 
  def check_acol_presence
    if acol
      errors.add(:base,"activerecord.errors.models.region.delete_with_existing_acol")
      return false
    end
  end
end

class Acol < ActiveRecord::Base
  belongs_to :region
end

I want to check the 'check_acol_presence' hook in RSpec test. So here is the test code:

region = FactoryGirl.create(:region)
acol = FactoryGirl.create(:acol, :region => region)
region.reload
region.destroy
lambda { region.reload }.should_not raise(ActiveRecord::RecordNotFound) 

In rails console this check works just fine. But the test fails. Why?

4

2 に答える 2

2

has_one 行の前に before_destroy 行を置くようにしてください

于 2012-12-01T22:35:29.763 に答える
0

raise だけでなく、raise_error にする必要があります。

lambda { region.reload }.should_not raise_error(ActiveRecord::RecordNotFound)

それ以外の場合は、テスト自体でエラーが発生していた可能性あります。

于 2013-12-20T22:32:15.870 に答える