2013-04-29 61 views
0

我正在嘗試測試我的用戶模型(使用devise寶石)。我正在運行devise寶石的rails4分支。我正在嘗試編寫一個最小密碼長度的測試。使用RSpec測試密碼長度使用設計

在我user_spec.rb,我已經寫了:

require 'spec_helper' 

describe User do 
    before { @user = User.new(full_name: "Example User", email: "[email protected]", password: "foobar", password_confirmation: "foobar") } 

    subject { @user } 

    it { should respond_to(:full_name) } 
    it { should respond_to(:email) } 
    it { should respond_to(:password) } 
    it { should respond_to(:password_confirmation) } 
    # it { should ensure_length_of(:password).is_at_least(8) } 

    it { should be_valid } 

    describe 'when full name is not present' do 
    before { @user.full_name = " " } 
    it { should_not be_valid } 
    end 

    describe 'when email is not present' do 
    before { @user.email = " " } 
    it { should_not be_valid } 
    end 

    describe 'when password is not present' do 
    before {@user.password = " "} 
    it { should_not be_valid } 
    end 

    describe 'when password is too short' do 
    it { should ensure_length_of(:password).is_at_least(8) } 
    it { should_not be_valid } 
    end 
end 

不過,我仍然得到這個故障/錯誤運行rspec spec/時:

Failure/Error: it { should be_valid } 
expected #<User id: nil, email: "[email protected]", encrypted_password: 
"$2a$04$/Ifwb1dmfzG6xtBS/amRfOrTTopd8P6JSV48L0G/SWSh...", 
reset_password_token: nil, reset_password_sent_at: nil, 
remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, 
last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, 
created_at: nil, updated_at: nil, full_name: "Example User"> to be valid, 
but got errors: Password is too short (minimum is 8 characters) 
# ./spec/models/user_spec.rb:14:in `block (2 levels) in <top (required)>' 
+0

'foobar'長度爲6個字符 – apneadiving 2013-04-29 12:41:36

回答

1

在我看來,你的spec文件工作得很好。

您的it { should be_valid }測試在第14行上失敗。這是因爲您的密碼爲「foobar」,只有6個字符長,從而導致用戶失效。

嘗試改變

before do 
    @user = User.new(
    full_name: "Example User", 
    email: "[email protected]", 
    password: "foobar", 
    password_confirmation: "foobar") 
end 

到:

before do 
    @user = User.new(
    full_name: "Example User", 
    email: "[email protected]", 
    password: "foobar123", 
    password_confirmation: "foobar123") 
end 
1

您的測試還沒有一個有效的密碼創建的用戶。所以你的測試實際上是保證了預期的行爲。

將您的測試用戶密碼更改爲「長測試密碼」,它應該可以正常工作。

致以問候