我刚刚开始使用rails,并决定遵循" Ruby on Rails教程"作者:M. Hartl。好像是一个很好的介绍。
我遇到了一次失败的测试让我疯了。 我正在运行 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 '
rspec测试:
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
我无法弄清楚我在这里做错了什么。
答案 0 :(得分:1)
在你失败的规范中你有
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