ruby-on-rails – FactoryGirl before(:create)回调没有创建关联

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – FactoryGirl before(:create)回调没有创建关联前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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
验证失败订单行不能为空

UPDATE

然而,我可以成功地执行以下操作,但显然只能完成创建一个:

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

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

解决方法

您需要将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

猜你在找的Ruby相关文章