FactoryGirl before(:create)回调没有创建关联

时间:2013-04-02 14:07:07

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord rails-activerecord

我有一个FactoryGirl工厂,它创建一个Order但是before(:create)回调不会创建关联的工厂对象:

父类

class Order < ActiveRecord::Base
  attr_accessible :tax, :total
  has_many :order_lines

  validates :user, presence: true
  validates :order_lines , presence: true
end

儿童班

class OrderLine < ActiveRecord::Base
  attr_accessible :order, :product, :qty
  belongs_to :order
  belongs_to :product
  ...
  ...
  validates :order, presence: true
end

工厂

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

问题

在我的rspec测试中,如果我创建一个订单对象:

describe Order do
  before {@order = FactoryGirl.create(:order) }  => #throws error (see below)
end

错误 的ActiveRecord :: RecordInvalid 验证失败订单行不能为空

更新

但我可以成功地做到以下几点,但显然只能完成创建一个:

after(:build) do |order, evaluator|
  order.order_lines << FactoryGirl.build(:order_line, order: order)
end

假设 - 我可以看到create_list可能会尝试保存OrderLine,因为父母尚未保存会导致错误 - 但我不知道不知道它是否仍然返回一个处于无效状态的OrderLine对象,因此订单对象上的order_lines集合仍然不应为空。

1 个答案:

答案 0 :(得分:7)

您需要将OrderLine工厂放入订单记录中,如此

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