Reputation: 2434
Let's say I have an app that has apartment units. It also has amenities, and garage_types. There are also locations. And each location may have differrent units, amenities, and garage_types. So I create the following factories:
FactoryGirl.define do
factory :unit do
name '608'
site
garage_type
amenity
end
factory :garage_type do
name 'garage_type a'
site
end
factory :amenity do
name 'amenity one'
site
end
factory :site do
name 'Site One'
phone '5121234567'
end
end
As you can see each factory references a site. But when the unit is created, it creates it's associated site and also creates the garage_type and amenity which each also create a site. So how do I get the unit and its associated factories to all use the same site instead of each creating a new site?
Upvotes: 0
Views: 106
Reputation: 5905
You can use factorygirl callbacks
I don't know your associations, so here's an example:
factory :unit do
name '608'
after(:build) {|unit| unit.sites = [FactoryGirl.create(:site)]}
end
factory :site do
name 'Site One'
phone '5121234567'
after(:build) {|site| site.garage_types = [FactoryGirl.create(:garage_type)]}
end
If you create a unit
using factory, then after building that unit
it will create a new associated site
for the newly created unit
. Then after creating a site
it will create an associated garage_type
.
Upvotes: 3
Reputation: 1256
Is this what you are trying to do?
site = FactoryGirl.create(:site)
unit = FactoryGirl.create(:unit, site: site)
garage_type = FactoryGirl.create(:garage_type, site: site)
amenity = FactoryGirl.create(:amenity, site: site)
Upvotes: 0