2011-09-29 37 views
8

我的Rails 3.1應用程序中有以下spec_helper.rb文件。我正在使用Spork更快地加載測試環境。在將Spork添加到組合之前,我所有的測試都可以正常工作。在添加spork之後,測試數據庫在測試運行之間沒有得到適當的清除,這導致了我的一些期望。Spork,RSpec和database_cleaner破壞開發數據庫

按照其他說明,我將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進入工作之前(:每個)部分,但是這會減慢測試運行顯着。

+0

什麼是你的'database.yml'? – Bohdan

+0

更新了問題以包含信息 –

+2

我也面臨同樣的問題,目前我使用'RAILS_ENV =測試包exec rake spec'來防止發生這種情況。 – subosito

回答

3

您是否嘗試將ENV["RAILS_ENV"] ||= 'test'移出Spork.prefork塊?

您確定Spork導致您的數據庫被清除了嗎?如果您使用RSpec的交易裝置,唯一可能導致這種情況的是使用before(:all)區塊內的工廠。您可以清理after(:all)區塊中的數據並擺脫DatabaseCleaner。

順便說一句,如果您使用截斷策略,則不需要運行DatabaseCleaner.start

1

您的RAILS_ENV是否明確設置爲「開發」?如果是這樣,默認的spec_helper將針對開發數據庫運行測試。如果您從vim內部運行測試,或者在命令行上運行rspec,那麼它將針對您的開發數據庫運行測試。

當我被迫使用database_cleaner時,我喜歡顯式設置RAILS_ENV在spec_helper中測試以保護我的開發數據庫。任何時候你使用的不是交易裝置,這可能是一個好主意。

我注意到你正在使用事務夾具和database_cleaner。如果您的數據庫支持事務,則根本不需要database_cleaner。如果您正在使用Mongo,或者您正在運行capybara-webkit測試,那麼您需要database_cleaner,並且希望禁用事務性裝置。