Search code examples
ruby-on-railsruby-on-rails-3.2mockingrspec2shoulda

Testing HABTM after_add/after_remove callbacks on rails 3.2


I have a Person class which HABTM Preferences - when a preference is added or removed I need to call a method which notifies a third-party API.

Right now my person class looks like this:

class Person < ActiveRecord::Base

    has_and_belongs_to_many :preferences, :after_add => :send_communication_preference_update

    def send_communication_preference_update(preference)
        ...
    end

end

To test this I have the following spec:

describe 'person.preferences #after_add' do
  let(:person)  { FactoryGirl.create(:person) }
  let(:pref)    { [Preference.find_by_preference_name("EmailMarketing")] }

  it 'should trigger callback' do
    person.preferences = pref
    person.should_receive(:send_communication_preference_update).with(pref.first)
  end
end

However this does not work.

Even losing with(pref.first) results in the same error below.

The error I'm getting is:

Failure/Error: person.should_receive(:send_communication_preference_update).with(pref.first)
       (#<Person:0x000000086297a8>).send_communication_preference_update(#<Preference preference_id: 4, preference_name: "EmailMarketing", created_at: "2014-07-08 08:31:23", updated_at: "2014-07-08 08:31:23", active: true, default_value: false>)
           expected: 1 time
           received: 0 times

Why is this?


Solution

  • change lines order in your specs: you should place should_receive before calling assigning

    it 'should trigger callback' do
      person.should_receive(:send_communication_preference_update).with(pref.first)
      person.preferences = pref
    end