应该无法正确验证区分大小写的唯一性
Shoulda cannot properly validate case-sensitive unique
使用 shoulda
和 FactoryGirl
来测试模型验证。
工厂
FactoryGirl.define do
factory :tag do
value { Faker::Lorem.word }
user
end
end
标签模型
class Tag < ApplicationRecord
validates :value,
presence: true,
uniqueness: { case_sensitive: false }
belongs_to :user
has_and_belongs_to_many :cards
end
标签规范
RSpec.describe Tag, type: :model do
describe 'validations' do
it { should validate_presence_of(:value) }
it { should validate_uniqueness_of(:value) }
end
describe 'associations' do
it { should belong_to(:user) }
# it { should have_and_belong_to_many(:cards) }
end
end
我 运行 测试时出现以下错误,
Failures:
1) Tag validations should validate that :value is case-sensitively unique
Failure/Error: it { should validate_uniqueness_of(:value) }
Tag did not properly validate that :value is case-sensitively unique.
After taking the given Tag, setting its :value to ‹"an arbitrary
value"›, and saving it as the existing record, then making a new Tag
and setting its :value to a different value, ‹"AN ARBITRARY VALUE"›,
the matcher expected the new Tag to be valid, but it was invalid
instead, producing these validation errors:
* value: ["has already been taken"]
* user: ["must exist"]
# ./spec/models/tag_spec.rb:6:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
测试case_insensitive
的正确方法是使用下面的匹配器,
it { should validate_uniqueness_of(:value).case_insensitive }
你也可以写成ignoring_case_sensitivity
:
it { should validate_uniqueness_of(:value).ignoring_case_sensitivity }
使用 shoulda
和 FactoryGirl
来测试模型验证。
工厂
FactoryGirl.define do
factory :tag do
value { Faker::Lorem.word }
user
end
end
标签模型
class Tag < ApplicationRecord
validates :value,
presence: true,
uniqueness: { case_sensitive: false }
belongs_to :user
has_and_belongs_to_many :cards
end
标签规范
RSpec.describe Tag, type: :model do
describe 'validations' do
it { should validate_presence_of(:value) }
it { should validate_uniqueness_of(:value) }
end
describe 'associations' do
it { should belong_to(:user) }
# it { should have_and_belong_to_many(:cards) }
end
end
我 运行 测试时出现以下错误,
Failures:
1) Tag validations should validate that :value is case-sensitively unique
Failure/Error: it { should validate_uniqueness_of(:value) }
Tag did not properly validate that :value is case-sensitively unique.
After taking the given Tag, setting its :value to ‹"an arbitrary
value"›, and saving it as the existing record, then making a new Tag
and setting its :value to a different value, ‹"AN ARBITRARY VALUE"›,
the matcher expected the new Tag to be valid, but it was invalid
instead, producing these validation errors:
* value: ["has already been taken"]
* user: ["must exist"]
# ./spec/models/tag_spec.rb:6:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
测试case_insensitive
的正确方法是使用下面的匹配器,
it { should validate_uniqueness_of(:value).case_insensitive }
你也可以写成ignoring_case_sensitivity
:
it { should validate_uniqueness_of(:value).ignoring_case_sensitivity }