Well-intentioned, but slow
# Gemfile gem 'database_cleaner', group: :test # spec_helper.rb -- This workaround is slow! RSpec.configure do |config| # ... config.use_transactional_fixtures = false config.before(:suite) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
A faster solution
The trick is to still use the
database_cleaner gem, but specify the slow
:truncation strategy only when we need it, and fall back to the fast
:transaction strategy otherwise. Here’s how:
RSpec.configure do |config| # ... config.use_transactional_fixtures = false config.before(:each) do DatabaseCleaner.strategy = if example.metadata[:js] :truncation else :transaction end DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
js: true was specified). Using this metadata, it’s easy to choose the appropriate database strategy on an example-by-example basis.
Here’s how long it took to run
rake spec on one of my projects before we adopted this solution:
Finished in 3 minutes 39.44 seconds
Finished in 41.27 seconds
That’s an 80% speedup!