开发者

rails test database won't wipe

开发者 https://www.devze.com 2023-02-08 13:08 出处:网络
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

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 开发者_JAVA百科environment's data between each use?

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

Thanks!

Tristan


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


Use transactional examples to rollback the data after every test run

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


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


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消