FactoryGirl has_many协会

时间:2013-07-13 03:24:48

标签: ruby-on-rails factory-bot

我正在使用来自http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girlhas_many关系的FactoryGirl示例。具体来说,例子是:

型号:

class Article < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :article
end

工厂:

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

当我运行相同的示例时(当然使用正确的模式),会抛出错误

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)

是否有新方法可以创建与FactoryGirl has_many关联的模型?

2 个答案:

答案 0 :(得分:3)

我认为api自那时起发生了重大变化。请查看此处的关联部分以获得进一步的指导:

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

答案 1 :(得分:1)

截至今天,您的示例将如下所示:

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

或者如果你需要灵活处理一些评论:

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

然后使用

create(:article_with_comment, comments_count: 15)

有关详细信息,请参阅入门指南中的关联部分: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations