0

我有两个模型:

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

我想检查 RSpec 测试中的“check_acol_presence”钩子。所以这里是测试代码:

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

在 Rails 控制台中,这个检查工作得很好。但是测试失败了。为什么?

4

2 回答 2

2

尝试将 before_destroy 行放在 has_one 行之前

于 2012-12-01T22:35:29.763 回答
0

它应该是 raise_error,而不仅仅是 raise:

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

否则,您的测试本身可能会引发错误。

于 2013-12-20T22:32:15.870 回答