Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl before(:create) callback not creating associations

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.

like image 508
pghtech Avatar asked Apr 02 '13 14:04

pghtech


1 Answers

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
like image 164
MilesStanfield Avatar answered Oct 16 '22 05:10

MilesStanfield