Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec Controllers in and out of namespace with same name

I have the following setup:

class UsersController < ApplicationController
...
end

class Admin::BaseController < ApplicationController
...
end

class Admin::UsersController < Admin::BaseController
...
end

And likewise specs:

#spec/controllers/users_controller_spec.rb:

describe UsersController do
...
end

#spec/controllers/admin/users_controller_spec.rb
describe Admin::UsersController do
...
end

All the specs run fine when run independantly, however when I run all together I get the warning:

toplevel constant UsersController referenced by Admin::UsersController

And the specs from the admin controller don't pass.

Routes file:

...
resources :users
namespace "admin" do
   resources :users
end

...

Rails 4, Rspec 2.14

Can I not use the same name for controllers in different namespaces?

like image 770
Yule Avatar asked Sep 26 '13 11:09

Yule


1 Answers

This happens when a top level class get autoloaded before a namespaced one is used. If you have this code without any class preloaded :

UsersController
module AdminArea
  UsersController
end

The first line will trigger constant missing hook : "ok, UsersController does not exist, so let's try to load it".

But then, reaching the second line, UsersController is indeed already defined, at top level. So, there's no const_missing hook triggered, and app will try to use the known constant.

To avoid that, explicitly require proper classes on top of your spec files :

#spec/controllers/users_controller_spec.rb:

require 'users_controller'

And

#spec/controllers/admin/users_controller_spec.rb

require 'admin/users_controller'
like image 123
kik Avatar answered Nov 18 '22 20:11

kik