在Rails应用程序,给出三种型号的用户,文章和审阅与下面的关系和验证:
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
但在此背景下,“一”是不是实例。 这样也不行,像以前那样。