0

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
miyamotomusashi
  • 531
  • 7
  • 22
  • use `person_copy.save!` to raise an error, when uniqueness is false. With RSpec you could use some nice helpers like `expect { person_copy.save! }.to raise_error` – 23tux Apr 12 '13 at 13:57

3 Answers3

0

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
toro2k
  • 19,020
  • 7
  • 64
  • 71
  • I am getting the following error when trying this `NoMethodError: undefined method 'must_raise' for #` – Chekkan Apr 27 '21 at 20:48
0

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
Beat Richartz
  • 9,474
  • 1
  • 33
  • 50
0

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
dklima
  • 72
  • 6