ruby - Rails——before_save 不工作?

标签 ruby ruby-on-rails-3 callback

我正在学习 Michael Hartl 的 RoR 教程,它涵盖了密码加密的基础知识。这是当前的用户模型:

class User < ActiveRecord::Base
    attr_accessor :password

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

    email_regex = /^[A-Za-z0-9._+-]+@[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 => "user@example.com",
                  :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_pa​​ssword 为 nil,因此第二个测试失败。但我不明白为什么它是 nil,因为 encrypt_password 方法应该由 before_save 调用。我知道我一定遗漏了什么 - 有人可以解释一下吗?

最佳答案

encrypt_password 方法不正确,应该是:

def encrypt_password
  self.encrypted_password = encrypt(password)
end

注意 self 的使用,它将正确设置用户对象的属性,而不是创建一个被遗忘的实例变量。

关于ruby - Rails——before_save 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6325846/

相关文章:

html - 如果登录为真,如何隐藏另一个 html 按钮?

ruby-on-rails - ruby on rails rspec 错误

jquery - 如何在 jquery 数据表 AJAX 回调后隐藏或显示列

javascript - 展平嵌套回调

javascript - attr() 的回调函数

ruby - ruby `Complex` 是类的时候怎么能像方法一样调用呢?

ruby-on-rails - 为应用程序和 CMS 使用单用户模型时如何限制对 activeadmin 仪表板的访问?

ruby-on-rails-3 - 轮胎上Elasticsearch的精确词组匹配

ruby-on-rails - Ruby on Rails - 将日期时间的哈希值转换为日期

jquery - 堆栈溢出式消息栏