问题
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