有一个项目有包含许多行程的发票。我遇到了新故事,要求发票必须有行程。我添加了验证 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
回调可能对您有所帮助。
来自documentation :
before(:create) - called before a factory is saved (via FactoryGirl.create)
看起来像这样:
before(:create) { |object| object.details << build(:invoice_detail)}
关于ruby-on-rails - 使用子存在验证创建父子 Factory Girl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36848015/