nameerror неопределенная локальная переменная или метод `log_out' Вы имели в виду? logout_url рубин на рельсах

Итак, я следую учебнику Майкла Хартла, и когда я пытаюсь выйти из системы, я получаю это "NameError in SessionsController#destroy"undefined local variable or method "log_out" for #<SessionsController:0x0000000275f290> Did you mean? logout_url

Мои тесты и эта ошибка появились только после того, как я добавил последний бит в свой тест, однако моя функция выхода из системы на веб-сайте также не работала.

Это мой session_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

# Logs out the current user.
  def destroy
    session.delete(:user_id)
    @current_user = nil
  end
end

Это мой session_controller:

class SessionsController < ApplicationController
  def new
  end

  def create
    #Gets user from database in lowercase & determines if user is valid
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      # Log the user in and redirect to the user's show page.
      log_in user
      redirect_to user
    else
      # Create an error message.
      flash.now[:danger] = 'Invalid email/password combination' 
      render 'new'
    end
  end

  # Logs out the current user.
  def destroy
    log_out # undefined variable Name error
    redirect_to root_url
  end
end

Мой application_controller:

  class ApplicationController < ActionController::Base
    protect_from_forgery with: :exception
    include SessionsHelper #temporary session cookie, expires automatically upon browser close
  end

Мое представление/layouts/_header.html.erb (используется для панели навигации, где находится ссылка для выхода):

<header class="navbar navbar-fixed-top navbar-inverse">
  <div class="container">
    <%= link_to image_tag("logo2.png", alt: "CourseBuddies logo"), root_path, id: "logo" %>
    <%- # link_to "sample app", '#', id: "logo" %>
    <nav>
      <ul class="nav navbar-nav navbar-right">
        <li><%= link_to "Home", root_path   %></li>
        <li><%= link_to "Reviews",   '#' %></li>
        <li><%= link_to "About us",   about_path %></li>

         <%- # LOGIN & SCROLL DOWN BAR %>
        <% if logged_in? %>
          **<li><%= link_to "Users", users_path %></li>
          <li class="dropdown">**
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              Account <b class="caret"></b>
            </a>
            <ul class="dropdown-menu">
              **<li><%= link_to "Profile", current_user %></li>
              <li><%= link_to "Settings", '#' %></li>**
              <li class="divider"></li>
              <li>
                **<%= link_to "Log out", logout_path, method: :delete %>**
              </li>
            </ul>
          </li>
        **<% else %>
          <li><%= link_to "Log in", login_path %></li>
        <% end %>**
      </ul>
    </nav>
  </div>
</header>

Моя пользовательская модель:

class User < ApplicationRecord
    #before saving, make sure the email is in downcase
    before_save { self.email = email.downcase }

    validates :name,  presence: true, length: { maximum: 50 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: {case_sensitive: false}


    # Let's you safely store a hashed password_digest to DB,
    # gives you password & password_confirmation attributes, 
    # an authenticate method that returns the user when pw is correct,
    # otherwise false. 
    has_secure_password(validations:false)
    validates :password, presence:true, length: { minimum: 6 }

     # Returns the hash digest of the given string.
    def User.digest(string)
        cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
        BCrypt::Password.create(string, cost: cost)
    end
end

Мой метод создания в моем контроллере Users: def create @user = User.new(user_params) #params[:user])#user_params)

if @user.save
  log_in @user
  flash[:success] = "Welcome to CourseBuddies!"
  redirect_to @user

else
  render 'new'
end

конец

Мой тест/test_helper:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end
end

И мой user_login_test:

require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end

   # Visit the login path.
# Verify that the new sessions form renders properly.
# Post to the sessions path with an invalid params hash.
# Verify that the new sessions form gets re-rendered and that a flash message appears.
# Visit another page (such as the Home page).
# Verify that the flash message doesn’t appear on the new page.  
  test "login with valid information followed by logout" do
    get login_path
    post login_path, params: { session: { email:    @user.email,
                                      password: 'password' } }
    assert is_logged_in?
    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)

    #AFTER ADDING THIS MY TEST FAILED

    #after logging in, we use delete to issue a DELETE request to the logout path
    #(Table 8.1) and verify that the user is logged out and redirected to the root URL
    delete logout_path
    assert_not is_logged_in?
    assert_redirected_to root_url
    follow_redirect!
    assert_select "a[href=?]", login_path
    assert_select "a[href=?]", logout_path,      count: 0
    assert_select "a[href=?]", user_path(@user), count: 0
  end
end

И напоследок мои маршруты:

Rails.application.routes.draw do

  get 'sessions/new'

  #ROOT, first page to show
  root 'pages#home'

  # maps requests for the URL/pages/home to the about us action in the Pages controller.
  # By using GET we arrange for the route to respond to a GET request.
  # With this we generate a about us action inside the Pages controller, automatically
  # get a page at the address /pages/about us
  get '/about', to: 'pages#about'
  get '/signup', to: 'users#new'
  post '/signup',  to: 'users#create' #signup route that responds to POST requests.
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  #resources :sessions
  resources :users
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html              

end

Извините, что много кода! В учебнике говорится, что тест users_login_test должен стать зеленым после добавления нового кода, но он терпит неудачу. Кроме того, выход из системы не работает и выдает мне эту ошибку: изображение ошибки

Буду благодарен за любую помощь!


person Myth    schedule 04.07.2017    source источник


Ответы (1)


Ошибка имени в SessionsController#destroy "неопределенная локальная переменная или метод log_out" для SessionsController: 0x0000000275f290 Вы имели в виду? logout_url

В руководстве (см. 8.3) имя метода в sessions_helper равно log_out, тогда как вы назвали его destroy, но назвали его log_out в sessions_controller. Вы должны изменить его на log_out

def log_out
  session.delete(:user_id)
  @current_user = nil
end
person Pavan    schedule 04.07.2017
comment
Спасибо, что заметил мою глупую ошибку и снова просветил меня, Паван! Ты лучший ! - person Myth; 05.07.2017