CheeseFry CheeseFry - 1 year ago 94
Ruby Question

Create Parent and Child with child presence validation Factory Girl

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}
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)}


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.

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}


Working Now
@andrykonchin was right. I had missed something in my

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

Answer Source

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)}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download