Я пытаюсь внедрить систему входа в систему, используя рельсы, а не внешний камень и следуя учебному пособию Майкла Хартля, который, по всей видимости, походит на свою вишню. До сих пор сайт сам функционирует нормально, это 2 тестов, чтобы сделать с входа в систему я борюсь с:Ruby возвращает класс nil в тестировании, отлично работает в dev
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, params: { 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, params: { 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
Мои сообщения об ошибках:
ERROR["test_login_with_invalid_information", UsersLoginTest, 2016-06-30 22:30:36 +0100]
test_login_with_invalid_information#UsersLoginTest (1467322236.17s)
NoMethodError: NoMethodError: undefined method `[]' for nil:NilClass
app/controllers/sessions_controller.rb:7:in `create'
test/integration/users_login_test.rb:12:in `block in <class:UsersLoginTest>'
app/controllers/sessions_controller.rb:7:in `create'
test/integration/users_login_test.rb:12:in `block in <class:UsersLoginTest>'
ERROR["test_login_with_valid_information", UsersLoginTest, 2016-06-30 22:30:36 +0100]
test_login_with_valid_information#UsersLoginTest (1467322236.18s)
NoMethodError: NoMethodError: undefined method `[]' for nil:NilClass
app/controllers/sessions_controller.rb:7:in `create'
test/integration/users_login_test.rb:21:in `block in <class:UsersLoginTest>'
app/controllers/sessions_controller.rb:7:in `create'
test/integration/users_login_test.rb:21:in `block in <class:UsersLoginTest>'
Коды ошибок указывают на следующий контроллер :
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
Я предположил, в начале это было связано с методами сеансов хелперы не доступны, однако сам сайт работает нормально в режиме разработки и регистрации возможна. Я что-то упустил из своего помощника сессий или самого тестового файла? Мои занятия помощник:
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
И, наконец, мой контроллер приложения:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
end
Извиняюсь за стену текста и спасибо заранее
Когда он говорит о неопределенном методе ... для nilclass это означает, что что-то есть то, что вы не ожидаете. Самый простой способ отладки - использовать что-то вроде byebug и точно выяснить, какое значение nil –