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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With