我刚刚开始使用 Rails,并决定遵循 M. Hartl 的“Ruby on Rails 教程”。似乎是一个很好的介绍。
我遇到了一个失败的测试,这让我抓狂。 我正在运行 rails 3.1.1,使用 rspec 2.7.0
我已经尝试修改条件,并测试“has_password”方法是否有效。
失败的测试:
1) User password encryption authenticate method should return the user on email/password match Failure/Error: matching_user.should == @user expected: # got: nil (using ==) # ./spec/models/user_spec.rb:149:in `block (4 levels) in '
The rspec test:
describe User do
before(:each) do
@attr = {:name => 'testing',
:email =>'testing@example.com',
:password => "testtest",
:password_confirmation => "testtest"}
end
...
describe "password encryption" do
before(:each) do
@user = User.create!(@attr)
end
...
describe "authenticate method" do
it "should exist" do
User.should respond_to(:authenticate)
end
it "should return nil on email/password mismatch" do
User.authenticate(@attr[:email], "wrongpass").should be_nil
end
it "should return nil for an email address with no user" do
User.authenticate("bar@foo.com", @attr[:password]).should be_nil
end
it "should return the user on email/password match" do
matching_user = User.authenticate(@attr[:email], @attr[:password])
matching_user.should == @user
end
end
在用户模型中:
...
def has_password?(submitted_password)
encrypt_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email) #self.where("email = ?", email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
private
def encrypt_password
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
我不知道我在这里做错了什么。
最佳答案
在你失败的规范中你有
matching_user.should == @user
但是 @user
没有在任何地方定义,所以它被设置为 nil。
编辑:
尝试将以下 puts
添加到失败的规范中,并查看运行后在规范输出中得到的结果。
it "should return the user on email/password match" do
matching_user = User.authenticate(@attr[:email], @attr[:password])
puts matching_user # add this
puts @user # and also this
matching_user.should == @user
end
关于ruby-on-rails - M. Hartl 的密码 Ruby on Rails 教程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8089331/