项目必须同时创建至少一项任务,以确保通过验证。这是我用来验证这一点的片段:
class Project < ActiveRecord::Base
validates :tasks, :length => { :minimum => 1 }
...
end
我面临的挑战是创建正确的工厂来使用 FactoryGirl 构建一个具有前期任务的项目。我在用着:
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
现在的问题是它失败了,因为它实际上创建了项目,然后尝试创建关联的任务。错误报告为:
Failure/Error: project = FactoryGirl.create(:project_with_tasks, tasks_count: 2)
ActiveRecord::RecordInvalid:
Validation failed: Projects must have at least one task
将其转换为before(:create)
意味着该项目不可参考。
任何帮助将不胜感激!