Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails minitest的唯一性检验_Ruby On Rails_Ruby_Model_Minitest - Fatal编程技术网

Ruby on rails 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,

我在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, 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