Search code examples
ruby-on-railspolymorphismassociationsfactory-botbelongs-to

FactoryGirl – Retrieving attributes from another factory in a polymorphic association


I have a Board that belongs to an Artist. So far I was able to setup this polymorphic association in my boards factory as so:

FactoryGirl.define do
  factory :board do
    association :boardable, factory: :artist
    boardable_type "Artist"
  end
end

The pattern I have setup in my actual app requires the name of my board to be the name of the artist it belongs to. I tried doing something like:

name boardable.name

But ended up getting this error:

ArgumentError: Trait not registered: boardable

What is usually the best way to retrieve attributes within a belongs_to/polymorphic association?


Solution

  • Polymorphic associations do not need an explicit association to be declared in FactoryGirl. The following has been verified and will work:

    FactoryGirl.define do
      factory :board do
        boardable factory: :artist
        name { boardable.name }
      end
    end
    

    As far as your Board's name is concerned, make sure to wrap the attribute value in brackets, or FactoryGirl might treat it as a trait :) The boardable_type attribute of your Board will be automatically set to the boardable's class, so it doesn't even need declaring.