FactoryGirl:填充一个具有很多关系的保存构建策略 [英] FactoryGirl: Populate a has many relation preserving build strategy
问题描述
我的问题似乎很普遍,但是我在文档或互联网本身中找不到任何答案.
My problem seems very common, but I haven't found any answer in the documentation or the internet itself.
似乎是这个问题的克隆 has_many,同时尊重在factory_girl中建立策略,但是在那之后的2.5年中,factory_girl发生了很大变化.
It might seem a clone of this question has_many while respecting build strategy in factory_girl but 2,5 years after that post factory_girl changed a lot.
我有一个具有has_many关系的模型,称为照片.我想填充这与保留我选择的构建策略有很多关系.
I have a model with a has_many relation called photos. I want to populate this has many relation preserving my choice of build strategy.
如果我打电话给offering = FactoryGirl.build_stubbed :offering, :stay
,我希望offering.photos
是存根模型的集合.
If I call offering = FactoryGirl.build_stubbed :offering, :stay
I expect offering.photos
to be a collection of stubbed models.
我发现实现这一目标的唯一方法是:
The only way i've found to achieve this is this one:
factory :offering do
association :partner, factory: :named_partner
association :destination, factory: :geolocated_destination
trait :stay do
title "Hotel Gran Vía"
description "Great hotel in a great zone with great views"
offering_type 'stay'
price 65
rooms 70
stars 4
event_spaces 3
photos do
case @build_strategy
when FactoryGirl::Strategy::Create then [FactoryGirl.create(:hotel_photo)]
when FactoryGirl::Strategy::Build then [FactoryGirl.build(:hotel_photo)]
when FactoryGirl::Strategy::Stub then [FactoryGirl.build_stubbed(:hotel_photo)]
end
end
end
end
不用说它必须存在一种更好的方法.
No need to say that IT MUST EXIST a better way of do that.
想法?
推荐答案
以下是Flipstone答案的较简洁版本:
Here's a slightly cleaner version of Flipstone's answer:
factory :offering do
trait :stay do
...
photos do
association :hotel_photo, :strategy => @build_strategy.class
end
end
end
这篇关于FactoryGirl:填充一个具有很多关系的保存构建策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!