Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Database Cleaner
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
@jamesladd
Copy link

jamesladd commented Mar 13, 2014

Where in your project do you typically put this file and from where is it required (test_helper.rb)?

@markquezada
Copy link

markquezada commented May 7, 2014

@jamesladd: spec/support/database_cleaner.rb

@gregblass
Copy link

gregblass commented Sep 2, 2015

This strategy is randomly deleting entries from my database in the middle of some of my tests for no apparent reason using Capybara-Webkit for tests with javascript enabled. Wish I could give more insight but it seems to be extremely random. Database is MYSQL.

@ptrikutam
Copy link

ptrikutam commented Sep 30, 2015

@gregblass we are encountering the exact same problem. Did you find a solution?

@thelastinuit
Copy link

thelastinuit commented Feb 19, 2020

@gregblass @ptrikutam no solution?

@ptrikutam
Copy link

ptrikutam commented Feb 20, 2020

@thelastinuit unfortunately, I'm not sure -- this was almost 5 years ago so I'm guessing I either figured it out or abandoned it. I've had a ton of trouble in general with capybara-webkit / JS testing.

I've used Database Cleaner on several projects since so I think it might have been resolved in more recent versions?

@gregblass
Copy link

gregblass commented Feb 20, 2020

Yeah, that's the thing - Database Cleaner is no longer necessary since Rails 5, as they added 1st class transaction rollback support. You can just set 'use transactional fixtures' to true in test.rb and call it a day.

Anyone still following this - just upgrade to Rails 5, and use the default rspec/capybara configuration out of the box and everything will just work.

However, if upgrading to Rails 5 is easier said than done for a particular project in your case - I actually did just use database cleaner (today) for one project that is still using Rails 4. Just use the current config they have posted on the database cleaner github readme (https://github.com/DatabaseCleaner/database_cleaner#rspec-with-capybara-example). I copy pasted that and was good to go immediately.

@thelastinuit
Copy link

thelastinuit commented Feb 20, 2020

@gregblass @ptrikutam nvm... 🤦‍♂️ it was a stupid mistake... sorry to bother you guys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment