How to test after_commit rspec

Hi guys,

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

c = = ‘hello’
c.domain = ‘


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”


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

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

after_commit :set_directory

def set_directory
puts “hello world”

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

I have tried to do this with:

c = = ‘bla’

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
? )

ok i found a solution!
in your spec;

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

for more info check here:

you can use GitHub - grosser/test_after_commit: Make after_commit callbacks fire in tests for Rails 3+ with transactional_fixtures = true. to test
after_commit while keeping transactional fixtures

1 Like

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

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