FactoryGirl:填充有很多关系保存构建策略

mig*_*mba 9 testing ruby-on-rails factory-bot

我的问题似乎很常见,但我没有在文档或互联网本身找到任何答案.

它似乎是这个问题的一个克隆has_many,同时尊重factory_girl中的构建策略,但在post-factory_girl改变了很多之后的2.5年.

我有一个名为照片的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
Run Code Online (Sandbox Code Playgroud)

没必要说IT必须存在更好的方法.

想法?

Aar*_*ter 10

您可以使用各种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
Run Code Online (Sandbox Code Playgroud)

  • `after(:stub)do | offering | offering.photos = [build_stubbed(:hotel_photo)] end`这不起作用.FactoryGirl引发错误:不允许存根模型访问数据库 (3认同)

Che*_*ewi 9

这是一个稍微清洁的Flipstone版本的答案:

factory :offering do
  trait :stay do
    ...
    photos do
      association :hotel_photo, :strategy => @build_strategy.class
    end
  end
end
Run Code Online (Sandbox Code Playgroud)