1

我有一个分类模型,其中包含以下内容:

# 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)>'

在我看来,测试应该通过了。我错过了什么?

4

1 回答 1

1

这不是 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

但是,如果您真的希望将 name 字段的唯一性限定为分类:

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
于 2013-04-15T18:27:52.553 回答