RSpec +数据库清理,没有正确清理

时间:2012-03-29 14:40:35

标签: ruby-on-rails rspec

我真的不明白为什么DatabaseCleaner没有清理我的测试数据库。这就是我得到的提示

1.9.2p290 :007 > DatabaseCleaner.clean

-

=> [#<DatabaseCleaner::Base:0x007fa7e4dd8b58 @autodetected=true, @orm=:active_record, @strategy=#<DatabaseCleaner::ActiveRecord::Transaction:0x007fa7e4dc14f8 @db=:default>>] 

这似乎没有正确设置数据库(应该是:test),所以我得到了像

这样的解决方案
 DatabaseCleaner[:active_record, :connection => :test].clean
 # => nil

宝石似乎设置正确:

1.9.2p290 :007 > DatabaseCleaner[:active_record, :connection => :test]

#<DatabaseCleaner::Base:0x007fe8fcfd4868 @orm=:active_record, @strategy=#<DatabaseCleaner::ActiveRecord::Transaction:0x007fe8fcfd2748 @db=:test, @connection_hash={"adapter"=>"sqlite3", "database"=>"db/test.sqlite3", "pool"=>5, "timeout"=>5000}>, @db=:test> 

这似乎正确地设置了测试数据库,但它仍然无法正确清理数据库。有什么建议吗?

非常感谢。

4 个答案:

答案 0 :(得分:14)

即使正确配置了数据库清理程序,也很容易留下数据。

config.before(:suite) do
  DatabaseCleaner.clean_with :truncation  # clean DB of any leftover data
  DatabaseCleaner.strategy = :transaction # rollback transactions between each test
  Rails.application.load_seed # (optional) seed DB
end

config.before(:each) do
  DatabaseCleaner.start
end

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

上面的配置开始&amp;在每次测试的任一侧运行清洁器。

如果您在规范中使用before :all,最终可能会出现数据:

describe User do
  # Before all is outside the before :each 
  before :all do
    @user = User.create(:email => 'hello@example.com')
  end

  ...tests here
end

答案 1 :(得分:5)

这是我的spec_helper.rb(略有修改) - 也许这会对你有帮助吗?

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'database_cleaner'

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
  end
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
end

答案 2 :(得分:4)

Avdi Grimm最近发表了一篇关于配置数据库清理工具的好文章:

http://devblog.avdi.org/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/

答案 3 :(得分:1)

$ rails c test
> require 'database_cleaner'
> DatabaseCleaner.strategy = :truncation
> DatabaseCleaner.clean

https://github.com/DatabaseCleaner/database_cleaner