2011-09-09 81 views
0

在邁克爾·哈特爾的Ruby on Rails的教程,ch 7.2.3,RSpec的就是返回以下錯誤:Rails教程ch 7.2.3 has_password?未定義的方法

Failures: 

1) User has_password? method should be true if the passwords match 
Failure/Error: @user.has_password?(@attr[:password].should be_true) 
NoMethodError: 
    undefined method `has_password?' for nil:NilClass 
# ./spec/models/user_spec.rb:132:in `block (3 levels) in <top (required)>' 

2) User has_password? method should be false if the passwords don't match 
Failure/Error: @user.has_password?("invalid").should be_false 
NoMethodError: 
    undefined method `has_password?' for nil:NilClass 
# ./spec/models/user_spec.rb:136:in `block (3 levels) in <top (required)>' 

Finished in 0.23931 seconds 
18 examples, 2 failures 

Failed examples: 

rspec ./spec/models/user_spec.rb:131 # User has_password? method should be true if the passwords match 
rspec ./spec/models/user_spec.rb:135 # User has_password? method should be false if the passwords don't match 

在控制檯中,我還對「確認密碼」

得到一個未定義的局部變量錯誤我徹底檢查了我的代碼,找不到差異,但我顯然做錯了。

這裏是我的用戶模型:

require 'digest' 

class User < ActiveRecord::Base 
    attr_accessor :password 
    attr_accessible :name, :email, :password, :password_confirmation 

    email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 

    validates :name, :presence => true, 
       :length  => { :maximum => 50 } 
    validates :email, :presence => true, 
       :format  => { :with => email_regex }, 
       :uniqueness => { :case_sensitive => false } 

    # Automatically create the virtual attribute 'password_confirmation'. 
    validates :password, :presence  => true, 
        :confirmation => true, 
        :length  => { :within => 6..40 } 

    before_save :encrypt_password 

    def has_password?(submitted_password) 
     self.encrypted_password == encrypt(submitted_password) 
    end 

    private 

    def encrypt_password 
     self.salt = make_salt if new_record? 
     self.encrypted_password = encrypt(password) 
    end 

    def encrypt(string) 
     secure_hash("#{salt}--#{string}") 
    end 

    def make_salt 
     secure_hash("#{Time.now.utc}--#{password}") 
    end 

    def secure_hash(string) 
    Digest::SHA2.hexdigest(string) 
    end 

end 
+1

我們就需要看到規範;問題在於你所說的是零,而不是該方法不存在。您確定正在加載和檢索適當的測試數據嗎? –

+0

你如何在規範中設置@user?聽起來像你還沒有初始化它。 –

回答

1

確保該位是在你的天賦,聽起來就像它缺少

before(:each) do 
    @user = User.create!(@attr) 
end 
+0

是的,這是從has_password丟失?方法。謝謝! –

+0

很高興它的工作,乾杯。 –

相關問題