5

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

楷模:

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)

有没有一种新方法可以创建has_many与 FactoryGirl 关联的模型?

4

2 回答 2

3

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

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

于 2013-07-13T04:06:50.337 回答
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

于 2017-02-17T13:24:48.430 回答