WoodenKitty
WoodenKitty

Reputation: 6539

rails test database won't wipe

I'm running rails 3.0.3 and using rspec-rails 2.4.1 with a postgresql database. Whenever I run my RSpec tests, the data remains at the end. Does anyone know how to get rails or rspec to wipe the test environment's data between each use?

Please tell me if there's any further information that could make answering my question easier.

Thanks!
Tristan

Upvotes: 4

Views: 3963

Answers (4)

Deepak N
Deepak N

Reputation: 2571

Use transactional examples to rollback the data after every test run

RSpec.configure do |config|
  config.use_transactional_examples = true
end

Upvotes: 5

thomax
thomax

Reputation: 9659

You don't need any extra gem in order to clean your test DB between runs. In your spec_helper.rb file, configure rspec as follows:

RSpec.configure do |c|
  c.around(:each) do |example|
    ActiveRecord::Base.connection.transaction do
      example.run
      raise ActiveRecord::Rollback
    end
  end
end

Upvotes: 1

James Chevalier
James Chevalier

Reputation: 10874

Another possibility, that I just put myself through, is using the wrong before block.

I accidentally set a before block as an all instead of an each:

before :all do
  user = FactoryGirl.create(:user)
  sign_in user
end

This caused the user to stick around in the database for the entire rspec run, which caused validation collisions.

Instead, the before should be an each so that everything is kept clean through the rspec run:

before :each do
  user = FactoryGirl.create(:user)
  sign_in user
end

If you've made this mistake, then you will probably need to manually clean up your test database before things go back to normal. The simplest way to do that is probably to truncate each of the tables (aside from schema_migrations).

Upvotes: 0

bobbywilson0
bobbywilson0

Reputation: 1072

Install the database_cleaner gem and then add this to your spec_helper.rb.

Spec::Runner.configure do |config|

  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

end

Upvotes: 10

Related Questions