Skip to content

Instantly share code, notes, and snippets.

@jsteiner
Created January 10, 2014 20:31
  • Star 80 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jsteiner/8362013 to your computer and use it in GitHub Desktop.
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

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

@markquezada
Copy link

@jamesladd: spec/support/database_cleaner.rb

@gregblass
Copy link

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

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

@thelastinuit
Copy link

@gregblass @ptrikutam no solution?

@ptrikutam
Copy link

@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

@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