是否应该使用FactoryGirl进行测试,未设置password_confirmation?

时间:2015-12-15 16:24:29

标签: ruby-on-rails ruby factory-bot

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

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

测试文件

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

FACTORY

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

我正在使用设备来检查密码确认。我知道它可能是因为有些愚蠢,但我真的无法弄清楚它有什么问题。

1 个答案:

答案 0 :(得分:1)

设计,不验证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)