How to build a parent with child factory in one step in order to pass validation

独自空忆成欢 提交于 2019-12-11 02:37:38

问题


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

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

Turning it into before(:create) means the project isn't available to reference.

Any help would be greatly appreciated!


回答1:


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.




回答2:


Can you try on before(:create) to "build" a task for the project and after(:create) saving them in order to by pass the validation error?

ex:

  before(:build) do |instance|
    instance.tasks << build(:task, project: instance)
  end
  after(:create) do |instance|
    instance.tasks.each{|t| t.save!}
  end


来源:https://stackoverflow.com/questions/16235222/how-to-build-a-parent-with-child-factory-in-one-step-in-order-to-pass-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!