I\'ve got these 5 models: Guardian, Student, Relationship, RelationshipType and School. Between them, I\'ve got these associations
class Guardian < ActiveReco
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)
.