This post is the optimal configuration I’ve found for such a situation. It uses transactions for your non-Javascript tests, and truncation with the :pre_count
option for your Javascript ones. Just drop this file into spec/support/
. Aside from rspec, make sure your
dependencies include database_cleaner >= 0.9.1 and capybara-webkit.
Capybara.javascript_driver = :webkit # Selenium works, but not as well
RSpec.configure do |config|
config.use_transactional_fixtures = false
# Use transactions by default
config.before :each do
DatabaseCleaner.strategy = :transaction
end
# Switch to truncation for javascript tests, but *only clean used tables*
config.before :each, :js => true do
DatabaseCleaner.strategy = :truncation, {:pre_count => true}
end
config.before :each do
DatabaseCleaner.start
end
config.after :each do
DatabaseCleaner.clean
end
end
Note for Postgres users
Database Cleaner’s :pre_count
option has (or had) a bug for Postgres, where it just blew up. I submitted a patch, and it should be in the next release. As of this writing it’s at 0.9.1. So until a higher version is out, you should add database_cleaner to your Gemfile like this:
gem 'database_cleaner', :git => 'git://github.com/bmabey/database_cleaner.git'