【问题标题】:Rspec presence: true check fails even though it works as intendedRspec 存在:真实检查失败,即使它按预期工作
【发布时间】:2020-06-16 23:40:08
【问题描述】:

在我正在构建的 Rails API 中,我的用户模型有以下 Rspec 测试和以下输出:

RSpec.describe User, type: :model do
  let(:michael) { User.new(email: "michael@email.com", password: "Password1", password_confirmation: "Password1") }

    it 'is not valid without a password' do
      michael.password = ''
      expect(michael).not_to be_valid, "Expect User to have a Password"
    end

  end
  1) User basic checks is not valid without a password
     Failure/Error: expect(michael).not_to be_valid, "Expect User to have a Password"
       Expect User to have a Password
     # ./spec/models/user_spec.rb:19:in `block (3 levels) in <main>'

但是,由于某种原因,这个测试失败了,即使我的用户模型上有以下内容

class User < ApplicationRecord
  has_secure_password
  validates :email, presence: true, uniqueness: true
  validates :password, presence: true
  validates :password,
            format: { with: /\A(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}\Z/, message: "Password must be at least 8 characters long, contain at least 1 uppercase and 1 lowercase letter and 1 number" },
            confirmation: true,
            on: :create
end

上述验证工作正常,您可以在此处看到:

➜ rails c
Running via Spring preloader in process 2774
Loading development environment (Rails 6.0.3.1)
irb(main):001:0> new = User.new
irb(main):002:0> new.email = "testing@testing.com"
irb(main):003:0> new.save
   (0.2ms)  BEGIN
  User Exists? (0.6ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "testing@testing.com"], ["LIMIT", 1]]
   (0.2ms)  ROLLBACK
=> false
irb(main):004:0> new.errors
=> #<ActiveModel::Errors:0x00007f743848dfb0 @base=#<User id: nil, email: "testing@testing.com", password_digest: nil, created_at: nil, updated_at: nil, admin: false>, @messages={:password=>["can't be blank", "can't be blank", "Password must be at least 8 characters long, contain at least 1 uppercase and 1 lowercase letter and 1 number"]}, @details={:password=>[{:error=>:blank}, {:error=>:blank}, {:error=>:invalid, :value=>nil}]}>

我到底做错了什么导致这个测试失败?这是一个非常简单的问题,除了密码测试之外,所有其他的都按预期工作。

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec rspec-rails


    【解决方案1】:

    首先,在您的测试中,password = '' 是有效的,因为对于 Ruby,'' 是一个东西。您必须将此添加到您的验证中: validates :password, presence: true, allow_blank: false

    另外,请看一下,您的密码验证是针对 on: :create 的,而在您的规范中,您并没有创建它。

    【讨论】:

    • 错误答案。 presence: true 使用 blank? 方法验证属性。因此,如果此属性不为空且不是nil,则模型有效。你不需要写allow_blank: false。如果您使用valid? 方法,甚至不使用savecreate 方法,on: :create 验证将调用新对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 2018-02-08
    • 2017-02-26
    • 1970-01-01
    • 2017-02-14
    相关资源
    最近更新 更多