FactoryGirl - how to create hierarchy of records?

Viewed 267

trying to create factory for nested Region records. I'm using ancestry gem for this purpose. Region is associated entity for Place

Place 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 place debug into :nested_regions factory I see that these region hierarchy has been created, but inside Place's before_validation hook Region.all returns only 'Southhampton' region. What is the right way to instantiate whole region hierarchy using FactoryGirl?

1 Answers
Related