【问题标题】:FactoryGirl - how to create hierarchy of records?FactoryGirl - 如何创建记录层次结构?
【发布时间】:2017-07-17 08:49:21
【问题描述】:

尝试为嵌套区域记录创建工厂。为此,我正在使用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 内仅返回“南汉普顿”区域。使用 FactoryGirl 实例化整个区域层次结构的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby factory-bot rspec-rails ancestry


    【解决方案1】:

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

    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 
    

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多