Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing after_commit with RSpec and mocking

I have a model Lead and a callback: after_commit :create, :send_to_SPL

I am using Rails-4.1.0, ruby-2.1.1, RSpec.

1) This spec is not passing:

context 'callbacks' do   it 'shall call \'send_to_SPL\' after create' do     expect(lead).to receive(:send_to_SPL)     lead = Lead.create(init_hash)     p lead.new_record? # => false   end end 

2) This spec is not passing too:

context 'callbacks' do   it 'shall call \'send_to_SPL\' after create' do     expect(ActiveSupport::Callbacks::Callback).to receive(:build)     lead = Lead.create(init_hash)   end end 

3) This one is passing, but I think it is not testing after_commit callback:

context 'callbacks' do   it 'shall call \'send_to_SPL\' after create' do     expect(lead).to receive(:send_to_SPL)     lead.send(:send_to_SPL)   end end 

What is the best way to test after_commit callbacks in Rails?

like image 260
Mihail Davydenkov Avatar asked Apr 10 '14 13:04

Mihail Davydenkov


1 Answers

I thought Mihail Davydenkov's comment deserved to be an answer:

You can also use subject.run_callbacks(:commit).

Also note that this issue (commit callbacks not getting called in transactional tests) should be fixed in rails 5.0+ so you may wish to make a note to remove any workarounds you may use in the meantime when you upgrade. See: https://github.com/rails/rails/pull/18458

like image 98
ihaztehcodez Avatar answered Sep 20 '22 11:09

ihaztehcodez