小编Jer*_*len的帖子

使用 RSpec 和 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" …
Run Code Online (Sandbox Code Playgroud)

ruby validation rspec model ruby-on-rails

7
推荐指数
1
解决办法
7726
查看次数

标签 统计

model ×1

rspec ×1

ruby ×1

ruby-on-rails ×1

validation ×1