Search code examples
ruby-on-railsrubyfactory-botancestry

FactoryGirl + Ancestry with two level deep


Basically:

  • I have a Structure model that has many Subjects.
  • 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

  • Have you considered using after(:build) blocks ?