Rspec Integration Test not Cleaning the Database

12,631

Solution 1

I think https://github.com/bmabey/database_cleaner is what you need.

Solution 2

For anyone using before(:all) hooks, be aware that these hooks are executed before the transaction associated to the fixture is opened. This means that any data created by before(:all) hooks will not be rolled back by transactional fixtures. You can read more in the RSpec documentation.

I just wanted to mention this because I was bit by it and my initial instinct was to jump to Database Cleaner (which wound up not being needed and eventually not working).

Solution 3

How do I prepare test database(s) for Rails rspec tests without running rake spec?

My answer there might be of interest to you. it's a nice solution. For your case, you would probably need something like

config.after :each do
  ActiveRecord::Base.subclasses.each(&:delete_all)
end

Solution 4

You want DatabaseCleaner, but you may find that the :truncation strategy is a bit too slow to run all the time. It's really only necessary for integration tests, so you can do this:

# spec/spec_helper.rb
require 'database_cleaner'
config.before(:suite) do
  DatabaseCleaner.clean_with :truncation
  DatabaseCleaner.strategy = :transaction
end

config.before(:each) do |group|
  # The strategy needs to be set before we call DatabaseCleaner.start
  case group.example.metadata[:type]
  when :feature
    DatabaseCleaner.strategy = :truncation
  else
    DatabaseCleaner.strategy = :transaction
  end
  DatabaseCleaner.start
end

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

# spec/features/your_feature_spec.rb
require 'spec_helper'
describe "An integration test", :type => :feature do
end

# spec/model/your_model_spec.rb
require 'spec_helper'
describe "A unit test" do
end

Obviously, this only applies if you're doing integration tests with RSpec directly vs. doing them with Cucumber.

Solution 5

Look here for a tutorial: http://railscasts.com/episodes/257-request-specs-and-capybara

It describes Database Cleaner besides Rspec and Capybara

Share:
12,631
donald
Author by

donald

Updated on June 12, 2022

Comments

  • donald
    donald about 2 years

    The database is not being cleaned after each integration test. The value stays in the database.

    Is there an option I should have to make this happen?

    Thanks

  • donald
    donald about 13 years
    Isn't there a way without Database Cleaner?
  • Danyel
    Danyel almost 11 years
    There is, see my answer here: stackoverflow.com/questions/5916126/…
  • Clam
    Clam over 7 years
    In rspec 3.4, We can check that via group.metadata[:type]
  • Kevin Hutchinson
    Kevin Hutchinson almost 6 years
    Thanks! Great answer! This is a non-obvious RSpec gotcha for sure.