[英]has_many and belongs_to associations in factory_girl
I have these models that I'm trying to create factories for using factory_girl.我有这些模型,我正在尝试创建使用 factory_girl 的工厂。
class Foo < ActiveRecord::Base
belongs_to :baz
end
class Baz < ActiveRecord::Base
has_many :foos
end
I'm not sure how to create the factories without creating a loop where the factories endlessly call each other.我不确定如何创建工厂而不创建工厂无休止地相互调用的循环。
Factory.define :foo do |f|
f.after_create do |ff|
ff.baz = Factory(:baz)
end
end
Factory.define :baz do |f|
f.after_create do |ff|
ff.foos = [Factory.create(:foo)]
end
end
I realize I can just leave out ff.foos = [Factory.create(:foo)]
in the baz
factory, but then in my baz
tests I'm forced to used foo.baz
instead of just using baz
.我意识到我可以在
baz
工厂中ff.foos = [Factory.create(:foo)]
,但是在我的baz
测试中,我被迫使用foo.baz
而不是只使用baz
。 Am I forced to use the baz
object by fetching it out of a foo
factory in my tests?在我的测试中,我是否被迫通过将它从
foo
工厂取出来使用baz
object? Or is there a better way?或者,还有更好的方法?
See the Associations section of the Getting Started guide请参阅 入门指南的关联部分
So, you need to use that syntax from that section, ie.因此,您需要使用该部分中的语法,即。 in your
Foo
declaration you need:在您的
Foo
声明中,您需要:
Factory.define :foo do |f|
f.association :baz
end
No after_create
needed for a belongs_to
association. belongs_to
关联不需要after_create
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.