gpt4 book ai didi

ruby-on-rails - 使用 RSpec 和 Rails 在模型中测试验证

转载 作者:行者123 更新时间:2023-12-04 13:48:04 26 4
gpt4 key购买 nike

我是使用 RSpec 测试我的应用程序的 super 新手,我正在尝试在没有用户的情况下测试评论的验证并不断收到语法错误。
这是评论模型代码。

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
这是评论规范:
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

最佳答案

你错过了 do ,这样做:

it "is invalid without a user" do
expect(build(:comment, user: nil)).to_not be_valid
end
但是当它失败时,这不是一个非常明确的测试,我建议您检查实际预期的验证错误。
这可能是这样的:
expect(ValidatingWidget.new.errors_on(:name)).to include("can't be blank")
expect(ValidatingWidget.new(:name => "liquid nitrogen")).to have(0).errors_on(:name)
rspec-rails errors_on @ relishapp

关于ruby-on-rails - 使用 RSpec 和 Rails 在模型中测试验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com