With Rails transactional tests, how are fixtures loaded once and rolled back per test, and when do you turn use_transactional_tests off?
answer
- use_transactional_tests defaults to true
- load once, cached by fixture key
- pinned connection, BEGIN ... ROLLBACK
- nested save becomes a savepoint
- uses_transaction for one test
basics
~20 sWith use_transactional_tests (default true) Rails inserts fixtures once, then wraps each test in a transaction on a pinned connection and rolls it back; turn it off for code that needs top-level transactions or other connections, and fixtures then reload per test.
solid answer
~50 s`use_transactional_tests` is a class attribute that defaults to `true`. Before the first test, Rails loads the fixtures and caches them by the test class's fixture list and paths. Each test then pins one connection per writing pool, opens a non-joinable transaction, and rolls it back in teardown. Fixtures stay in place and the test's writes vanish. A `save` inside the test runs as a savepoint, and `after_commit` callbacks still fire when it completes. Other threads get the same pinned connection, so they see the uncommitted rows. I turn it off with `self.use_transactional_tests = false`, or `uses_transaction :test_name` for one test, when code needs a top-level transaction: an isolation level, a real commit, or another process reading the data. Then fixtures are deleted and reinserted before every test, and I clean up what the test wrote.
code
ruby · 11 linesclass MatchSettlementTest < ActiveSupport::TestCase
# This one test needs a real top-level transaction
uses_transaction :test_settles_under_serializable
test "settles under serializable" do
Match.transaction(isolation: :serializable) do
matches(:opening_day).update!(status: :played)
end
assert matches(:opening_day, :reload).played?
end
endgo deeper
Know that each test's database changes are rolled back automatically, so tests start from the fixture data.
Explain load-once caching, the per-test BEGIN and ROLLBACK, and why saves inside a test become savepoints.
Recognise isolation-level errors, separate-connection readers and leaked rows, and opt out narrowly with uses_transaction or a dedicated class.
Decide how much of the suite may run outside transactions, weighing realism of commit behaviour against suite speed and cleanup discipline.
## The default: one load, many rollbacks `ActiveRecord::TestFixtures`, included into every Rails test class, defines **`use_transactional_tests`** as a class attribute with the default `true`. Two things follow: 1. **Fixtures load once.** Before the first test, Rails inserts the fixture rows and stores them under a cache key built from the class's fixture names, paths and class mappings. Later tests with the same key reuse them. A class that declares a different fixture list invalidates the cache, and the next test reloads. 2. **Each test runs inside a transaction.** In setup, Rails pins one connection for each writing pool, opens a transaction marked **non-joinable**, and in teardown rolls it back. The result: every test starts with exactly the fixture data, and nothing it wrote survives. ## What happens inside the test transaction - A model `save` opens its own transaction. Because the outer test transaction is non-joinable, that becomes a **savepoint**, and when the savepoint is released Rails runs the record's commit callbacks. So `after_commit` hooks do fire in transactional tests. - While pinned, the connection is handed to **every thread** that checks one out from that pool, and `lock_threads` (default `true`) serialises their access with a lock. A system test's server thread therefore sees the uncommitted fixture rows and the test's writes. - Replica connections are pointed at the writing pool for the duration, so a read sent to a replica also sees the open transaction. - If something commits or rolls back the outer transaction itself, teardown detects it, resets the connection and clears the fixture cache, so the next test reloads from YAML. ## When transactional tests get in the way | Situation | What goes wrong | |---|---| | `Team.transaction(isolation: :serializable)` in the code under test | raises `ActiveRecord::TransactionIsolationError`: "cannot set transaction isolation in a nested transaction" | | testing that a failure rolls back the whole unit of work | the "rollback" is only to a savepoint; the real commit never happens | | a child process, or a tool on a separate connection, must read the rows | it cannot see uncommitted data | | code that opens its own connections from threads | it may block on, or race with, the pinned connection | ## Turning it off, narrowly - `self.use_transactional_tests = false` in one test class. - `uses_transaction :test_settles_match_under_serializable` for a single test method. - `skip_transactional_tests_for_database(:analytics)` to keep transactions on the primary but not on another database. With transactions off, Rails **resets its fixture cache and deletes and reinserts the fixtures before each test**, which is slower. Anything the test creates that is not in a fixture table stays behind, so clean it up in `teardown`. ## Diagnosing leaks - A test that passes alone but fails after a non-transactional test usually means rows written outside fixture tables were never cleaned up. - A test that suddenly sees missing fixtures right after a test calling raw `COMMIT` is the cache-invalidation case above. - Keep non-transactional classes few, and name them so it is obvious they own their cleanup. ## A test's life, step by step 1. **Before setup:** fixtures are loaded if the cache is cold, then each writing pool's connection is pinned and a non-joinable transaction is opened. 2. **Setup and test body:** every query, from any thread, goes through the pinned connection, and model saves become savepoints. 3. **Teardown:** Rails unpins each connection and rolls back. If the transaction was already gone, it resets the connection and empties the fixture cache. 4. **Next test:** with the cache warm, it skips straight to pinning and opening a new transaction. ## Several databases In a multi-database app every writing pool gets its own pinned transaction. `use_transactional_tests_for_database(:analytics, false)` or `skip_transactional_tests_for_database(:analytics)` exempts one database, for example one that is written by a separate process, while the primary keeps the cheap rollback.
- Why do after_commit callbacks fire in a Rails transactional test even though the test transaction is rolled back?Rails opens the test transaction as non-joinable. A model `save` inside it therefore runs in its own savepoint transaction, and when that completes Rails runs the record's commit callbacks. The outer rollback later discards the data, but the callbacks have already run.
- With use_transactional_tests = false, what happens to fixtures between tests?Rails clears its fixture cache and reloads every declared fixture before each test: it deletes the rows in the fixture tables and inserts the YAML again. Fixture tables are therefore reset, but rows in other tables, files and anything committed elsewhere persist until the test cleans them up.
A transactional test is like rehearsing on a stage with a full reset button: the set (the fixtures) is built once, each rehearsal moves the props around, and the button puts everything back exactly as built. Turning transactions off means tearing the set down and rebuilding it before every rehearsal.
- Transactional tests truncate and reload every fixture table before each test.
- after_commit callbacks never run inside a Rails transactional test.
- A system test's server thread cannot see the test's uncommitted rows.
- Setting an isolation level in code works fine inside a transactional test.
- Turning transactional tests off leaves fixtures loaded once for the whole run.
Assumes Rails 8.1, where the test transaction is opened on a pinned connection (pin_connection!) that every thread receives, with lock_threads serialising access.