Почему я получаю сообщение об ошибке «ActionController :: UrlGenerationError: Нет совпадений с маршрутом ...»? - PullRequest
0 голосов
/ 08 мая 2018

Я использую ruby ​​2.3.1 с рельсами 5.0.7. У меня следующие ошибки при запуске RSpec:

Неудачи:

1) AuthenticationController POST / auth / login, когда запрос действителен, возвращает токен аутентификации Ошибка / ошибка: перед {публикация 'auth / login', params: valid_credentials, headers: headers}

 ActionController::UrlGenerationError:
   No route matches {:action=>"auth/login", :controller=>"authentication", :email=>"foo@bar.com", :password=>"foobar"}
 # ./spec/controllers/authentication_controller_spec.rb:32:in `block (4 levels) in <top (required)>'
 # ./spec/rails_helper.rb:85:in `block (3 levels) in <top (required)>'
 # ./spec/rails_helper.rb:84:in `block (2 levels) in <top (required)>'

2) AuthenticationController POST / auth / login При неправильном запросе возвращается сообщение об ошибке Ошибка / Ошибка: перед {post '/ auth / login', params: invalid_credentials, headers: headers}

 ActionController::UrlGenerationError:
   No route matches {:action=>"/auth/login", :controller=>"authentication", :email=>"paolo.jakubowski@quitzonbartoletti.net", :password=>"30NoVoGu7h"}
 # ./spec/controllers/authentication_controller_spec.rb:41:in `block (4 levels) in <top (required)>'
 # ./spec/rails_helper.rb:85:in `block (3 levels) in <top (required)>'
 # ./spec/rails_helper.rb:84:in `block (2 levels) in <top (required)>'

Вот мои маршруты. Rb:

Rails.application.routes.draw do # Подробнее о DSL, доступных в этом файле, см. http://guides.rubyonrails.org/routing.html

ресурсов: задачи to

 resources :items

конец

отправьте 'auth / login', чтобы: 'authentication # authenticate'

post 'регистрация', чтобы: 'users # create'

конец

Вот сгенерированные маршруты:

Префикс Verb URI Pattern Controller # Действие

    todo_items GET    /todos/:todo_id/items(.:format)     items#index

       POST   /todos/:todo_id/items(.:format)     items#create


    todo_item GET    /todos/:todo_id/items/:id(.:format) items#show

       PATCH  /todos/:todo_id/items/:id(.:format) items#update

       PUT    /todos/:todo_id/items/:id(.:format) items#update

       DELETE /todos/:todo_id/items/:id(.:format) items#destroy

 todos GET    /todos(.:format)                    todos#index

       POST   /todos(.:format)                    todos#create

  todo GET    /todos/:id(.:format)                todos#show

       PATCH  /todos/:id(.:format)                todos#update

       PUT    /todos/:id(.:format)                todos#update

       DELETE /todos/:id(.:format)                todos#destroy

  auth_login POST   /auth/login(.:format)        authentication#authenticate

signup POST   /signup(.:format)                   users#create

Вот аутентификационный_контроллер.spec:

    require 'rails_helper'

    RSpec.describe AuthenticationController, type: :controller do
      # Authentication test suite
      describe 'POST /auth/login' do
        # create test user
        let!(:user) { create(:user) }

        # set headers for authorization
        let(:headers) { valid_headers.except('Authorization')  }

        # set test valid and invalid credentials
        let(:valid_credentials) do 
           { 
              email: user.email, 
              password: user.password 
           } 
        end # let(:valid_credentials) do 

        let(:invalid_credentials) do 
          {
             email: Faker::Internet.email,
             password: Faker::Internet.password
          }
        end # let(:invalid_credentials) do 

        # set request.headers to our custom headers
        # before { allow(request).to receive(:headers).and_return(headers) }

        # returns auth token when request is valid
        context 'when request is valid' do
          before { post 'auth/login', params:  valid_credentials , headers: headers }

          it 'returns an authentication token' do
            expect(json['auth_token']).not_to be_nil
          end #  it 'returns an authentication token' do
        end #     context 'when request is valid' do

        # returns failure message when request is invalid
        context 'When request is invalid' do
          before { post '/auth/login', params: invalid_credentials, headers: headers }

          it 'returns a failure message' do
            expect(json['message']).to match(/Invalid credentials/)
          end # it 'returns a failure message' do
        end # context 'When request is invalid' do


      end # describe 'POST /auth/login' do

    end # RSpec.describe AuthenticationController, type: :controller do

Вот аутентификационный_контроллер:

    class AuthenticationController < ApplicationController

      skip_before_action :authorize_request, only: :authenticate
      # return auth token once user is authenticated
      def authenticate
        auth_token = AuthenticateUser.new(auth_params[:email], auth_params[:password]).call
        json_response(auth_token: auth_token)
      end # def authenticate

      private

      def auth_params
        params.permit(:email, :password)
      end

    end

Любая помощь будет оценена. Заранее спасибо.

1 Ответ

0 голосов
/ 08 мая 2018

Вы попали не в ту сторону. Вы уже находитесь в контроллере аутентификации, поэтому кроме параметров вам просто нужно выполнить действие:

post 'authenticate', params:  valid_credentials , headers: headers

Место, которое вы публикуете, должно соответствовать конечной точке контроллера, независимо от того, как вы определили метод, в данном случае «authenticate»

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...