I have a FactoryGirl factory that creates an Order , but the before (: create) callback does not create an 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
Kids 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 an order object:
describe Order do before {@order = FactoryGirl.create(:order) } =>
ERROR ActiveRecord :: RecordInvalid Validation failed. Order lines cannot be empty.
UPDATE
However, I can successfully do the following, but obviously only does it:
after(:build) do |order, evaluator| order.order_lines << FactoryGirl.build(:order_line, order: order) end
Hypothesis . I can see where create_list can try to save the OrderLine , which will cause an error because the parent was not saved, but I donβt know, it still returns an OrderLine object that is only in an invalid state, and therefore the order_lines collection in the order object is still will not be empty.