ruby-on-railsrubyfactory-botrspec-railsancestry

FactoryGirl - how to create hierarchy of records?


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?


Solution

  • Don't use variables for that purpose. Create separate factories for each level and use it as follow:

    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