Rails 3.2对于before_destroy挂钩的RSpec测试失败

时间:2012-12-01 10:41:10

标签: ruby-on-rails rspec-rails

我有两种模式:

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控制台中,此检查工作正常。但测试失败了。为什么呢?

2 个答案:

答案 0 :(得分:2)

尝试在has_one line

之前放置before_destroy行

答案 1 :(得分:0)

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

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

否则,您的测试本身可能提出错误。