我是使用Rspec测试我的应用程序的超级新手,并且正在尝试在没有用户的情况下测试注释的验证,并不断收到语法错误。这是注释模型代码。
class Comment < ApplicationRecord
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) }
belongs_to :user
belongs_to :product
scope:rating_desc, -> { order(rating: :desc) }
end
这是我试图测试的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
请帮忙!!
您在这里所做的很好-建立对象并使用be_valid
匹配器。但是,如果您使用Shoulda-matchers,则可以使用一种方法来测试模型验证:
describe Comment do
it { is_expected.to validate_presence_of :user }
end
您可以对其他验证(例如唯一性,数字性等)执行此操作,尽管您必须查找语法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句