Database Cleaner provides Ruby gems with strategies to reset databases between tests, keeping specs isolated from leftover data.
Overview
Database Cleaner is a family of Ruby gems that implement strategies for wiping or rolling back database state during automated tests. The original goal is a predictable empty or known baseline while specs run.
Each object-relational mapper has its own adapter gem; many projects only need database_cleaner-activerecord. Adapters cover SQL databases such as MySQL, PostgreSQL, and SQLite, plus MongoDB and Redis. Strategies include transaction rollbacks, truncation, deletion, and a null strategy that performs no cleaning.
You call DatabaseCleaner.start before runs that need open transactions, wrap suites in DatabaseCleaner.cleaning, or invoke DatabaseCleaner.clean with a chosen strategy. Truncation can take options and will not truncate schema migration tables. For SQL backends, :transaction is fastest when a single connection shares the app and tests; truncation or deletion suits multi-connection setups such as Capybara JavaScript drivers.
Safeguards block running in production and against remote databases unless explicitly disabled, with optional DATABASE_URL allowlists.
Key features
- Per-ORM adapter gems
- Transaction, truncation, deletion strategies
- Multi-ORM and multi-database cleaning
- RSpec, Minitest, and Cucumber patterns
- Null strategy for no-op cleaning
- Production and remote DB safeguards
- Configurable URL allowlists
Use cases
- Isolated Rails test databases
- Feature specs with external browsers
- MongoDB or Redis test cleanup
- Non-Rails ActiveRecord test suites