Search code examples
ruby-on-railsfactory-botactivemodel

FactoryGirl - override association with trait?


Let's say I have the following ActiveRecord models:

class Car
  belongs_to :driver
end

class Driver
  # Has attribute :name
  has_one :car
end

And I define a couple of factories using these models:

FactoryGirl.define do
  factory :car do
    association :driver

    trait :fast_car do
      association :driver, :fast
    end
  end
end

FactoryGirl.define do
  factory :driver do
    name 'Jason'

    trait :fast do
      name 'Mario'
    end
  end
end

When I execute the following code:

car = FactoryGirl.create(:car, :fast_car)

I would expect car.driver.name to equal Mario, but instead it equals Jason. This leads me to believe that you can't use traits to override associations for factories. Is this true? If so, what would be the proper way to override the associated Driver for a fast car?


Solution

  • Fortunately, you can. You need to specify the factory keyword for an association with an array, where the first element is the name of the factory that you want to use for the association and the rest elements are the factory's traits:

    FactoryGirl.define do
      factory :car do
        association :driver
    
        trait :fast_car do
          association :driver, factory: [:driver, :fast]
        end
      end
    end
    
    FactoryGirl.define do
      factory :driver do
        name 'Jason'
    
        trait :fast do
          name 'Mario'
        end
      end
    end