尝试为嵌套区域记录创建工厂。我为此目的使用祖先宝石。区域是 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 实例化整个区域层次结构的正确方法是什么?
不要为此目的使用变量。为每个级别创建单独的工厂,并按如下方式使用它:
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