使用子项存在validationFactory Girl创建父项和子项

有一个包含许多旅行的发票的项目。 新的故事以我的方式要求发票必须旅行。 我添加了一个validationvalidates :trips, presence: true trip validates :trips, presence: true但是现在它已经炸毁了我的一些测试,因为FactoryGirl在创建相关行程之前试图保存发票。

 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 

我该怎么做才能创建这些对象。 最好是在工厂级别,因为有许多测试利用这种行为(并且目前由于它而失败)。 这似乎是测试级别的一个很好的解决方案。

更新仍然努力让我的测试现在变绿。 42使用以下代码进行测试时出错。

validation失败:旅行不能为空

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

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

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

回调before可以帮助你。

从文档 :

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

它看起来像这样:

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