使用 RSpec 和 Rails 测试模型中的验证

Jer*_*len 7 ruby validation rspec model ruby-on-rails

我对使用 RSpec 测试我的应用程序非常陌生,我正在尝试在没有用户的情况下测试评论的验证,并不断出现语法错误。这是评论模型代码。

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
Run Code Online (Sandbox Code Playgroud)

这是评论规范:

require 'rails_helper'

describe Comment do 
  before do 
    @product = Product.create!(name: "race bike", description: "fast race bike")
        @user = User.create!(email: "jerryhoglen@me.com", 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
Run Code Online (Sandbox Code Playgroud)

max*_*ner 4

您在这里所做的很好 - 构建对象并使用be_valid匹配器。但是,如果您使用shoulda-matchers,则可以使用单行代码来测试模型验证:

describe Comment do
  it { is_expected.to validate_presence_of :user }
end
Run Code Online (Sandbox Code Playgroud)

您可以对其他验证(例如唯一性、数值性等)执行此操作,但您必须查找语法。