测试没有通过Rails教程第8章

时间:2015-07-30 02:35:45

标签: ruby-on-rails railstutorial.org

根据Rails Tutorial,测试应该通过,但是我的测试失败了。我怎么可能做错了?

users_login_test.rb

def setup
    @user = users(:microte)
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

users_controller.rb

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to Microte"
      redirect_to @user
    else
      render 'new'
    end
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end
end

sessions_helper.rb

module SessionsHelper

  # Logs in the given user
  def log_in(user)
    session[:user_id] = user.id
  end

  # Returns the current logged-in user (if any)
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end
end

这是测试输出:

 FAIL["test_login_with_valid_information", UsersLoginTest, 2015-07-30 00:12:45 +0100]
 test_login_with_valid_information#UsersLoginTest (1438211565.39s)
    Expected response to be a <redirect>, but was <200>
    test/integration/users_login_test.rb:22:in `block in <class:UsersLoginTest>'

  1/1: [=========================================================================================================] 100% Time: 00:00:03, Time: 00:00:03

Finished in 3.83137s
1 tests, 1 assertions, 1 failures, 0 errors, 0 skips

1 个答案:

答案 0 :(得分:1)

这意味着您的执行流程尚未到达该行:

redirect_to @user

这是因为你有来自@user.save的错误结果。

现在,您可以应用Chapter 7的调试知识。将debugger置于if语句之上,再次运行测试并检查验证错误:

@user.valid?
@user.errors.messages

你应该得到验证错误,并且很可能在那里找到答案。