Factory_girl 中的 has_many 和 Below_to 关联
我有这些模型,我正在尝试使用factory_girl 创建工厂。
class Foo < ActiveRecord::Base
belongs_to :baz
end
class Baz < ActiveRecord::Base
has_many :foos
end
我不知道如何在不创建工厂无休止地互相调用的循环的情况下创建工厂。
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
我意识到我可以在 baz
工厂中省略 ff.foos = [Factory.create(:foo)]
,然后在我的 baz
测试我被迫使用 foo.baz
而不是仅仅使用 baz
。我是否被迫在测试中从 foo
工厂中获取 baz
对象来使用它?或者有更好的方法吗?
I have these models that I'm trying to create factories for using 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
. Am I forced to use the baz
object by fetching it out of a foo
factory in my tests? Or is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅入门指南的关联部分
添加
因此,您需要使用该部分中的语法,即。在您的
Foo
声明中,您需要:belongs_to
关联不需要after_create
。See the Associations section of the Getting Started guide
Added
So, you need to use that syntax from that section, ie. in your
Foo
declaration you need:No
after_create
needed for abelongs_to
association.