应该使用 FactoryGirl 进行匹配测试,password_confirmation 未设置?

Shoulda-matchers test with FactoryGirl, password_confirmation not set?

我正在使用由 FactoryGirl 创建的实体使用 shoulda-matchers 测试我的帐户模型。

两个文件的代码如下所示:

测试文件

require 'spec_helper'

describe Account do
  before { @account = FactoryGirl.build(:account) }
  subject { @account }

  it { should validate_presence_of(:email) }
  it { should validate_presence_of(:password) }
  it { should validate_presence_of(:password_confirmation).
        with_message(@account.password_confirmation+' '+@account.password) }
  it { should allow_value('example@domain.com').for(:email) }

  it { should be_valid }
end

工厂

FactoryGirl.define do
  factory :account do
    email { FFaker::Internet.email }
    password "12345678"
    password_confirmation "12345678"
  end

end

我的错误如下:

1) Account should require password_confirmation to be set
  Failure/Error: it { should validate_presence_of(:password_confirmation).
   Expected errors to include "12345678 12345678" when password_confirmation is set to nil, got errors: ["password_confirmation can't be blank (nil)"]
 # ./spec/models/account_spec.rb:9:in `block (2 levels) in <top (required)>'


rspec ./spec/models/account_spec.rb:9 # Account should require password_confirmation to be set

我正在使用应该检查密码确认的装置。我知道这可能是因为一些愚蠢的事情,但我真的无法弄清楚它有什么问题。

设计,不验证 password_confirmation 的存在,它只是验证密码的确认,请参阅 Validatable 第 34 行:https://github.com/plataformatec/devise/blob/v3.5.3/lib/devise/models/validatable.rb#L34

validates_confirmation_of :password, if: :password_required?

编辑:您还可以看到 password_confirmation 运行 上没有验证器:User.validators_on(:password_confirmation)