out of time
-
Test after_commit hooks with transactional fixtures enabled
Rails 3 introduced
after_commitandafter_rollbackhooks, which are quite useful for situations in which a call to an external service relies on a consistent database state from that service’s perspective. Unfortunately, out of the box, it’s quite difficult to test these hooks, because Rails by default wraps each test case in a database transaction (rolling this transaction back at the end of each test maintains test isolation much more efficiently than manually deleting everything from your database). So, after_commit doesn’t fire at the end of the transactions that happen within your tests, because those aren’t real transactions; they’re savepoints (most relational databases don’t support true nested transactions).Anywho, turns out it’s pretty straightforward to monkey-patch ActiveRecord to fire the
after_commitcallback in the situation we’d expect in our tests — namely, when there’s exactly one open transaction on the transaction stack. Here’s the bacon:Just require that somewhere from your
spec_helperand you’re good to go.