问题
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