简体   繁体   中英

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?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM