FactoryGirl and polymorphic associations FactoryGirl and polymorphic associations ruby-on-rails ruby-on-rails

FactoryGirl and polymorphic associations


Although there is an accepted answer, here is some code using the new syntax which worked for me and might be useful to someone else.

spec/factories.rb

FactoryGirl.define do  factory :musical_user, class: "User" do    association :profile, factory: :musician    #attributes for user  end  factory :artist_user, class: "User" do    association :profile, factory: :artist    #attributes for user  end  factory :artist do    #attributes for artist  end  factory :musician do    #attributes for musician  endend

spec/models/artist_spec.rb

before(:each) do  @artist = FactoryGirl.create(:artist_user)end

Which will create the artist instance as well as the user instance. So you can call:

@artist.profile

to get the Artist instance.


Use traits like this;

FactoryGirl.define do    factory :user do        # attributes_for user        trait :artist do            association :profile, factory: :artist        end        trait :musician do            association :profile, factory: :musician        end    endend

now you can get user instance by FactoryGirl.create(:user, :artist)


Factory_Girl callbacks would make life much easier. How about something like this?

Factory.define :user do |user|  #attributes for userendFactory.define :artist do |artist|  #attributes for artist  artist.after_create {|a| Factory(:user, :profile => a)}endFactory.define :musician do |musician|  #attributes for musician  musician.after_create {|m| Factory(:user, :profile => m)}end