FactoryGirl:构建对象创建的关联对象(FactoryGirl: Building an o

2019-10-18 18:41发布

I don't know if this is a bug with FactoryGirl or if it is something i am doing wrong

I have two factory definitions

factory :employee do
  name "name1"
  association :department
end

factory :department do
  name "department1"
end

I would expect the following to build both employee and department

FactoryGirl.build(:employee, :name => "employee")

But it builds the employee object and creates department in the database. I am sure it use to work in some older versions of FactoryGirl.

I am using factory_girl version 4.2.0.

How do i make it build the associated objects instead of creating one?

Answer 1:

您可以使用build_stubbed

FactoryGirl.build_stubbed :employee

然后FactoryGirl将建立一个Employee对象,并在内存部门的对象。 所有两个有假身份证一样1000+和正确关联。



Answer 2:

是的,这是FactoryGirl的默认行为。 然而,该文档显示你,你可以指定你的协会,如构建策略:

factory :employee do
  name "name1"
  association :department, strategy: :build
end

见https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations



Answer 3:

要小心,因为构建不会保存对象,但如果工厂有关联仍会使请求到数据库。 例如,如果你在部门工厂定义的关联,他们将在数据库持久化。 build_stubbed,而另一方面,通过build_stubbed也将创建关联。

了解更多关于这个话题在这里



文章来源: FactoryGirl: Building an object creates its associated object