Home > Mobile >  Override Rails Devise Controllers and get routing errors
Override Rails Devise Controllers and get routing errors

Time:02-04

I'm overriding Devise controllers in Rails like that:

module Api
  module V1
    module Devise
      class RegistrationsController < Devise::RegistrationsController
      ....
      end
    end
  end
end

And thats my routes:

Rails.application.routes.draw do
  root 'application#index'

  devise_for :users
  devise_for :taxi_drivers, only: :passwords

  resources :taxi_drivers_groups, only: %i[index new create edit update]

  namespace :api do
    namespace :v1 do
      devise_for :users,
        defaults: { format: :json },
        class_name: 'User',
        skip: %i[registrations sessions passwords],
        path: '',
        path_names: { sign_in: 'login', sign_out: 'logout' }

      devise_scope :user do
        post 'signup', to: 'devise/registrations#create'
        post 'login',  to:'devise/sessions#create'
        delete 'logout', to: 'devise/sessions#destroy'
        post 'password_recover', to: 'devise/passwords#create'
        put 'password_recover', to: 'devise/passwords#update'
      end
    end
  end
end

And I'm getting an error when I try to pass my tests:

ActionController::RoutingError: uninitialized constant Api::V1::Devise::RegistrationsController

And in my test file:

test 'user invalid sigup with empty fields' do
  @valid_signup_params[:name] = nil

  post('/api/v1/signup.json', { user: @valid_signup_params }, headers: { format: :json })

  assert_equal last_response.status, 422
  assert_equal json_response['errors']['name'].count, 1
end

Do you have any idea how to fix this error?

Thanks!

CodePudding user response:

The issues comes from a constant clash between the newly defined controller and the existing one.

Replacing class RegistrationsController < Devise::RegistrationsController with class RegistrationsController < ::Devise::RegistrationsController is fixing the issue as ruby knows that he has to find the RegistrationsController class in the previously defined Devise module and not in the current definition.

  • Related