[英]How to create multiple records with FactoryGirl? Currently images are applied only to first record
[英]Creating a FactoryGirl definition that uses a currently seeded record
我遇到了与FactoryGirl的GitHub页面( #623 )中提出的问题相同的问题,即通过种子数据触发了唯一性验证。
我的工厂原本是这样的:
factory :country, class: MyApp::Models::Country do
code { MyApp::Models::Country.first.code }
name { MyApp::Models::Country.first.name }
end
不理想,打碎了短绒,所以我使用#623中的建议进行了重构:
factory :country, class: MyApp::Models::Country do
intitalize_with { MyApp::Models::Country.find_or_create_by(code: 'GB') }
end
但是我现在在棉绒上得到以下错误堆栈:
/Users/philostler/.rvm/gems/ruby-2.1.2/gems/activemodel-4.1.4/lib/active_model/attribute_methods.rb:435:in `method_missing': undefined method `intitalize_with=' for #<MyApp::Models::Country id: nil, code: nil, name: nil> (NoMethodError)
from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.4/lib/active_record/attribute_methods.rb:208:in `method_missing'
from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:16:in `block (2 levels) in object'
from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:15:in `each'
from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:15:in `block in object'
from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:14:in `tap'
from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:14:in `object'
现在,它试图在一个空白模型对象上调用intitalize_with =,该对象当然会崩溃。
我只是希望工厂使用已经存在的记录,同时仍通过皮棉。
我是用错误的方式处理还是这里有错误(可能是因为我使用的是名称空间)?
当您使用FactoryGirl并使用常量声明class
,经常会遇到非相关消息的奇怪错误,就像您所做的那样。 使用字符串解决了我这方面的问题,这当然与自动加载有关。
我不知道这是否是您的解决方案,但是您可以尝试(对您所有的工厂都可以这样做)
# Instead of
factory :country, class: MyApp::Models::Country do
code { MyApp::Models::Country.first.code }
...
end
# Do
factory :country, class: 'MyApp::Models::Country' do
code { MyApp::Models::Country.first.code }
...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.