开发者

Rspec Integration Test not Cleaning the Database

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

Is there a开发者_如何学Pythonn option I should have to make this happen?

Thanks


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


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


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


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

It describes Database Cleaner besides Rspec and Capybara


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.


There are two ways to accomplish this:

  1. Configure transactional examples for each individual test.
  2. Configure transactional examples for all the tests.

If you opt for option 1: At the top of the spec file, after:

require 'spec_helper'

Add:

RSpec.configure {|c| c.use_transactional_examples = true }

That will roll back the transactions after each example.

2.If you want to configure it globally, then, in the spec_helper.rb

RSpec.configure do |config|
...
config.use_transactional_examples = true # Add this
...
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜