2017-05-07 70 views
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

回答

1

在你的第一次測試你期望它會驗證密碼的確認,但你傳遞相同的密碼,所以它永遠不會有機會失敗。所以你有3個選項。 1使用你的第一個測試,但改變確認不一樣(通過工廠女孩傳遞參數)。 2你可以期望提高(如果你這樣做,你應該指定哪個錯誤會增加)。或者,您也可以使用Factory Girl的構建方法,並期望用戶無效。