rspec database cleaner transaction strategy guide
Sets up DatabaseCleaner transaction strategy in RSpec for fast isolated tests. Use when configuring DB cleaning. Not for truncation strategy choice (see edge cases).
TL;DR
Use the transaction strategy: wrap each test in a DB transaction and roll back. It is the fastest isolation method and works for most suites; switch to truncation only for JavaScript-driven (separate connection) tests.
Error
(Not an error; a setup guide. The failure it prevents: tests leaking data into each other.)Steps
- Add databasecleaner to the Gemfile and require it in railshelper. Expected: the gem loads.
- Configure:
config.before(:suite) { DatabaseCleaner.strategy = :transaction }, clean with truncation once before the suite. Expected: clean starting state. - Wrap each test:
config.around(:each) { |ex| DatabaseCleaner.cleaning { ex.run } }. Expected: rollback after every test. - For
js: truefeature tests (separate DB connection), switch those to:truncation. Expected: Capybara threads see the data. - Run the suite twice in a row. Expected: second run is green, proving isolation.
When to use
- New RSpec suite or flaky data leakage.
- You want the fastest correct strategy.
When not to use
- Non-Rails or non-ActiveRecord suites.
- You already use transactional fixtures (built-in alternative).
Tool compatibility
- RSpec 3.x; database_cleaner 2.x; Rails.
Variant phrasings
DatabaseCleaner transaction vs truncation
Transaction for speed, truncation for multi-connection tests.
RSpec test database isolation
The general topic; transactions are the default answer.
Why it happens
Tests share one database. Without per-test rollback, data leaks between tests and creates order dependence.
Edge cases
- Rails' own
use_transactional_fixturesdoes the same thing; do not combine both. - Truncation is slower but necessary when the app server uses a separate connection.
- Parallel tests need separate databases per process regardless of strategy.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_KgAj4KdoRw6cZVF-R92Hpw
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.