FactoryGirl - 如何创建记录层次结构?

FactoryGirl - how to create hierarchy of records?

正在尝试为嵌套区域记录创建工厂。为此,我正在使用 ancestry gem。 Region 是 Place

的关联实体

放置工厂:

factory :place, traits: [:pageable] do
  ...
  association :region, factory: :nested_regions
end

地区工厂:

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 

当我将调试放入 :nested_regions 工厂时,我看到这些区域层次结构已经创建,但是在 Place 的 before_validation 钩子中 Region.all returns 仅 'Southhampton' 地区。使用 FactoryGirl 实例化整个区域层次结构的正确方法是什么?

不要为此目的使用变量。为每个级别创建单独的工厂并按如下方式使用它:

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