FactoryGirl before(:create) callback not creating associations
activerecord, rails-activerecord, ruby, ruby-on-rails, ruby-on-rails-3
Solution
You need to put your OrderLine factory into the order record like this
Factory :order do
...
ignore do
number_or_order_lines 1
end
before(:create) do |order, evaluator|
order.order_lines << (FactoryGirl.create :order_line, order: order)
end
end
Problem
I have a FactoryGirl factory, that creates a `Order` but the before(:create) callback does not create the associated factory object: Parent Class ``` class Order < ActiveRecord::Base attr_accessible :tax, :total has_many :order_lines validates :user, presence: true validates :order_lines , presence: true end ``` Child Class ``` class OrderLine < ActiveRecord::Base attr_accessible :order, :product, :qty belongs_to :order belongs_to :product ... ... validates :order, presence: true end ``` Factory ``` Factory :order do ... ignore do number_or_order_lines 1 end before(:create) do |order, evaluator| FactoryGirl.create_list :order_line, evaluator.number_or_order_lines, order: order end end Factory :order_line do association :user association :order ... end ``` PROBLEM In my rspec test, if I create a order object: ``` describe Order do before {@order = FactoryGirl.create(:order) } => #throws error (see below) end ``` ERROR ActiveRecord::RecordInvalid Validation failed Order Lines can't be blank UPDATE I can however successfully do the following but obviously only accomplishes creating one: ``` after(:build) do |order, evaluator| order.order_lines << FactoryGirl.build(:order_line, order: order) end ``` Hypothesis - I can see where the `create_list` might be attempting to save the `OrderLine` which would cause an error since the parent hasn't been saved - but I don't know if it still returns a OrderLine object that is just in an invalid state and therefore the order_lines collection on the order object should still not be empty.