Kev*_*alt 7 testing unit-testing ruby-on-rails
我目前正在开始从灯具迁移到工厂并遇到一些测试数据库挑战.
当我运行整个测试套件时,数据库将被清除,并重新加载新的工厂生成的数据.但是,当我运行单个单元测试时,数据库不会清除旧值.
我可以在每个单独的测试之前运行rake db:test:prepare,但这会减慢我的开发速度.
这是我的测试设置:
self.use_transactional_fixtures = false
self.use_instantiated_fixtures = true
Run Code Online (Sandbox Code Playgroud)
例如:
require File.dirname(__FILE__) + '/../test_helper'
class LocationTest < ActiveSupport::TestCase
test "should require name to save" do
location = Factory.create(:location)
end
end
Run Code Online (Sandbox Code Playgroud)
将成功运行一次但在后续运行测试文件时失败.之前从未发生这种情况,因为测试夹具会在每次运行时加载.
我添加了工厂排序,但在每次运行期间只有序列属性:
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
Run Code Online (Sandbox Code Playgroud)
结果是:
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
Run Code Online (Sandbox Code Playgroud)
首先检查您的测试设置,以确保它们是您想要的,尽管我怀疑您可能有理由不允许在事务中运行测试的标准做法(退出时回滚)。
其他选项是(1)手动使用事务进行测试,如上面的测试(如果还没有事务),加上(2)添加一种teardown
方法来手动清除相关表。
归档时间: |
|
查看次数: |
2887 次 |
最近记录: |