我正在学习使用 RSpec 进行测试。我的测试有问题。
我的模型:
class User < ActiveRecord::Base
has_secure_password
# Validation macros
validates_presence_of :name, :email
validates_uniqueness_of :email, case_sensitive: false
end
我的工厂:
FactoryGirl.define do
factory :user do
name "Joe Doe"
email "joe@example.com"
password_digest "super_secret_password"
end
end
还有我的规范:
require 'rails_helper'
RSpec.describe User, type: :model do
user = FactoryGirl.build(:user)
it 'has a valid factory' do
expect(FactoryGirl.build(:user)).to be_valid
end
it { is_expected.to respond_to(:name) }
it { is_expected.to respond_to(:email) }
it { is_expected.to respond_to(:password) }
it { is_expected.to respond_to(:password_confirmation) }
it { expect(user).to validate_presence_of(:name) }
it { expect(user).to validate_presence_of(:email) }
it { expect(user).to validate_presence_of(:password) }
it { expect(user).to validate_uniqueness_of(:email).case_insensitive }
end
我希望这次测试能通过。但我得到的结果是:
Failures:
1) User should validate that :email is case-insensitively unique Failure/Error: it { expect(user).to validate_uniqueness_of(:email).case_insensitive }
User did not properly validate that :email is case-insensitively unique. The record you provided could not be created, as it failed with the following validation errors: * name: ["can't be blank"] # ./spec/models/user_spec.rb:18:in `block (2 levels) in <top (required)>'
Finished in 0.34066 seconds (files took 1.56 seconds to load) 9 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:18 # User should validate that :email is case-insensitively unique
我错过了什么?
更新
我认为这是一个错误:https://github.com/thoughtbot/shoulda-matchers/issues/830
最佳答案
这是因为您在 IMO 中声明了 2 次!首先构建用户,然后在 expect()
中构建相同的用户。
只需像这样使用您使用 factory-bot 构建的第一个用户:
it 'has a valid factory' do
expect(user).to be_valid
end
附言
最好使用 Faker gem 而不是像在 factory.rb
关于ruby-on-rails - 为什么我的模型的唯一性验证规范在应该通过时却失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34830015/