我刚刚开始使用rails,并决定遵循m.hartl的“rubyonrails教程”。好像是个不错的介绍。
我遇到了一个失败的考试,这让我发疯。
我运行的是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 =>'[email protected]',
: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("[email protected]", @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/