我在Ruby on Rails上使用minitest。以下是我的模特。
require 'mongoid'
class Person
include Mongoid::Document
index({ pin: 1 }, { unique: true, name: "pin_index" })
field :first_name
field :last_name
field :pin
validates :pin, presence: true, uniqueness: true
validates :first_name, presence: true
validates :last_name, presence: true
end
我尝试编写模型测试。我想编写一个控制引脚字段是否唯一的测试。我怎样才能做到这一点?有什么想法吗?
我尝试编写如下测试:
it 'must not be valid' do
person_copy = person.dup
person.save
person_copy.save
end
答案 0 :(得分:0)
您可以像这样编写测试:
it 'must have unique pin' do
person_copy = person.dup
proc { person_copy.save! }.must_raise(Mongoid::Errors::Validations)
person_copy.errors.must_include(:pin)
end
答案 1 :(得分:0)
您可以使用assert_includes
和assert_same
来测试错误是否正确(关于唯一性):
it 'must not be valid' do
person_copy = person.dup
person.save
person_copy.save
assert_includes person.errors, :pin
assert_same person.errors[:pin], "pin is not unique (replace with actual error message)"
end
答案 2 :(得分:0)
考虑到你已经设置了一个灯具,你可以这样做:
test 'pin must be unique' do
new_person = Person.new(@person.attributes)
refute new_person.valid?
end