FactoryGirl and polymorphic associations

后端 未结 6 1501
爱一瞬间的悲伤
爱一瞬间的悲伤 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 14:53

    It seems that polymorphic associations in factories behave the same as regular Rails associations.

    So there is another less verbose way if you don't care about attributes of model on "belongs_to" association side (User in this example):

    # Factories
    FactoryGirl.define do
      sequence(:email) { Faker::Internet.email }
    
      factory :user do
        # you can predefine some user attributes with sequence
        email { generate :email }
      end
    
      factory :artist do
        # define association according to documentation
        user 
      end
    end
    
    # Using in specs    
    describe Artist do      
      it 'created from factory' do
        # its more naturally to starts from "main" Artist model
        artist = FactoryGirl.create :artist        
        artist.user.should be_an(User)
      end
    end
    

    FactoryGirl associations: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

提交回复
热议问题