ruby-on-railsrubyrspec

Rails - Named route not working in controller spec


In my routes.rb file I had this route:

resources :profiles

In my controller specs I had thus paths such as:

profiles_path
new_profile_path 

etc.

Now I had to move this inside a namespace. The new route is then:

  namespace :admin do
    resources :profiles
  end

Then I started using it as follows:

admin_profiles_path

This path works fine in my feature specs. But the problem is that when I use this in my controller specs, I'm getting the following error:

 ActionController::UrlGenerationError:
   No route matches {:action=>"/admin/profiles", :controller=>"profiles", :dir=>"asc", :order=>"name"}

When I try to check my routes for this controller however, I get the proper route:

admin_profiles GET    /admin/profiles(.:format)                admin/profiles#index

This is my controller test:

RSpec.describe Admin::ProfilesController, type: :controller do
  render_views

  describe 'GET #index' do
    before do
      user = create(:user)
      sign_in user, scope: :user
    end

    it 'sorts by profile name by default' do
      profile_a = create(:profile, name: 'A name')
      profile_b = create(:profile, name: 'B name')
      profile_c = create(:profile, name: 'C name')

      get admin_profiles_path
      
      #some expects

    end
end

And this is my action:

module Admin
  class ProfilesController < ApplicationController
    before_action :authenticate_user!
    load_and_authorize_resource

    def index
      if params[:search_text].present?
        @profiles = Profile.search(params[:search_text])
      else
        @profiles = Profile.all
      end
    end
  end
end

Why is it pointing to a profiles action and not an index one. And what am I doing wrong?


Solution

  • When running rails routes then this line

    admin_profiles GET    /admin/profiles(.:format)    admin/profiles#index
    ^^^^^^^^^^^^^^
    

    tells you that the name of the route changed because you name spaced it with admin.

    Instead of profiles_path (or new_profile_path), you now have to use admin_profiles_path (or new_admin_profile_path).

    And will route the request following Ruby on Rails conventions to the index method of a Admin::ProfilesController.