我的问题似乎很常见,但我没有在文档或互联网本身中找到任何答案。
这似乎是这个问题的克隆has_many 同时尊重factory_girl 中的构建策略 https://stackoverflow.com/questions/1506556/has-many-while-respecting-build-strategy-in-factory-girl但 2.5 年后,factory_girl 发生了很大变化。
我有一个具有 has_many 关系的模型,称为照片。我想填充这与保留我对构建策略的选择有很多关系。
如果我打电话offering = FactoryGirl.build_stubbed :offering, :stay
我预计offering.photos
成为存根模型的集合。
我发现实现这一目标的唯一方法是:
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
不用说,一定存在更好的方法来做到这一点。
Ideas?
您可以使用各种 FactoryGirl 回调:
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
after(:stub) do |offering|
offering.photos = [build_stubbed(:hotel_photo)]
end
after(:build) do |offering|
offering.photos = [build(:hotel_photo)]
end
after(:create) do |offering|
offering.photos = [create(:hotel_photo)]
end
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)