Search code examples
rspecfactory-botrspec-rails

Factory Bot Association Attribute Depends on Neighbor Association


My application is Rails 6.1 with Factory Bot and RSpec.

I have an order model with two different belongs-to associations: Company and Contact. Contact also belongs to Company, creating a sort of circular association.

In my Factory for order I have:

FactoryBot.define do
  factory :order do
    factory :order_with_po do
      po_number {1234}
    end

    company
    contact
  end
end

However, I get issues because the contact that gets created uses factory bot which in turn creates a new company for that contact. A different company is also created at the same time for the order. These two companies do not match, but there is a validation on the order that makes sure the contact's company is the same as the order's company.

How can I specify that the contact created uses the same company that the order creates? What is best practice?


Solution

  • After many trial and errors, I found the following works:

    FactoryBot.define do
      factory :order do
        factory :order_with_po do
          po_number {1234}
        end
    
        company
    
        before(:create) do |order|
          order.contact_id = FactoryBot.create(:contact, company_id: order.company_id).id
        end
      end
    end
    

    It's a little strange feeling, but it's how Factory Bot works. After it builds the order, it has the company already created and, as such, you can reference the company ID in the before create hook. I put that to use to specify the company ID for the order's contact.