Permalink
Browse files

Add tests and documentation for has_many relationships

  • Loading branch information...
1 parent 791591b commit 9c6c252d0fb58ba6321d8db56778bb3469ff5a77 @joshuaclayton joshuaclayton committed Feb 17, 2012
Showing with 86 additions and 0 deletions.
  1. +45 −0 GETTING_STARTED.md
  2. +41 −0 spec/acceptance/create_list_spec.rb
View
45 GETTING_STARTED.md
@@ -260,6 +260,51 @@ post.new_record? # => true
post.author.new_record? # => true
```
+Generating data for a `has_many` relationship is a bit more involved,
+depending on the amount of flexibility desired, but here's a surefire example
+of generating associated data.
+
+```ruby
+FactoryGirl.define do
+
+ # post factory with a `belongs_to` association for the user
+ factory :post do
+ title "Through the Looking Glass"
+ user
+ end
+
+ # user factory without associated posts
+ factory :user do
+ name "John Doe"
+
+ # user_with_posts will create post data after the user has been created
+ factory :user_with_posts do
+ # posts_count is declared as an ignored attribute and available in
+ # attributes on the factory, as well as the callback via the evaluator
+ ignore do
+ posts_count 5
+ end
+
+ # the after_create yields two values; the user instance itself and the
+ # evaluator, which stores all values from the factory, including ignored
+ # attributes; `create_list`'s second argument is the number of records
+ # to create and we make sure the user is associated properly to the post
+ after_create do |user, evaluator|
+ FactoryGirl.create_list(:post, evaluator.posts_count, :user => user)
+ end
+ end
+ end
+end
+```
+
+This allows us to do:
+
+```ruby
+FactoryGirl.create(:user).posts.length # 0
+FactoryGirl.create(:user_with_posts).posts.length # 5
+FactoryGirl.create(:user_with_posts, :posts_length => 15).posts.length # 15
+```
+
Inheritance
-----------
View
41 spec/acceptance/create_list_spec.rb
@@ -39,3 +39,44 @@
end
end
end
+
+describe "multiple creates and ignored attributes to dynamically build attribute lists" do
+ before do
+ define_model('User', :name => :string) do
+ has_many :posts
+ end
+
+ define_model('Post', :title => :string, :user_id => :integer) do
+ belongs_to :user
+ end
+
+ FactoryGirl.define do
+ factory :post do
+ title "Through the Looking Glass"
+ user
+ end
+
+ factory :user do
+ name "John Doe"
+
+ factory :user_with_posts do
+ ignore do
+ posts_count 5
+ end
+
+ after_create do |user, evaluator|
+ FactoryGirl.create_list(:post, evaluator.posts_count, :user => user)
+ end
+ end
+ end
+ end
+ end
+
+ it "generates the correct number of posts" do
+ FactoryGirl.create(:user_with_posts).posts.length.should == 5
+ end
+
+ it "allows the number of posts to be modified" do
+ FactoryGirl.create(:user_with_posts, :posts_count => 2).posts.length.should == 2
+ end
+end

0 comments on commit 9c6c252

Please sign in to comment.