[英]FactoryGirl - how to create hierarchy of records?
嘗試為嵌套的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
當我將debug放入:nested_regions工廠時,我看到已經創建了這些區域層次結構,但是在Place的before_validation鈎子Region.all
只返回'Southhampton'區域。 使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.