在factory_girl中与孩子们建立联系 [英] Populating an association with children in factory_girl

查看:68
本文介绍了在factory_girl中与孩子们建立联系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个型号为Foo的has_many'Bar'.我为每个对象都有一个factory_girl工厂. Bar的工厂与Foo有关联.它会在创建Bar时实例化Foo.

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.

我想要一个工厂,该工厂创建一个包含条形图的Foo.理想情况下,可以通过:bar工厂创建此Bar,并遵守用于创建Foo的构建策略(创建/构建).

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.

我知道我可以叫:bar工厂,然后从新的Bar中获取Foo参考.我想避免这种情况;在我的测试案例中,重要的对象是Foo;打电话给Bar工厂似乎有点circuit回.另外,我看到有多个Bar的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.

这可能在factory_girl中吗?您如何在父母中定义这种关系?

Is this possible in factory_girl? How do you define this relationship in the parent?

推荐答案

Factory.after_ hooks似乎是成功完成此操作的唯一方法.我想出了一种无需复制代码即可维护构建策略的方法:

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:

Factory.define :foo do |f|
  f.name "A Foo"
  f.after(:build) { |foo|
    foo.bars << Factory.build(:bar, :foo => foo)
  }
  f.after(:create) { |foo|
    foo.bars.each { |bar| bar.save! }
  }
end

文档指出,如果:create使用构建策略.如果使用:build,则仅调用after_build,每个人都很高兴.

The documentation states that after_build will be called before after_create if the :create build strategy is used. If :build is used, then only after_build is called, and everyone is happy.

我还创建了一个抽象的,普遍适用的版本在此要点,以使内容保持干燥.

I've also created an abstracted generally-applicable version at this gist to keep things DRY.

这篇关于在factory_girl中与孩子们建立联系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆