A developer notebook I should have started 10 years ago..

FactoryBot traits for model association

TLDR

How can I specify traits for model associations in factory_bot?

FactoryBot.define do
  factory :user do
    # `public_company` is the model reference name
    # `company` is the association factory name
    # `public` is the trait name
    association :public_company, factory: %i[company public]
  end
end

FactoryBot traits

Let’s define User.

class User < ApplicationRecord
  belongs_to :company
end

Easy peasy for the related factory.

FactoryBot.define do
  factory :user do
    association :company # explicit association
  end
end

# or

FactoryBot.define do
  factory :user do
    company # implicit association
  end
end

Now, we’re updating the class name of the relation.

class User < ApplicationRecord
  belongs_to :public_company, class_name: "Company"
end

In the factory, we must set the factory param.

FactoryBot.define do
  factory :user do
    association :public_company, factory: :company
  end
end

And finally, if we need to specify the trait of the used factory.

FactoryBot.define do
  factory :company do
    trait :public do
      public { true }
    end
  end
end

We must set the factory param with an array of [:factory_name, :trait_name].

FactoryBot.define do
  factory :user do
    association :public_company, factory: %i[company public]
  end
end

Resources: