ActiveModel::SecurePassword undefined method `password_digest='

戏子无情 提交于 2020-01-01 18:55:09

问题


I try to use rails 3.1 ActiveModel::SecurePassword by following http://bcardarella.com/post/4668842452/exploring-rails-3-1-activemodel-securepassword

and I end up with red light ...

user.rb

class User < ActiveRecord::Base
  has_secure_password
  validates :password, :presence => { :on => :create }
end

factory.rb

Factory.define :user do |f|
  f.email "foo@bar.com"
  f.password "foobar"
  f.password_confirmation { |u| u.password }  
end

spec_user.rb

describe User do
  it "should authenticate with matching username and password" do
    user = Factory(:user, :email => 'frank@gmail.com', :password => 'secret')
    User.authenticate('frank@gmail.com', 'secret').should == user
  end
end

and i get a red light ...

 Failure/Error: user = Factory(:user, :email => 'frank@gmail.com', :password => 'secret')
 NoMethodError:
   undefined method `password_digest=' for #<User:0xb383460>

and I thought it was rake db:migrate problem and I look into rails c , but obviously password_digest is defined.

ruby-1.9.2-p180 :007 > a = User.new
 => #<User id: nil, email: nil, password_digest: nil, is_admin: nil, created_at: nil, updated_at: nil> 
ruby-1.9.2-p180 :008 > a.password_digest = 3
 => 3 

回答1:


I was getting the same issue, and found a (what I think is) a better solution in the following comment:

http://bcardarella.com/post/4668842452/exploring-rails-3-1-activemodel-securepassword#comment-281584959

basically, you need to add a password_digest field to your model with a migration. Before then, it'll add a password_digest= method, but it won't be saved, and the method won'tr show up in factories and the like




回答2:


solved by

describe User do
  it "should authenticate with matching username and password" do
    user = Factory(:user, :email => 'frank@gmail.com', :password => 'secret')
    User.find_by_email('frank@gmail.com').try(:authenticate, 'secret').should == user
  end
end


来源:https://stackoverflow.com/questions/6069304/activemodelsecurepassword-undefined-method-password-digest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!