简体   繁体   English

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

[英]FactoryGirl - how to create hierarchy of records?

trying to create factory for nested Region records. 尝试为嵌套的Region记录创建工厂。 I'm using ancestry gem for this purpose. 我正在使用祖先宝石来达到这个目的。 Region is associated entity for Place 区域是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. 当我将debug放入:nested_regions工厂时,我看到已经创建了这些区域层次结构,但是在Place的before_validation钩子Region.all只返回'Southhampton'区域。 What is the right way to instantiate whole region hierarchy using FactoryGirl? 使用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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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