Kelvin Matheus
Kelvin Matheus

Reputation: 147

FactoryBot Rails - Using another factory outside a factory definition

I have the following factory:

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

When I try to run the test I got the following error:

ArgumentError:
  Factory not registered: legal_person_account

The factory is not identifying another factory outside the Factory :charge_transaction definition.

I need this behavior because I need to use the same :legal_person_account factory into two fields of this charge_transaction factory, the :origem_account_id and :transactional_code fields.

Could someone help me, please?

Upvotes: 1

Views: 2473

Answers (2)

Thanh
Thanh

Reputation: 8624

I think you can not do this. I prefer a way that you create legal_person_account first and then assign it to charge_transaction in your test, ex:

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

and in your charge_transaction, define a callback:

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

so charge_transaction still uses the same origem_account.

Upvotes: 1

Subash
Subash

Reputation: 3168

you need to define or register a factory for legal_person_account so within your FactoryBot.define block you should add a

factory :legal_person_account do
end

and you should be good to go

Upvotes: 0

Related Questions