我有一个模型 Foo
has_many 'Bar'。我为每个对象都有一个factory_girl 工厂。 Bar 的工厂与 Foo 有关联;当它创建 Bar 时,它会实例化一个 Foo。
我想要一个工厂来创建一个包含 Bar 的 Foo。理想情况下,这个 Bar 将通过 :bar 工厂创建,并遵循用于创建 Foo 的构建策略(创建/构建)。
我知道我可以调用 :bar 工厂,然后从新 Bar 中获取 Foo 引用。我想避免这种情况;在我的测试用例中,重要的对象是 Foo;调用 Bar 工厂似乎有点迂回。另外,我可以看到需要一个带有多个 Bar 的 Foo。
这在factory_girl中可能吗?你如何定义父母之间的这种关系?
I have a model Foo
that has_many 'Bar'. I have a factory_girl factory for each of these objects. The factory for Bar has an association to Foo; it will instantiate a Foo when it creates the Bar.
I'd like a Factory that creates a Foo that contains a Bar. Ideally this Bar would be created through the :bar factory, and respect the build strategy (create/build) used to create the Foo.
I know I could just call the :bar factory and then grab the Foo reference from the new Bar. I'd like to avoid this; in my test case, the important object is Foo; calling the Bar factory seems a bit circuitous. Also, I can see the need for a Foo with multiple Bars.
Is this possible in factory_girl? How do you define this relationship in the parent?
发布评论
评论(5)
Factory.after_ hooks 似乎是成功完成此操作的唯一方法。我找到了一种在不重复代码的情况下维护构建策略的方法:
文档指出
:create 构建策略,>after_build 将在
after_create
之前调用。如果使用:build
,那么只调用after_build
,大家皆大欢喜。我还创建了一个抽象的通用版本以此要点来保持干燥。
The
Factory.after_ hooks
appear to be the only way to do this successfully. I've figured out a way to maintain the build strategy without duplicating code:The documentation states that
after_build
will be called beforeafter_create
if the:create
build strategy is used. If:build
is used, then onlyafter_build
is called, and everyone is happy.I've also created an abstracted generally-applicable version at this gist to keep things DRY.
您可以通过两种方式使用
association
方法:如果这不起作用,您可以使用回调手动关联它们。这是我的一个应用程序的示例:
You can use the
association
method both ways:If that won't work, you can associate them manually using a callback. Here's an example from one of my apps:
FactoryGirl 现在有一个
:method =>;您可以在关联上使用 :build
选项,这将构建关联的对象而不是创建它。#64:构建对象创建关联
FactoryGirl now has a
:method => :build
option you can use on the association, which will build the associated object rather than creating it.#64: Building an object creates associations
FactoryGirl 4.3.0 在父对象上调用
build
时在关联上调用save!
,我认为这不是正确的行为。深入研究 FactoryGirl 代码后,将
strategy: :build
添加到工厂中的关联定义中,现在似乎可以在不调用save!
的情况下创建我的关联。FactoryGirl 4.3.0 is calling
save!
on an association when callingbuild
on the parent object, which i believe is not intended to be the correct behavior.After digging through the FactoryGirl code, adding
strategy: :build
to the association definition in the factory seems now be creating my association without callingsave!
.使用
factory_girl-4.5.0
,在父对象工厂中创建n个子对象Using
factory_girl-4.5.0
, create n child objects in a parent object factory