rails设计验证password_confirmation无法正常工作

时间:2017-05-07 00:30:56

标签: ruby-on-rails devise

我在设计验证方面遇到了麻烦。这是我的模型类(请注意,我已启用validatable):

class User < ApplicationRecord

  devise :database_authenticatable, :registerable, :recoverable,
    :rememberable, :trackable, :validatable

end

我尝试使用以下方法验证密码确认:

describe User do
  before { @user = FactoryGirl.build(:user) }
  subject { @user }
  it { should validate_confirmation_of(:password) }
end

我的工厂:

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

但我收到了这个错误:

  1) User should require password_confirmation to match password
     Failure/Error: it { should validate_confirmation_of(:password) }

   Expected errors to include "doesn't match Password" when password is set to "different value",
   got no errors
 # ./spec/models/user_spec.rb:18:in `block (2 levels) in <top (required)>'

这意味着不会触发设计验证器。

现在我添加一个自定义验证器:

  validate :password_must_match
  def password_must_match
    errors.add(:password, "doesn't match confirmation") if password != password_confirmation
  end

得到了这个错误:

Failures:

  1) User should require password_confirmation to match password
     Failure/Error: it { should validate_confirmation_of(:password) }

       Expected errors to include "doesn't match Password" when password is set to "different value",
       got errors:
       * "doesn't match Password" (attribute: password_confirmation, value: "some value")
       * "doesn't match confirmation" (attribute: password, value: "different value")
     # ./spec/models/user_spec.rb:18:in `block (2 levels) in <top (required)>'

正如您所看到的,我们现在有2个验证错误,"doesn't match Password"来自设计validatable,而"doesn't match confirmation"来自我自己的自定义验证器。

我还尝试使用自定义测试代替it { should validate_confirmation_of(:password) }

  describe "#confirmation_of_password" do
    it "should fail when password does not match" do
      expect { User.create!(email: "xxx@xxx.com", password: "123456", password_confirmation: "1234567") }.to raise_error
    end
  end

它有效。但我不想从shoulda

重新发明轮子

0 个答案:

没有答案