尝试为嵌套的Region记录创建工厂。我为此目的使用ancestry gem。区域是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 hook Region.all
内部仅返回' Southhampton&# 39;区域。使用FactoryGirl实例化整个区域层次结构的正确方法是什么?
答案 0 :(得分: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