I want to clear my test database before running the each spec files.
I am already using rspec with factory girl.
Thanks, Hare
I want to clear my test database before running the each spec files.
I am already using rspec with factory girl.
Thanks, Hare
Add to RSpec.configure
block in your spec_helper.rb
config.before(:suite) do
DatabaseCleaner.clean_with :truncation
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
Must work
before :each
? Isn't before :suite
sufficient? –
Counterweigh In your spec_helper.rb, inside the RSpec.configure block
RSpec.configure do |config|
# ...
config.before(:suite) do
DatabaseCleaner.clean_with :transaction
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:all) do
DatabaseCleaner.start
end
config.after(:all) do
DatabaseCleaner.clean
end
# ...
end
before(:all) and after(:all) runs for every spec file and not before and after the whole suite. So, for every spec file you will be able to clear database using any of the three strategies :transaction, :truncation, :deletion
This is what I typically do for DatabaseCleaner
# Database Cleaner
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
That will make sure you have a clean database for each test.
Checkout a related, albeit old, article by Avdi for more info.
© 2022 - 2024 — McMap. All rights reserved.
database_cleaner
gem? – Gause