问题
I have a conditional callback that triggers a job. If the manager changes, it should call the method
class Employee < ActiveRecord::Base
after_update :employee_manager_on_change, if: :employee_id_changed?
def employee_manager_on_change
EmployeeManagerChangedJob.perform_later(id)
end
end
I'm having trouble to test this. I needed something like
context 'when changing manager' do
subject { user.manager = new_manager }
it 'calls employee_manager_on_change' do
expect { suject.run_callbacks :update }.to receive(:employee_manager_on_change)
end
end
Anyone knows what's the best approach for this?
回答1:
I ended up using the gem shoulda-callback-matchers
context 'callbacks' do
it { is_expected.to callback(:employee_manager_on_change).after(:update).if :manager_id_changed? }
end
回答2:
Anything like this?
context 'when changing manager' do
before { user.manager = new_manager }
it 'calls employee_manager_on_change' do
user.save
expect(user).to receive(:employee_manager_on_change)
end
end
You can even specify how many time the method has to be called
expect(user).to receive(:employee_manager_on_change).once
来源:https://stackoverflow.com/questions/42475287/how-to-test-conditional-activerecord-after-update-callback-with-rspec