Search code examples
ruby-on-rails-3ruby-on-rails-pluginsfactory-bot

FactoryGirl and variables inside factory


What if I want to do something like

FactoryGirl.define do
  factory :leaf do
  end

  factory :tree do
    l = []
    leaves do
      l << Factory.build(:leaf)
      //some app logic here
      l
    end
    root l.first
  end
end

How should I write this to make it work?

And maybe somebody have a link with really complex and untrivial examples of using FactoryGirl?

Thank you.


Solution

  • I'm not 100% sure I've followed what you're asking but would this work?

    factory :tree do
        after_build { |tree|  
            # build your leaves here
            # ...
    
            tree.root l.first
        }
    end