Have you considered using after(:build) blocks ?
FactoryGirl + Ancestry with two level deep
-
30-06-2022 - |
Question
Basically:
- I have a
Structure
model that has manySubjects
. - Each subject has a parent and it can be 2-levels deep.
- A
Structure
has to have one Subject at_depth 0 and one Subject at_depth 2.
The problem:
- I can't figure out how to build my Subject Factory and how to make the association in the Structure Factory.
I'm on Rails 4, factory_girl_rails 4.2.1 and Ruby 2.0.0
Here is what I tried for the subject factory:
factory :subject_grand_parent do |f|
name Forgery(:name).company_name
factory :subject_parent do |s|
f.parent { Factory.create(:subject_grand_parent) }
factory :subject do |s|
f.parent { Factory.create(:subject_parent) }
end
end
end
But I can't define parent two times.
And in the Structure
factory I'm not sure how to define multiple subjects for my association. Here
what I have now:
factory :structure do
subjects {|structure| [structure.association(:subject)] }
...
end
Thanks in advance
Solution 2
OTHER TIPS
Alright, this seems to work:
Subject
Factory:
factory :subject do name Forgery(:name).company_name
factory :subject_children do
name Forgery(:name).company_name + ' child'
after :build do |subject|
subject_grand_parent = Subject.create(name: Forgery(:name).company_name)
subject_parent = subject_grand_parent.children.create(name: Forgery(:name).company_name)
subject.parent = subject_parent
subject.ancestry_depth = 2
end
end
end
Structure
Factory:
after(:build) do |structure|
structure.subjects << FactoryGirl.build(:subject)
structure.subjects << FactoryGirl.build(:subject_children)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow