2017-07-17 14 views
3

ネストされたRegionレコードのファクトリを作成しようとしています。私はこの目的のために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 
関連する問題