Created
June 17, 2012 16:08
-
-
Save jackfranklin/2944968 to your computer and use it in GitHub Desktop.
creating has_many relationships in FactoryGirl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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