1
votes

I have the following routes:

config/routes.rb:

Rails.application.routes.draw do
  scope module: :api do
    namespace :v1 do
      resources :users
    end
  end
end

controllers/api/v1/users_controller.rb:

module Api
  module V1
    class UsersController < ApplicationController
      def index
        ...
      end
    end
  end
end

The controller specs are under the folder spec/controllers/api/v1/.

spec/controllers/api/v1/users_controller_spec.rb:

module Api
  module V1
    RSpec.describe UsersController, type: :controller do
      let!(:users) { create_list(:user, 10) }

      describe 'GET /v1/users' do
        before { get :index }
        # Already tried `get '/v1/users'`, got the same error

        it 'should return 10 users' do
          expect(JSON.parse(response).size).to eq(10)
        end
      end
    end
  end
end

Once I run the tests I receive the following error:

ActionController::UrlGenerationError: No route matches {:action=>"index", :controller=>"api/v1/users"}

Note that it "infers" the api part from somewhere, but my routes are like these:

v1/users
v1/users/:id
...

How can I make it work?

1
Side note: it's probably better to do RSpec.describe Api::V1::UsersController instead of putting it inside Api::V1 module.Grzegorz

1 Answers

1
votes

I believe this is because you are namespacing your test with Api::V1::UsersController, but your route is defined within the scope of Api. That's why your routes are not under /api

Try removing the Api module from the controller and test or changing scope module: :api to namespace :api

Alternatively, you could keep it all as-is and make the get request to your v1_users_path or whatever the corresponding path is when you run rails routes (instead of :index).