拥有一个项目,其中有许多Trips的发票。新的故事来了我的方式,要求发票必须有旅行。我已经添加了一个验证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错误。
验证失败:旅行不能在我的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)}
在创建父项之前,是否可以使用父项ID创建子项? – CheeseFry
@CheeseFry,你可以,但数据库中的外键约束会阻止它。你不应该*创建*,你只需要*构建*一个子模型并将其添加到(父模型)关联中;当你保存父模型(发票)时,新的子模型也会被保存,就像在我的例子中,对吧? – andrykonchin
更新了我的代码,使其工作。谢谢你的例子! – CheeseFry