FactoryBot Rails - 在工厂定义之外使用另一个工厂

时间:2018-02-05 21:25:31

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

我有以下工厂:

setInterval

当我尝试运行测试时出现以下错误:

FactoryBot.define do
  origem_account = FactoryBot.create(:legal_person_account)

  Factory :charge_transaction, class: ChargeTransaction, parent: :transaction do
    type { :charge }

    trait :valid_attributes do
      value { 500 }
      origem_account_id { origem_account.id }

      transactional_code { origem_account.id.to_s + '-teste' }
      origem_account_value_before_transaction nil
      destination_account_id nil
      destination_account_value_before_transaction nil
    end

  end
end

工厂未确定工厂:charge_transaction 定义之外的其他工厂。

我需要这种行为,因为我需要在此charge_transaction工厂的两个字段中使用相同的:legal_person_account 工厂,:origem_account_id :transactional_code fields。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您需要为legal_person_account定义或注册工厂,以便在FactoryBot.define区块中添加

factory :legal_person_account do
end

你应该好好去

答案 1 :(得分:0)

我认为你不能这样做。我更喜欢您首先创建legal_person_account然后在测试中将其分配给charge_transaction的方式,例如:

let(:origem_account) { create :legal_person_account }
let(:charge_transaction) { create :charge_transaction, origem_account:origem_account }

并在charge_transaction中定义回调:

factory :charge_transaction do
  ...
  after(:build) { |transaction| transaction.transactional_code =  transaction.origem_account_id.to_s + 
  -teste }
end

所以charge_transaction仍然使用相同的origem_account