2011-06-13 44 views
8

我遵循Michael Hartl的RoR教程,它涵盖了密码加密的基础知识。这是用户模式,因为它目前为:Rails - before_save不工作?

class User < ActiveRecord::Base 
    attr_accessor :password 

    attr_accessible :name, :email,: password, :password_confirmation 

    email_regex = /^[A-Za-z0-9._+-][email protected][A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/ 
               #tests for valid email addresses. 

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

    before_save :encrypt_password 

    private 

     def encrypt_password 
      @encrypted_password = encrypt(password) 
     end 

     def encrypt(string) 
      string 
     end 
end 

(显然这是没有做任何加密,因为加密方法是不是真的实现,但是这不是我的问题)

我然后写以下规格(根据教程):

require 'spec_helper' 

describe User do 

    before(:each) do 
     @attr = { :name => "Example User", :email => "[email protected]", 
        :password => "abc123", :password_confirmation => "abc123"} 
    end 

    describe "password encryption" do 

     before(:each) do 
      @user = User.create!(@attr) # we are going to need a valid user in order 
             # for these tests to run. 
     end 

     it "should have an encrypted password attribute" do 
      @user.should respond_to(:encrypted_password) 
     end 

     it "should set the encrypted password upon user creation" do 
      @user.encrypted_password.should_not be_blank 
     end 

    end 
end 

第一这些测试的通过,但由于@user.encrypted_password是零,第二测试失败。但我不明白为什么它是零,因为encrypt_password方法应该被before_save调用。我知道我必须错过一些东西 - 有人可以解释吗?

回答

20

的ENCRYPT_PASSWORD方法不正确,应阅读:

def encrypt_password 
    self.encrypted_password = encrypt(password) 
end 

的使用注意事项自我,这将正确设置为用户对象的属性,而不是创建该遗忘的实例变量。

+1

我给你的“接受的答案”,因为这解决了我的问题,但我仍然有这个所以概念上的问题,如果你想解决这些我跟进的问题是在这里:HTTP:/ /stackoverflow.com/questions/6327174/rails-self-vs :)赢得积分的另一个机会。 – Kvass 2011-06-13 06:14:03