Create Parent and Child with child presence validation Factory Girl

落爺英雄遲暮 提交于 2019-12-24 15:12:33

问题


Have a project that has Invoices with many Trips. New story came my way requesting that an Invoice MUST have a trip. I've added a validation validates :trips, presence: true but it is now blowing up a number of my tests since FactoryGirl is trying to save the invoice before creating the associated trip.

FactoryGirl.define do
  factory :invoice do
    sequence(:invoice_id) { SecureRandom.uuid}
    merchant
    amount 100.00
    item_count 1
    paid false
    currency "GBP"
    invoice_type "pre-flight"
    service_rendered false
    cancelled false

    after(:create) { |object| create(:trip, invoice_id: object.invoice_id)}
  end

end

What can I do to create these objects. Preferably at the factory level since there are numerous tests utilizing this behavior (and currently failing because of it.) This seems like a good solution at the test level.

Update Still struggling with getting my tests green now. 42 Tests are erroring out with the following code.

Validation failed: Trips can't be blank

My current updated line in my FactoryGirl code

  before(:create) { |object| object << build(:trip, invoice_id: object.invoice_id)}

Here is my trip factory as well.

FactoryGirl.define do
  factory :trip do
    depart_airport "MCI"
    arrive_airport "ORD"
    passenger_first_name "Joe"
    passenger_last_name "Business"
    passenger_count 1
    departure_date {10.days.from_now}
    invoice
  end

end

Working Now @andrykonchin was right. I had missed something in my before(:create)...

before(:create) { |object| object.trips << build(:trip, invoice_id: object.invoice_id)}


回答1:


before callback may help you.

From the documentation:

before(:create) - called before a factory is saved (via FactoryGirl.create)

It would look like this:

before(:create) { |object| object.details << build(:invoice_detail)}


来源:https://stackoverflow.com/questions/36848015/create-parent-and-child-with-child-presence-validation-factory-girl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!