Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl has_many association

I'm using the FactoryGirl example for has_many relationships from http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl. Specifically, the example is:

Models:

class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :article
end

Factories:

factory :article do
  body 'password'

  factory :article_with_comment do
    after_create do |article|
      create(:comment, article: article)
    end
  end
end

factory :comment do
  body 'Great article!'
end

When I run that same example (with the proper schema, of course), an error is thrown

2.0.0p195 :001 > require "factory_girl_rails"
 => true
2.0.0p195 :002 > article = FactoryGirl.create(:article_with_comment)
ArgumentError: wrong number of arguments (3 for 1..2)

Is there a new way to create models with has_many associations with FactoryGirl?

like image 989
Zach Latta Avatar asked Oct 03 '22 13:10

Zach Latta


2 Answers

I think the api has changed significantly since then. Have a look at the section on associations here for further guidance:

https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

like image 185
muttonlamb Avatar answered Oct 06 '22 05:10

muttonlamb


As of today your example would looks like this:

factory :article do
  body 'password'

  factory :article_with_comment do
    after(:create) do |article|
      create_list(:comment, 3, article: article)
    end
  end
end

factory :comment do
  body 'Great article!'
end

Or if you need flexibility on a number of comments:

factory :article do
  body 'password'

  transient do
    comments_count 3
  end

  factory :article_with_comment do
    after(:create) do |article, evaluator|
      create_list(:comment, evaluator.comments_count, article: article)
    end
  end
end

factory :comment do
  body 'Great article!'
end

Then use like

create(:article_with_comment, comments_count: 15)

For more details please refer to associations section in getting started guide: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

like image 30
wik Avatar answered Oct 06 '22 03:10

wik