Ruby on rails minitest的唯一性检验
我在RubyonRails上使用minitest。下面是我的模型Ruby on rails minitest的唯一性检验,ruby-on-rails,ruby,model,minitest,Ruby On Rails,Ruby,Model,Minitest,我在RubyonRails上使用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,
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
我试着写一个模型测试,我想写一个测试来控制pin字段是否唯一。我该怎么做?有什么想法吗
我尝试编写一个测试,如下所示:
it 'must not be valid' do
person_copy = person.dup
person.save
person_copy.save
end
您可以这样编写测试:
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
您可以使用并测试错误是否正确(关于唯一性):
考虑到已经设置了固定装置,您可以执行以下操作:
test 'pin must be unique' do
new_person = Person.new(@person.attributes)
refute new_person.valid?
end
使用
person\u copy.save
在唯一性为false时引发错误。使用RSpec,您可以使用一些很好的帮助程序,如expect{person\u copy.save!}。要引发\u错误
我在尝试此NoMethodError时遇到以下错误:未定义的方法“must\u raise”for#
test 'pin must be unique' do
new_person = Person.new(@person.attributes)
refute new_person.valid?
end