rails rspec destroy data after each test
# spec/rails_helper.rb
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
Ensure you have the database_cleaner
gem in your Gemfile:
# Gemfile
group :test do
gem 'database_cleaner'
end
Run bundle install:
bundle install
Update your .rspec
file to include the following line:
--require rails_helper
This configuration will use the DatabaseCleaner gem to clean the database before each test. The :transaction
strategy is used for non-JS tests, and the :truncation
strategy is used for JS tests. This ensures a clean slate for each test, preventing data interference between examples. The :before(:suite)
hook truncates the database once before the test suite runs, and the :before(:each)
and :after(:each)
hooks manage transactions and cleaning before and after each test.