How to test conditional ActiveRecord after_update callback with rspec?

寵の児 提交于 2021-02-10 05:52:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!