title: Rails -- before_save not working?
body: <p>I am following Michael Hartl's RoR tutorial, and it is covering the basics of password encryption.  This is the User model as it currently stands:</p>
  
  <pre><code>class User &lt; 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 =&gt; true,
                       :length =&gt; {:maximum =&gt; 50}
      validates :email, :presence =&gt; true,
                        :format =&gt; {:with =&gt; email_regex},
                        :uniqueness =&gt; {:case_sensitive =&gt; false}
      validates :password, :presence =&gt; true,
                           :length =&gt; {:maximum =&gt; 20, :minimum =&gt; 6},
                           :confirmation =&gt; true
  
      before_save :encrypt_password
  
      private
  
          def encrypt_password
              @encrypted_password = encrypt(password)
          end
  
          def encrypt(string)
              string
          end
  end
  </code></pre>
  
  <p><em>(Obviously this isn't doing any encrypting because the encrypt method isn't really implemented but that's not my question)</em></p>
  
  <p>I then wrote the following Spec (according to the tutorial):</p>
  
  <pre><code>require 'spec_helper'
  
  describe User do
  
      before(:each) do
          @attr = { :name =&gt; "Example User", :email =&gt; "user@example.com",
                    :password =&gt; "abc123", :password_confirmation =&gt; "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
  </code></pre>
  
  <p>The first of these tests passes, but since <code>@user.encrypted_password</code> is nil, the second test fails.  But I don't understand why it's nil since the <code>encrypt_password</code> method should be being called by <code>before_save</code>.  I know I must be missing something -- can someone please explain?</p>