Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing validations in model using RSpec with Rails

I'm super new to testing my app using RSpec and I'm trying to test the validation of a comment without a user and keep getting syntax errors. Here is the comment model code.

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :product

  scope :rating_desc, -> { order(rating: :desc) }

  validates :body, presence: true
  validates :user, presence: true
  validates :product, presence: true
  validates :rating, numericality: { only_integer: true }

  after_create_commit { CommentUpdateJob.perform_later(self, user) }
end

and here is the comment spec:

require 'rails_helper'

describe Comment do 
  before do 
    @product = Product.create!(name: "race bike", description: "fast race bike")
        @user = User.create!(email: "[email protected]", password: "Maggie1!")
        @product.comments.create!(rating: 1, user: @user, body: "Awful bike!")
  end

  it "is invalid without a user"
   expect(build(:comment, user:nil)).to_not be_valid
  end
end
like image 325
Jerry Hoglen Avatar asked Jun 30 '26 09:06

Jerry Hoglen


1 Answers

What you're doing here is good - building objects and using the be_valid matcher. But if you use shoulda-matchers there's a one-liner to test a model validation:

describe Comment do
  it { is_expected.to validate_presence_of :user }
end

You can do this for other validations such as uniqueness, numericality, etc, though you'd have to look up the syntax.

like image 69
max pleaner Avatar answered Jul 01 '26 22:07

max pleaner