FactoryGirl and polymorphic associations

后端 未结 6 1472
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 14:18

The design

I have a User model that belongs to a profile through a polymorphic association. The reason I chose this design can be found here. To summarize, there a

6条回答
  •  天涯浪人
    2020-12-23 15:18

    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
      end
    end
    

    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.

提交回复
热议问题