How to test after_commit rspec


#1

Hi guys,

I am trying to test a after_commit hook in my rails model with rspec.
However when doing something like:

c = Client.new
c.name = ‘hello’
c.domain = ‘test.com
c.save

or

c = Factory(:client)

the callback doesn’t get triggered.
I use rails 3 with ruby 1.9.2

Does anybody know how to get the “after_commit” “triggered”

thanxs!


#2

What is in the callback? How are you testing that it has/has not been
called?


#3

Well i won’t bother you with the details but this should work right?

after_commit :set_directory

def set_directory
puts “hello world”
end


#4

ohw and i test by just creating a record (client in this case);

I have tried to do this with:

c = Client.new
c.name = ‘bla’
c.save

or by doing:
c = Factory(:client)

or by doing:
c = Factory.create(:client)

also the other hooks in my model work perfectly:
after_save :set_upload
after_destroy :remove_upload

and in the app the after_commit gets called. So it isn’t my code but the
creation with rspec is the problem (something to do with mocking perhaps
? )


#5

ok i found a solution!
in your spec;

c = Factory(:client)
c.send(:set_directory)
#yes just call the method directly (not the most perfect method but it
works! :stuck_out_tongue:

for more info check here:
http://apidock.com/rails/v3.0.0/ActiveRecord/Callbacks
http://gem-session.com/2010/03/how-to-test-callback-methods-in-rails


#6

you can use https://github.com/grosser/test_after_commit to test
after_commit while keeping transactional fixtures


#7

just got stung by this too

the problem is that after_commit callback is called, well, after the
save transaction gets commited :D, which actually never happens in rspec
if you have transactional fixtures on

config.use_transactional_fixtures = true

haven’t found a good solution yet


#8

This works great! And it looks like it’s built in to Rails 5+, too.