2017-02-26 36 views
2

我有觸發作業的條件回調。如果經理髮生變化,應該調用方法如何使用rspec測試條件ActiveRecord after_update回調?

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 

我很難測試這個。我需要像

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 

任何人都知道什麼是最好的方法呢?

回答

2

我結束了使用寶石shoulda-callback-matchers

context 'callbacks' do 
    it { is_expected.to callback(:employee_manager_on_change).after(:update).if :manager_id_changed? } 
end 
0

任何這樣的事情?

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 

你甚至可以指定多少時間的方法也被稱爲

expect(user).to receive(:employee_manager_on_change).once