如何一步一步建立带有子工厂的父级以通过验证 [英] How to build a parent with child factory in one step in order to pass validation
问题描述
项目必须至少同时创建一个任务,以确保通过验证.这是我用来验证这一点的代码段:
Projects must have at least one task created at the same time to ensure the validation passes. This is the snippet I use to validate this:
class Project < ActiveRecord::Base
validates :tasks, :length => { :minimum => 1 }
...
end
我所面临的挑战是创建合适的工厂,以使用FactoryGirl来构建一个具有预先任务的项目.我正在使用:
The challenge I'm having is create the right factory to build a project with task upfront using FactoryGirl. I'm using:
FactoryGirl.define do
factory :task do
name "Get this test passing"
project
end
factory :project do
title "Complete the application"
factory :project_with_tasks do
ignore do
tasks_count 5
end
after(:create) do |project, evaluator|
FactoryGirl.create_list(:task, evaluator.tasks_count, project: project)
end
end
end
end
现在的问题是,这实际上失败了,因为它实际上创建了项目,然后尝试创建关联的任务.错误报告为:
Now the problem is this fails as it actually creates the project, then tries to create the associated task. The error is reported as:
Failure/Error: project = FactoryGirl.create(:project_with_tasks, tasks_count: 2)
ActiveRecord::RecordInvalid:
Validation failed: Projects must have at least one task
将其转换为before(:create)
表示该项目不可引用.
Turning it into before(:create)
means the project isn't available to reference.
任何帮助将不胜感激!
推荐答案
我最终通过以下方式建立工厂来让它通过:
I ended up getting it passing by building the factory in the following way:
project = FactoryGirl.build(:project)
project.tasks << FactoryGirl.create(:task)
project.save
这会在完成保存之前将任务添加到项目中.
This adds the task to the project before a save is done.
这篇关于如何一步一步建立带有子工厂的父级以通过验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!