【问题标题】:How do I get the Rails test database to rebuild before each test?如何在每次测试之前重建 Rails 测试数据库?
【发布时间】:2010-10-30 17:18:21
【问题描述】:

我目前正在开始从夹具迁移到工厂并遇到一些测试数据库挑战。

当我运行我的整个测试套件时,数据库被清除并重新加载新的工厂生成的数据。但是,当我运行单个单元测试时,数据库不会清除旧值。

我可以在每次单独测试之前运行 rake db:test:prepare,但这会减慢我的开发速度。

这是我的测试设置:

  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

【问题讨论】:

    标签: ruby-on-rails unit-testing testing


    【解决方案1】:

    首先检查您的测试设置以确保它们是您想要的,尽管我怀疑您可能有理由禁止在事务中运行测试的标准做法(退出时回滚)。

    其他选项是 (1) 手动使用事务进行上述测试(其中还没有事务),加上 (2) 添加teardown方法手动清理相关表。

    【讨论】:

    • 添加:self.use_transactional_fixtures = true 到这个类,它的工作原理!谢谢你。是的,我无法在整个环境中更改它是有原因的。我什至没想过只为这一次测试而改变它……哦!再次感谢。
    【解决方案2】:

    您可以在单元测试中覆盖setup 方法,以便它删除您要清除的数据。

    【讨论】:

      【解决方案3】:

      由于每个测试都应该从一个干净的数据库开始,因此请尝试将代码库中的内容放在可以在每个测试中使用事务的地步。因此,您的测试质量将大大提高。

      此外,这与您的问题没有直接关系……但在任何情况下,都不要使用 Rails 固定装置。改用工厂(查看 factory_girl_rails gem)。另外,请查看 RSpec 而不是 Test::Unit。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        • 2019-01-01
        • 1970-01-01
        • 2023-01-11
        • 2023-03-24
        • 2022-11-12
        • 1970-01-01
        相关资源
        最近更新 更多