我的分类模型包含以下内容:
# Mass assignable fields
attr_accessible :name, :classification, :is_shown
# Add validation
validates :name, :presence => true, :uniqueness => true
validates :classification, :presence => true
使用rspec + capybara,我想测试唯一性验证器。
Taxonomy.create(:name => 'foo', :classification => 'activity').save!(:validate => false)
it { should validate_uniqueness_of(:name).scoped_to(:classification) }
此测试失败,出现以下错误:
Failure/Error: it { should validate_uniqueness_of(:name).scoped_to(:classification) }
Expected errors to include "has already been taken" when name is set to "foo", got errors: ["name has already been taken (\"foo\")", "classification is not included in the list (:activitz)"] (with different value of classification)
# ./spec/models/taxonomy_spec.rb:14:in `block (3 levels) in <top (required)>'
在我看来,测试应该通过。我错过了什么?
答案 0 :(得分:0)
这不是Capybara的问题,因为这是在处理模型规范。我假设您使用的是shoulda matchers gem,以便使用这些特殊的ActiveRecord
验证匹配器。
给出一个类似你的例子的模型:
class Taxonomy < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => true
validates :classification, :presence => true
end
您将拥有以下规范:
describe Taxonomy do
it { should validate_presence_of(:name) }
it { should validate_uniqueness_of(:name) }
it { should validate_presence_of(:classification) }
end
但是,如果您确实希望将名称字段的唯一性限定为分类:
class Taxonomy < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => { :scope => :classification }
validates :classification, :presence => true
end
......以及以下规范:
describe Taxonomy do
it { should validate_presence_of(:name) }
it { should validate_uniqueness_of(:name).scoped_to(:classification) }
it { should validate_presence_of(:classification) }
end