2

项目必须同时创建至少一项任务,以确保通过验证。这是我用来验证这一点的片段:

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)意味着该项目不可参考。

任何帮助将不胜感激!

4

2 回答 2

2

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.

于 2013-04-26T16:05:08.047 回答
0

您可以尝试 before(:create) 为项目“构建”一个任务,然后 after(:create) 保存它们以绕过验证错误吗?

前任:

  before(:build) do |instance|
    instance.tasks << build(:task, project: instance)
  end
  after(:create) do |instance|
    instance.tasks.each{|t| t.save!}
  end
于 2013-04-26T12:49:20.940 回答