Difference between expect and is_expected.to in Rspec

爷,独闯天下 提交于 2019-12-24 06:38:51

问题


What is the difference between those keywords.

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) }

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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/36832428/difference-between-expect-and-is-expected-to-in-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!