2017-07-17 96 views
3

试图为嵌套区域记录创建工厂。为此,我使用ancestry宝石。地区是地方FactoryGirl - 如何创建记录层次结构?

关联实体

地点工厂:

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内只返回'Southhampton'地区。使用FactoryGirl实例化整个区域层次结构的正确方法是什么?

回答

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