我目前正在開始從燈具遷移到工廠,並遇到一些測試數據庫挑戰。如何在每次測試之前讓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
地址: self.use_transactional_fixtures = true 到這個類,它的工作原理!謝謝。 是的,我無法改變整個環境的原因是有的。我甚至沒有想過只爲這個測試改變它...... doh! 再次感謝。 – 2009-06-03 01:19:38