在 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
以下工厂使用较新的 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.
为了克服这个障碍,我做了比我想承认的更多的尝试,但我被困住了!我的一个想法是创建这样的审阅者:
factory :article do
body "This is the article content"
title "This is the title"
user
reviewers {|a| [FactoryGirl.create(:reviewer, article: a)] }
end
但在这种情况下,“a”不是实例。所以这也不起作用,就像以前一样。