运行 Rails 单元测试时无法访问工厂中的种子
我有包含一些设置数据的工厂。例如:
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
有谁知道为什么会发生这种情况?
I have factories that include some setup data. For example:
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 just assigns all countries from a lookup table to that particular event. I include all the countries by loading seeds before I run my tests with this line in my test helper:
require "#{Rails.root}/db/seeds.rb"
This works great when running individual unit tests:
ruby test/unit/event_test.rb
However Country.all returns nothing when I run the test using:
rake test:units
Does anyone know why this is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要 test_helper 中的种子,它会加载一次。每次测试运行后,数据库都会被清除,包括种子数据。为了使种子每次都加载,请将类似的内容添加到 test_helper 的
ActiveSupport::TestCase
类定义中。You require seeds in the test_helper, it's loaded once. After each test run database is wiped out, including seeded data. In order to make seeds load every time, add something like this to your test_helper's
ActiveSupport::TestCase
class definition.查看 rake gem 的源代码。看起来您必须在每个测试文件中手动加载
seeds.rb
文件,或者更好的是,从test_helper.rb
加载。Have a look at the source code for the
rake
gem. It looks like you'll have to load yourseeds.rb
file manually in each test file, or better yet, fromtest_helper.rb
.