ruby-on-railsrubyminitestshoulda

Rails Minitest undefined method `greater_than_or_equal_to' for #<Shoulda::Matchers


I want to use ShouldaMatchers gem inside of Minitest to check simple model validation:

class Portfolio < ApplicationRecord
  validates :share_ratio, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 }
end

To do so I've got a Minitest:

require 'test_helper'

class PortfolioTest < ActiveSupport::TestCase
  context 'validations' do
    should validate_numericality_of(:share_ratio).greater_than_or_equal_to(0)
    should validate_numericality_of(:share_ratio).is_less_than_or_equal_to(100)
  end
end

But I'm getting an error:

class:PortfolioTest': undefined method `greater_than_or_equal_to' for #Shoulda::Matchers::ActiveModel::ValidateNumericalityOfMatcher:0x00007fba91da3ce0 (NoMethodError)

#Gemfile:
  gem 'shoulda', '~> 4.0'
  gem 'shoulda-matchers', '~> 4.0'

I tried to change validation inside of the model:

validates_numericality_of :share_ratio, greater_than_or_equal_to: 0, less_than_or_equal_to: 100

But error is the same.


Solution

  • You got one of them right, but not the other.

    should validate_numericality_of(:share_ratio).is_greater_than_or_equal_to(0)
    should validate_numericality_of(:share_ratio).is_less_than_or_equal_to(100)