Search code examples
activerecordrspec-rails

RSpec and active record validations


I'm trying to validate that the rating of a movie is greater than 0 and less than or equal to 5 and for that I'm using the "be_valid" in RSpec which seems to work when I check if the movie title is nil but it's not working for the rating.

I don't understand why

Model:

class Movie < ApplicationRecord
  validates :title, presence: true
  validates :rating, presence: true, numericality: { greater_than_or_equal_to: 0,less_than_or_equal_to: 5,  only_integer: true }
end

Spec:

RSpec.describe Movie, type: :model do
  # checking model validations
  subject{described_class.new}

    it "title must be present" do
      subject.title = ""
      expect(subject).not_to be_valid
    end

    it "rating must be greater than 0" do
      subject.rating = 1
      expect(subject.rating).to be_valid
    end

    it "rating must be less than or equal to 5" do
      subject.rating = 5
      expect(subject.rating).to be_valid
    end
end

Error:

Movie
  title must be present
  rating must be greater than 0 (FAILED - 1)
  rating must be less than or equal to 5 (FAILED - 2)

Failures:

  1) Movie rating must be greater than 0
     Failure/Error: expect(subject.rating).to be_valid
     
     NoMethodError:
       undefined method `valid?' for 1:Integer
     # ./spec/models/movie_spec.rb:15:in `block (2 levels) in <top (required)>'

  2) Movie rating must be less than or equal to 5
     Failure/Error: expect(rating).to be_valid
     
     NameError:
       undefined local variable or method `rating' for #<RSpec::ExampleGroups::Movie:0x00007f8332f46fc0>
     # ./spec/models/movie_spec.rb:20:in `block (2 levels) in <top (required)>'

Solution

  • You should use expect(subject).to be_valid in the other 2 test cases. You are getting the error because you are trying to validate subject.rating which is an integer.