问题
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?
回答1:
You can use build_stubbed
FactoryGirl.build_stubbed :employee
Then FactoryGirl will build an employee object and a department object in memory. All of the two have fake ids like 1000+, and correctly associated.
回答2:
Yes, this is the default behaviour for FactoryGirl. However, the documentation shows you that you can specify a build strategy for your association, e.g.:
factory :employee do
name "name1"
association :department, strategy: :build
end
See https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations
回答3:
Be careful because build won't save the object, but if the factory has associations it will still make requests to a database. For example, if you defined association in department factory they will be persisted in db. build_stubbed, on the other hand, will create associations via build_stubbed too.
Read more about this topic here
来源:https://stackoverflow.com/questions/19407234/factorygirl-building-an-object-creates-its-associated-object