问题
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