Spec_helper

First disable rspec-rails implicit wrapping of tests in a database transaction at spec_helper.rb :

config.use_transactional_fixtures = false

Database_cleaner strategy

Create a file to hold database_cleaner configurationa: spec/support/database_cleaner.rb:

#spec/support/database_cleaner.rb
RSpec.configure do |config|

#Clear the test database completely before running all tests.   
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

#Sets the default database cleaning strategy to be transactions.
  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

#This line only runs before examples which have been flagged :js => true. Where the transaction setting won’t work, so this code overrides the setting and chooses the “truncation” strategy instead.
  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

#These lines hook up database_cleaner around the beginning and end of each test, telling it to execute whatever cleanup strategy we selected beforehand.
  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end