在ruby教程中失败测试(Michael Hartl)

时间:2011-12-07 20:34:27

标签: ruby-on-rails-3 rspec

我正在学习Michael Hartl的教程。我使用RSPEC来运行测试。 到目前为止一切都那么好,但似乎我已经碰到了以下例子。

这是失败的测试(它应该通过):

describe "authenticate method" do
  it "should return the user on email/password match" do
    matching_user = User.authenticate(@attr[:email], @attr[:password])
    matching_user.should == @user
  end
end

以防万一。 @user定义为:

before(:each) do
  @user = User.create!(@attr)
end

@attr定义为:

before(:each) do        
  @attr = {
          :name => "Example user", 
          :email => "user@example.com",
          :password => "foobar",
          :password_confirmation => "foobar"
        }
end

user.rb中的条目

before_save :encrypt_password

def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
end

def self.authenticate(email, submitted_password)
    user = find_by_email(email)
    return nil  if user.nil?
    return user if user.has_password?(submitted_password)
end

private

def encrypt_password 
      self.salt = make_salt unless has_password?(password)
      self.encrypted_password = encrypt(password) 
end

def encrypt(string)
      secure_hash("#{salt}--#{string}")
end

def make_salt
      secure_hash("#{Time.now.utc}--#{password}")
end

def secure_hash(string)
      Digest::SHA2.hexdigest(string)
end

测试失败时显示错误消息

c:\RailsInstaller\work\apptwit>rspec spec/models/user_spec.rb
.................F

Failures:

  1) User password validations password encryption authenticate method should return the user on email/password
     Failure/Error: matching_user.should == @user
       expected: #<User id: 1, name: "Example user", email: "user@example.com", created_at: "2011-12-07 19:08:23
ed_at: "2011-12-07 19:08:23", encrypted_password: "fbdbaf712fa1b6c925c4ab2192e73ac9f9d1bedf67630610d68...">
            got: nil (using ==)
     # ./spec/models/user_spec.rb:204:in `block (5 levels) in <top (required)>'

Finished in 221.37 seconds
18 examples, 1 failure

Failed examples:

rspec ./spec/models/user_spec.rb:202 # User password validations password encryption authenticate method should
he user on email/password match

我会很感激任何指针, 非常感谢。

1 个答案:

答案 0 :(得分:1)

如果matching_user为零,那么您可能需要在puts email中添加一些puts user.inspectself.authenticate语句来进行调试。

似乎无法通过电子邮件找到用户,或者由于某种原因,您的密码在验证方法中不正确。