Rails アプリケーションで、User、Article、Reviewer の 3 つのモデルが与えられ、次の関係と検証が行われます。
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
そして、新しい 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
レビュアーが作成される前に検証が失敗するため、記事を作成するファクトリは機能しません。
> FactoryGirl.create(:article)
ActiveRecord::RecordInvalid: Validation failed: article must have at least one reviewer.
私はこのハードルを克服しようとして認めたくないほど多くの試みをしましたが、立ち往生しています! 私が思いついたアイデアの 1 つは、次のようなレビュアーを作成することでした。
factory :article do
body "This is the article content"
title "This is the title"
user
reviewers {|a| [FactoryGirl.create(:reviewer, article: a)] }
end
ただし、このコンテキストでは、「a」はインスタンスではありません。そのため、以前のようには機能しません。