使用带有Rspec的Rails在模型中测试验证

杰里·霍格伦(Jerry Hoglen)

我是使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Rails 4,rspec 3:模型验证测试

Rspec的“ on::update”测试验证不起作用(Rails4 / Rspec 3)

使用不带辅助工具的rspec在Rails模型中测试字段唯一性的验证

Rails-枚举字段的测试验证

由于模型中的“only_integer”验证,rails factory rspec测试失败

Rails 5.2 rspec - 如何测试模型是否实际使用自定义验证器?

Proc中的RSpec模型验证测试错误

在Rails中,运行bin / rspec时如何运行所有模型测试?

如何在Rails 5中使用RSpec测试模型中的关联?

带有硒/独立铬的dockerized Rails 5应用中RSpec系统测试的SSL错误

如何使用Rspec和FactoryGirl在Rails模型中测试before_update回调?

.env未在带有rspec的Rails的测试环境中加载

用于 Swagger 测试的带有 Apivore 的 Rails RSpec

如何在flutter中测试验证iOS中的InAppPurchase

如何在Spring Boot应用中测试验证器?

Rails模型验证有效,但rake测试失败

如何测试验证注释?

Behat测试验证消息

如果没有使用rspec的Rails中的真实文件,就无法使用通过CarrierWave进行的模型

如何使用 RSpec 测试带有参数的方法?

Rails:RSpec未能通过模型子类的验证

模型上的Rails rspec测试更新属性

测试指向自身 rspec rails 5 的模型

为什么我的模型验证失败了,为什么我的rspec测试没有通过?

rspec和首次测试试验

使用带有延迟的协程验证在单元测试中调用的方法

使用bundle exec rspec规范时如何运行带有rspec标记的测试?

RSpec:带有搜索踢的无效模型

赛普拉斯测试验证