FactoryGirl:访问特征内的关联数据

时间:2019-01-05 10:35:12

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

我有一个付款模型,一个发票模型和一个用于将付款分配给发票的联接表invoice_payments。 我正在这样创建我的付款工厂:-

FactoryGirl.define do
  factory :payment do
    customer
    user
    date Date.today
    amount 300
    discount 50
    mode "Cash"

    trait :with_invoice_payments do
      invoice = create(:invoice, customer: customer)
      invoice_payments_attributes do 
        attributes = []
        attributes << attributes_for(:invoice_payment, invoice_id: invoice.id)
      end
    end
  end
end

现在,我的发票应具有与正在创建的付款相同的customer_id。这就是为什么我invoice = create(:invoice, customer: customer)希望这将创建与该付款客户相同的客户的发票。但这给了我错误wrong number of arguments (given 3, expected 1..2) 如何制作发票,以使invoice.customer_id成为该特征本身中与该付款相关联的customer_id?

1 个答案:

答案 0 :(得分:0)

找到我的解决方案:-

FactoryGirl.define do
  factory :payment do
    customer
    user
    date Date.today
    amount 300
    discount 50
    mode "Cash"

    trait :with_invoice_payments do
      invoice_payments_attributes do 
        attributes = []
        attributes << attributes_for(:invoice_payment, invoice_id: create(:invoice, 
       customer: customer).id)
      end
    end
  end
end