Get two associations within a Factory to share another association

后端 未结 6 1644
情书的邮戳
情书的邮戳 2021-02-12 14:57

I\'ve got these 5 models: Guardian, Student, Relationship, RelationshipType and School. Between them, I\'ve got these associations

class Guardian < ActiveReco         


        
6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 15:24

    I'd use transient & dependent attributes in this case:

    FactoryGirl.define do
      factory :relationship do
        transient do
          school { create(:school) }
          # now you can even override the school if you want!
        end
    
        guardian { create(:guardian, school: school) }
        student { create(:student, school: school) }
        relationship_type RelationshipType.first
      end
    end
    

    Usage:

    relationship = FactoryGirl.create(:relationship)
    
    relationship.guardian.school == relationship.student.school
    # => true
    

    And you can even override the school if you want:

    awesome_school = FactoryGirl.create(:school)
    awesome_relationship = FactoryGirl.create(:relationship, school: awesome_school)
    
    awesome_relationship.guardian.school == awesome_school
    # => true
    awesome_relationship.student.school == awesome_school
    # => true
    

提交回复
热议问题