创建带有孩子存在状态验证的工厂的父母和孩子 [英] Create Parent and Child with child presence validation Factory Girl

查看:65
本文介绍了创建带有孩子存在状态验证的工厂的父母和孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个包含许多行程的发票的项目.新的故事以我的方式出现,要求发票必须出差.我已经添加了一个验证validates :trips, presence: true,但是由于FactoryGirl试图在创建关联的旅程之前保存发票,所以现在正在炸毁许多测试.

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.

更新 现在仍在努力使我的测试变得绿色. 42测试使用以下代码出错.

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

我在FactoryGirl代码中当前更新的行

My current updated line in my FactoryGirl code

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

这也是我的旅行工厂.

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

立即工作 @andrykonchin是正确的.我错过了before(:create)...

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

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

推荐答案

before回调可能会为您提供帮助.

before callback may help you.

文档:

before(:create)-在保存工厂之前调用(通过 FactoryGirl.create)

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

它看起来像这样:

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

这篇关于创建带有孩子存在状态验证的工厂的父母和孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆