Skip to content

Instantly share code, notes, and snippets.

@jackfranklin
Created June 17, 2012 16:08
Show Gist options
  • Save jackfranklin/2944968 to your computer and use it in GitHub Desktop.
Save jackfranklin/2944968 to your computer and use it in GitHub Desktop.
creating has_many relationships in FactoryGirl
#models/discussion.rb
has_many :posts
#models/post.rb
belongs_to :discussion
#spec/factories/discussions.rb
FactoryGirl.define do
factory :discussion do
sequence(:title) { |n| "My Discussion#{n}" }
user
category
#eval is all the attributes on discussion
#need to do it on create so it creates all the discussion attributes correctly first
after(:create) do |discussion, eval|
discussion.posts = create_list(:post, 1, user: eval.user, discussion: discussion)
end
end
end
#spec/factories/posts.rb
FactoryGirl.define do
factory :post do
sequence(:content) { |n| "Hey this is some content #{n}" }
user
discussion
end
end
# good reference:
# http://icelab.com.au/articles/factorygirl-and-has-many-associations/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment