database transaction rollback between tests: how to set up
Sets up transaction rollback between tests for DB isolation. Use when configuring per-test DB cleanup. Not for multi-connection tests.
TL;DR
Wrap each test in a database transaction and roll it back. It is the fastest isolation strategy; configure it in the test framework's setup hooks.
Error
(Not an error; a setup guide. The failure it prevents: data leaking between tests.)Steps
- Enable the framework's transactional mode (RSpec transactional fixtures, Django TestCase, Spring @Transactional). Expected: the option on.
- Verify: insert a row in one test, assert absence in the next. Expected: rollback proven.
- For raw setups, open the transaction in
beforeEachand roll back inafterEach. Expected: manual but explicit. - Exclude multi-connection tests (browser-driven) to truncation strategy. Expected: the exception handled.
- Run the suite twice. Expected: second run green.
When to use
- Configuring DB isolation.
- You want the fastest correct strategy.
When not to use
- Tests using a separate DB connection (use truncation).
- Non-relational stores without transactions.
Tool compatibility
- RSpec, Django, Spring, and equivalents.
Variant phrasings
Transactional tests setup
The general task.
Rollback database after each test
The mechanism; framework hooks.
Why it happens
Rollback is O(1) cleanup versus O(n) deletion. It is faster and atomic.
Edge cases
- Some DDL cannot roll back; keep migrations out of tests.
- Savepoints nest transactions for complex setups.
- Parallel tests need separate databases regardless.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstgIS8TpYJ1IybfT5nxqCJg
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.