使用子存在验证创建父子 Factory Girl
Create Parent and Child with child presence validation Factory Girl
有一个项目,其中包含许多行程的发票。我遇到了新故事,要求发票必须有行程。我已经添加了一个验证 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
我该怎么做才能创建这些对象。最好是在工厂级别,因为有许多测试利用了这种行为(目前因此失败。)This 在测试级别似乎是一个很好的解决方案。
更新
现在仍在努力让我的测试变绿。 42 测试出现以下代码错误。
Validation failed: Trips can't be blank
我的 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) - called before a factory is saved (via
FactoryGirl.create)
看起来像这样:
before(:create) { |object| object.details << build(:invoice_detail)}
有一个项目,其中包含许多行程的发票。我遇到了新故事,要求发票必须有行程。我已经添加了一个验证 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
我该怎么做才能创建这些对象。最好是在工厂级别,因为有许多测试利用了这种行为(目前因此失败。)This 在测试级别似乎是一个很好的解决方案。
更新 现在仍在努力让我的测试变绿。 42 测试出现以下代码错误。
Validation failed: Trips can't be blank
我的 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) - called before a factory is saved (via FactoryGirl.create)
看起来像这样:
before(:create) { |object| object.details << build(:invoice_detail)}