Ruby on rails 运行Rails单元测试时无法访问工厂中的种子

Ruby on rails 运行Rails单元测试时无法访问工厂中的种子,ruby-on-rails,unit-testing,factories,Ruby On Rails,Unit Testing,Factories,我的工厂包含一些设置数据。例如: Factory.define :event do |event| event.name { Factory.next(:email) } event.blurb "Test event blurb" event.association(:owner, :factory => :user) event.countries Country.all end Country.all只是将查找表中的所有国家/地区分配给该特定事件。在运行测试之前,

我的工厂包含一些设置数据。例如:

Factory.define :event do |event|
  event.name  { Factory.next(:email) }
  event.blurb "Test event blurb"
  event.association(:owner, :factory => :user)
  event.countries Country.all
end
Country.all只是将查找表中的所有国家/地区分配给该特定事件。在运行测试之前,我通过加载种子将所有国家/地区包括在内,测试助手中有以下行:

require "#{Rails.root}/db/seeds.rb"
这在运行单个单元测试时非常有效:

ruby test/unit/event_test.rb
但是,当我使用以下命令运行测试时,Country.all不返回任何内容:

rake test:units

有人知道为什么会发生这种情况吗?

请查看
rake
gem的源代码。看起来您必须在每个测试文件中手动加载
seeds.rb
文件,或者更好的是,从
test\u helper.rb

您需要在test\u helper中加载种子,它只加载一次。每次测试运行后,数据库都会被清除,包括种子数据。为了使seed每次都能加载,请在test\u助手的
ActiveSupport::TestCase
类定义中添加类似的内容

class ActiveSupport::TestCase
  # this line:
  setup { load "#{Rails.root}/db/seeds" }
end

我还应该注意,有必要将访问数据库的属性放在块中。event.countries Country.all变成event.countries{Country.all}我已经在test_helper.rb上做了,但是正如hakunin所指出的,必须在每个文件中完成,访问工厂中数据的属性也需要放在块中