FactoryGirl - how to create a record hierarchy?
trying to create a factory for nested Region records. I am using ancestry for this purpose . Region is an associated object for Place
Place the factory:
factory :place, traits: [:pageable] do
...
association :region, factory: :nested_regions
end
Region factory:
factory :region do
level 'area'
factory :nested_regions do |r|
# create South Hampton region sequence
continent = FactoryGirl.create(:region,
level: Region.levels[:continent],
name: 'Europe ')
country = FactoryGirl.create(:region,
level: Region.levels[:country],
name: 'United Kingdom',
parent: continent)
state = FactoryGirl.create(:region,
level: Region.levels[:state],
name: 'England',
parent: country)
county = FactoryGirl.create(:region,
level: Region.levels[:county],
name: 'Hampshire',
parent: state)
name 'Southampton'
parent county
end
end
When I post debug to : nested_regions factory, I see that this region hierarchy is created, but inside the Place, the before_validation hook Region.all
only returns the Southhampton region. What is the correct way to create an entire scope hierarchy using FactoryGirl?
+3
source to share
1 answer
Don't use variables for this purpose. Create separate factories for each tier and use it like this:
factory :region do
name 'Region'
factory :county
association :parent, factory: :region
level 'county'
end
factory :area
association :parent, factory: :county
level 'Area'
name 'area'
end
end
+1
source to share