Ivan
Ivan

Reputation: 847

Rails 3.2 RSpec test for before_destroy hook fails

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?

Upvotes: 0

Views: 780

Answers (2)

sergiokas
sergiokas

Reputation: 349

It should be raise_error, not just raise:

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

Otherwise, your test itself was probably raising the error.

Upvotes: 0

Andrey Kryachkov
Andrey Kryachkov

Reputation: 901

Try to put before_destroy line before has_one line

Upvotes: 2

Related Questions