Skip to content

Instantly share code, notes, and snippets.

@elle
Created October 29, 2012 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elle/3970695 to your computer and use it in GitHub Desktop.
Save elle/3970695 to your computer and use it in GitHub Desktop.
STI and circular referencial association
FactoryGirl.define do
sequence :first_name { |n| "John #{n}" }
sequence :email { |n| "john#{n}@example.com" }
factory :employee do
first_name { generate(:first_name) }
last_name 'Smith'
email { generate(:email) }
position { Settings.employee.positions.first }
staff_number { "%06d" % (rand * 1000000) } # random 6 digit number
supervisor nil
factory :supervisor do
first_name 'Manager'
sequence(:email) { |n| "manager#{n}@example.com" }
end
# Option 2: which I have not used yet but this is from Inheritance section
# ref: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md
# You can also assign the parent explicitly:
#factory :post do
# title "A title"
#end
#factory :approved_post, parent: :post do
# approved true
#end
factory :employee_with_supervisor, parent: :supervisor do
# not sure what should come here
end
end
trait :with_supervisor do
before :create do
supervisor { FactoryGirl.create :supervisor }
end
end
end
# then use like so:
employee = create(:employee, :with_supervisor) # using the trait we created
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment