2009-06-02 152 views
7

我目前正在開始從燈具遷移到工廠,並遇到一些測試數據庫挑戰。如何在每次測試之前讓Rails測試數據庫重建?

當我運行我的整個測試套件時,數據庫被清除,並重新加載新的工廠生成的數據。但是,當我運行單個單元測試時,數據庫不會清除舊值。

我可以運行rake db:test:準備在每個單獨的測試之前,但這會減慢我的開發速度。

這裏是我的測試設置:

self.use_transactional_fixtures = false 
    self.use_instantiated_fixtures = true 

例如:

require File.dirname(__FILE__) + '/../test_helper' 
class LocationTest < ActiveSupport::TestCase 
    test "should require name to save" do 
    location = Factory.create(:location) 
    end 
end 

將運行一次成功,但未能在隨後的測試文件的運行。之前從未發生這種情況,因爲測試裝置會在每次運行時加載。

我已經加入廠測序,但每次運行期間,只有序列屬性:

Factory.define :location do |l| 
    l.sequence(:name) {|n| "place#{n}"} 
    l.street '123 N Pitt Street' 
    l.state_id 4 
    l.city 'San Francisco' 
    l.location_type_id LocationType::COMMON 
    l.shipper_id 1 
    l.zip 23658 
    end 

結果:

trunk>ruby test\unit\location_test.rb 
Loaded suite test/unit/location_test 
Started 
. 
Finished in 0.162 seconds. 

1 tests, 0 assertions, 0 failures, 0 errors 

>ruby test\unit\location_test.rb 
Loaded suite test/unit/location_test 
Started 
E 
Finished in 0.134 seconds. 

    1) Error: 
test_should_require_name_to_save(LocationTest): 
ActiveRecord::RecordInvalid: Validation failed: Name has already been taken 
    c:/ruby/lib/ruby/gems/1.8/gems/thoughtbot-factory_girl-1.2.1/lib/factory_girl/proxy/create.rb:5:in `result' 
    c:/ruby/lib/ruby/gems/1.8/gems/thoughtbot-factory_girl-1.2.1/lib/factory_girl/factory.rb:293:in `run' 
    c:/ruby/lib/ruby/gems/1.8/gems/thoughtbot-factory_girl-1.2.1/lib/factory_girl/factory.rb:237:in `create' 
    test/unit/location_test.rb:18:in `test_should_require_name_to_save' 

1 tests, 0 assertions, 0 failures, 1 errors 

回答

1

首先檢查您的測試設置,以確定它們是您想要的,儘管我懷疑您可能有理由不允許在事務中運行測試(在退出時回退)的標準做法。

其他選項是 (1)手動使用交易爲像上面的(那裏是沒有交易)的測試,加上 (2)添加一個teardown方法手動清理了相關表格。

+1

地址: self.use_transactional_fixtures = true 到這個類,它的工作原理!謝謝。 是的,我無法改變整個環境的原因是有的。我甚至沒有想過只爲這個測試改變它...... doh! 再次感謝。 – 2009-06-03 01:19:38

0

您可以覆蓋setup方法在你的單元測試,以便它刪除你想清除的數據。

0

因爲每個測試應該從一個乾淨的數據庫啓動,試圖讓事情在你的代碼庫的地步,你爲每個測試可以使用交易。結果,您的測試質量將大大提高。此外,這與您的問題沒有直接關係......但在任何情況下,絕對不要在任何情況下使用Rails燈具。改用工廠(查看factory_girl_rails gem)。另外,請查看RSpec而不是Test :: Unit。

相關問題