1
我遇到了设计验证问题。这是我的模型类(请注意,我已经启用validatable
):rails设计验证password_confirmation不起作用
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: "[email protected]", password: "123456", password_confirmation: "1234567") }.to raise_error
end
end
自定义测试尝试和它的作品。但我不想重新发明轮子shoulda