Get two associations within a Factory to share another association

后端 未结 6 1648
情书的邮戳
情书的邮戳 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条回答
  •  逝去的感伤
    2021-02-12 15:34

    This answer is the first result on Google for 'factory girl shared association' and the answer from santuxus really helped me out :)

    Here's an update with the syntax from the latest version of Factory Girl in case anyone else stumbles across it:

    FactoryGirl.define do
      factory :relationship do
        guardian
        relationship_type RelationshipType.first
    
        after(:build) do |relationship|
          relationship.student = FactoryGirl.create(:student, school: relationship.guardian.school) unless relationship.student.present?
        end
      end
    end
    

    The unless clause prevents student from being replaced if it's been passed into the factory with FactoryGirl.create(:relationship, student: foo).

提交回复
热议问题