Rspec中expect和is_expected.to的区别 [英] Difference between expect and is_expected.to in Rspec

查看:39
本文介绍了Rspec中expect和is_expected.to的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些关键字之间有什么区别.

What is the difference between those keywords.

在下面的例子中,使用 expect 通过了测试,而 is_expected.to 没有通过.

In the following example, using expect passed the test, while is_expected.to failed it.

it { expect validate_uniqueness_of(:access_token) }

it { is_expected.to validate_uniqueness_of(:access_token) }

测试 User 类,由 Devise 生成

Testing for class User, which is generated by Devise

class User < ActiveRecord::Base
  devise :lockable, :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  validates :access_token, uniqueness: true

  before_validation :generate_access_token!, on: :create

  def generate_access_token!
    begin
      self.access_token = Devise.friendly_token
    end while User.find_by(access_token: self.access_token)
  end
end

推荐答案

is_expected_to 只是一个较短的写作版本

is_expected_to is just a shorter version of writing

expect(subject).to

您的第一个规范通过了,因为它实际上根本没有测试任何内容.

Your first spec passes because it is not actually testing anything at all.

第二个规范失败,因为没有唯一性验证.尽管您的代码正在处理重复项(但具有与验证相同的竞争条件),但它以不同的方式执行此操作:它生成一个新令牌,而不是报告错误.验证匹配器通常通过检查对象的 errors 哈希来工作,而您的代码没有设置它,因此规范失败.

The second spec fails because there is no uniqueness validation. Although your code is handling duplicates (but with the same race condition as a validation), it is doing so in a different way: it generates a new token, rather than reporting an error. The validation matchers typically work by checking the object's errors hash, and your code doesn't set that so the spec fails.

这篇关于Rspec中expect和is_expected.to的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆