4
votes

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
2
/Users/jerryhoglen/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load': /Users/jerryhoglen/Desktop/nameofapp/spec/models/comment_spec.rb:15: syntax error, unexpected keyword_end, expecting end-of-input (SyntaxError) @ZhongZheng - Jerry Hoglen

2 Answers

1
votes

you missed a do, do it like:

it "is invalid without a user" do
  expect(build(:comment, user: nil)).to_not be_valid
end

But that's not a very clear test when it fails, I suggest you check the actual expected validation error. That's what it may look like:

expect(ValidatingWidget.new.errors_on(:name)).to include("can't be blank")
expect(ValidatingWidget.new(:name => "liquid nitrogen")).to have(0).errors_on(:name)

See rspec-rails errors_on @ relishapp

0
votes

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.