8

我的 Rails 3.1 应用程序中有以下 spec_helper.rb 文件。我正在使用 Spork 更快地加载环境进行测试。在将 Spork 添加到混合物中之前,我的所有测试都有效。添加 spork 后,测试数据库在测试运行之间没有得到正确清除,这超出了我的一些期望。

按照其他说明,我将 database_cleaner 添加到下面列出的代码中;但是,现在,开发数据库和测试数据库都在清理。ENV["RAILS_ENV"] 调用在此调用期间返回测试。

有没有办法明确限制对 DatabaseCleaner.clean_with(:truncation) 的调用只影响测试数据库?

require 'rubygems'
require 'spork'

Spork.prefork do
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'
  require 'shoulda/matchers/integrations/rspec'
  require 'database_cleaner'

  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

  RSpec.configure do |config|
    config.mock_with :mocha

    config.formatter = 'documentation'
    config.use_transactional_fixtures = true

    config.before(:suite) do
      DatabaseCleaner.strategy = :truncation
    end

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

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

Spork.each_run do
  FactoryGirl.reload
end

更新:这是我的 database.yml 文件

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

此外,我通过将 clean_with 调用移动到 before(:each) 部分来解决基本问题,但这会显着减慢测试运行速度。

4

2 回答 2

3

你试过搬出ENV["RAILS_ENV"] ||= 'test'街区Spork.prefork吗?

您确定 Spork 导致您的数据库未清理吗?如果您使用的是 RSpec 的事务性固定装置,那么唯一可能导致这种情况的是在before(:all)块内使用工厂。您可以清理after(:all)块中的数据并摆脱 DatabaseCleaner。

顺便说一句,如果您使用截断策略,则无需运行DatabaseCleaner.start.

于 2012-02-20T10:04:13.197 回答
1

您的 RAILS_ENV 是否明确设置为“开发”?如果是这样,默认的 spec_helper 将针对开发数据库运行测试。如果您从 vim 内部运行测试,或在命令行上运行 rspec,那么它将针对您的开发数据库运行测试。

当我被迫使用 database_cleaner 时,我喜欢显式设置 RAILS_ENV 以在 spec_helper 中进行测试以保护我的开发数据库。每当您使用除事务性固定装置以外的其他东西时,这可能是一个好主意。

我注意到您同时使用了事务性装置和 database_cleaner。如果您的数据库支持事务,则根本不需要 database_cleaner。如果您使用的是 Mongo,或者您正在运行 capybara-webkit 测试,那么您将需要 database_cleaner,并希望禁用事务性固定装置。

于 2012-11-23T05:35:07.810 回答