Rails教程8.2:登录注销

时间:2015-09-08 04:57:30

标签: ruby-on-rails automated-tests railstutorial.org

通过Rails教程和第8章,我无法通过我的一个测试。一直在检查几个小时...任何帮助将不胜感激。

ERROR["test_login_with_valid_information", UsersLoginTest, 2015-09-07     00:25:37 -0700]
test_login_with_valid_information#UsersLoginTest (1441610737.31s)
BCrypt::Errors::InvalidHash:         
BCrypt::Errors::InvalidHash: invalid hash
    app/controllers/sessions_controller.rb:8:in `create'
    test/integration/users_login_test.rb:22:in `block in <class:UsersLoginTest>'
    app/controllers/sessions_controller.rb:8:in `create'
    test/integration/users_login_test.rb:22:in `block in <class:UsersLoginTest>'

22/22: [============] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.46288s
22 tests, 44 assertions, 0 failures, 1 errors, 0 skips    

users_login_test.rb

require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end

  test "login with invalid information" do
    get login_path
    assert_template 'sessions/new'
    post login_path, session: { email: "", password: "" }
    assert_template 'sessions/new'
    assert_not flash.empty?
    get root_path
    assert flash.empty?
  end

  test "login with valid information" do
    get login_path
    post login_path, session: { email: @user.email, password: 'password' }
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)
  end
end

sessions_controller.rb

class SessionsController < ApplicationController

  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      redirect_to user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
  end
end

3 个答案:

答案 0 :(得分:1)

我知道自从最初发布以来已经有一段时间,但我有完全相同的错误,我的问题是一个拼写错误(缺少=) 的 users.yml里

michael:
  name: Michael Example
  email: michael@example.com
  password_digest: <% User.digest('password') %>

应该在哪里

michael:
name: Michael Example
email: michael@example.com
password_digest: <%= User.digest('password') %>

答案 1 :(得分:0)

@PraveenGeorge是正确的 - 至少自上次测试通过以来,您需要回溯跟踪并检查您的代码。基于您共享的两个文件的内容与教程相匹配的事实,问题出在其他地方(不幸的是,我们看不到SO)。

也许是你在def User.digest(string)或在sessions_helper.rb中的user.rb?

答案 2 :(得分:-1)

亲爱的@Travislogan:由于ruby on rails教程本身在很多方面都是自我解释的,所以在进入8.2节之前,你可能已经错过了一些步骤/代码。因此,请至少将前一章中的所有测试和项目代码交叉检查到当前的一个,再检查一次。它将帮助您找出代码中的错误。