在FactoryGirl中从父级设置子属性

时间:2013-05-12 22:49:40

标签: ruby-on-rails ruby factory-bot

如何设置依赖于FactoryGirl的依赖属性?

FactoryGirl.define do
  factory :line_item do
    quantity 1
    price 30 # I want price to come from the product association: self.product.price

    cart
    order
    product
  end
end

我尝试了这个,但它不起作用:

  factory :line_item do |f|
    f.quantity 1

    f.cart
    f.order
    f.product
    after_build do |line_item|
      line_item.price = line_item.product.price
    end
  end

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

FactoryGirl.define do   
  factory :line_item do
    quantity 1
    price { product.price }

    cart
    order
    product   
  end 
end