Search code examples
ruby-on-railsrspecdatabase-cleaner

Database not cleaning when testing Controllers with RSpec


When testing my Models with RSpec I use the following code to clean my database:

config.before(:suite) do
  begin
    DatabaseCleaner.start
  ensure
    DatabaseCleaner.clean
  end
end

config.after(:suite) do
  DatabaseCleaner.clean_with(:truncation)
end

All my Model tests pass, but when I test my controllers they appear to use the same dataset that my models operate on, making my tests error out.

I can get my Controller tests to pass by using this code instead:

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

This however, causes my Model tests to fail. Any advice on how to either combine these blocks without breaking one set of tests or the other?


Solution

  • You didn't mention any specific versions of database_cleaner, nor your database. But the latest config for database_cleaner in RSpec uses an around filter

    https://github.com/DatabaseCleaner/database_cleaner#rspec-example