如何使用工厂女孩创建具有has_many的关联列表,并在创建时使用验证

Bli*_*zzo 18 ruby-on-rails-3 factory-bot

在Rails应用程序中,给出了三个模型User,Article和Reviewer,它们具有以下关系和验证:

class User < ActiveRecord::Base
  has_many :articles
  has_many :reviewers
end

class Reviewer < ActiveRecord::Base
  belongs_to :user
  belongs_to :article
end

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :reviewers

  validate :has_reviewers?

  def has_reviewers?
    errors.add(:base, "article must have at least one reviewer.") if self.reviewers.blank?
  end
end
Run Code Online (Sandbox Code Playgroud)

以下工厂使用较新的DSL:

FactoryGirl.define do

  factory :user do
    name { (8...20).map{ ('a'..'z').to_a[rand(26)] }.join }
    age  { Kernel.rand(100) }
  end

  factory :article do
    body "This is the article content"
    title "This is the title"
    user
    after_create do |article|
      article.reviewers = create_list(:user, 2)
    end
  end

  factory :reviewer do
    user
    article
    state { ["published","draft","rejected","archived"][Kernel.rand(4)] }
  end

end
Run Code Online (Sandbox Code Playgroud)

创建文章的工厂不起作用,因为在创建审阅者之前验证失败:

> FactoryGirl.create(:article)
ActiveRecord::RecordInvalid: Validation failed: article must have at least one reviewer.
Run Code Online (Sandbox Code Playgroud)

我已经做出了比尝试克服这个障碍更多的尝试,但我被卡住了!我的一个想法就是创建这样的评论者:

  factory :article do
    body "This is the article content"
    title "This is the title"
    user
    reviewers {|a| [FactoryGirl.create(:reviewer, article: a)] }
  end
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,"a"不是实例.所以这也不像以前那样有效.

Bli*_*zzo 22

我将这个转发到Factory Girl github页面作为一个问题,并且我一直在寻找答案:

before_create do |article|
  article.reviewers << FactoryGirl.build(:reviewer, article: article)
end
Run Code Online (Sandbox Code Playgroud)

关键是在before_create中进行,因此验证尚未解决,并确保将新创建的审阅者推送到正在创建的实例的评论列表中.感谢Unixmonkey做出回应并让我尝试新事物:)

https://github.com/thoughtbot/factory_girl/issues/369#issuecomment-5490908


Uni*_*key 3

factory :article do
  reviewers {|a| [a.association(:reviewer)] }
end
Run Code Online (Sandbox Code Playgroud)

或者

factory :article do
  before_create do |a|
    FactoryGirl.create(:reviewer, article: a)
  end
end
Run Code Online (Sandbox Code Playgroud)