简体   繁体   中英

uniqueness test on minitest

I use minitest on Ruby on Rails. Below is my model.

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

I try to write model test.I want to write a test that controls whether pin field is unique or not. How can i do this? Any idea?

I try to write a test like below:

it 'must not be valid' do
  person_copy = person.dup
  person.save
  person_copy.save
end

You can write the test like this:

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

You can use assert_includes and assert_same to test the error is the right one (about uniqueness):

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

Considering you have a fixture already set, you can just do this:

test 'pin must be unique' do
  new_person = Person.new(@person.attributes)
  refute new_person.valid?
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM