Read more

Rails < 5: How to get after_commit callbacks fired in tests

Emanuel
August 09, 2018Software engineer at makandra GmbH

If you use transactional_fixtures or the database_cleaner gem Show archive.org snapshot with strategy :transaction, after_commit callbacks will not be fired in your tests.

Rails 5+

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Rails 5 has a fix Show archive.org snapshot for this issue and no further action is needed.

Rails 3, Rails 4

Add the gem test_after_commit Show archive.org snapshot to your test group in the Gemfile and you are done. You don't need to change the database strategy to deletion (which might lead to longer test runs).

Note:

Most often a after_commit is the only right choice. Sending emails, performing async sidekiq workers and many things more are kind of broken with an after_save callback.

If you replace an after_save callback with an after_commit callback this list might help you to fix your code afterwards:

  • attribute_changed? will return true in the after_save callback and false in the after_commit callback. Use something like previous_changes.key?(:attribute) instead.
Posted by Emanuel to makandra dev (2018-08-09 16:35)