Rspec controllers in and out of the namespace of the same name

I have the following setup:

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

And similar characteristics:

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

All specifications work fine when they run independently, however when I run everything together, I get a warning:

 toplevel constant UsersController referenced by Admin::UsersController 

And the administrator controller specifications do not pass.

Route File:

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

...

Rails 4, Rspec 2.14

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

+7
ruby-on-rails rspec
source share
1 answer

This happens when the top-level class is automatically loaded before using the namespace. If you have this code without preinstalling the class:

 UsersController module AdminArea UsersController end 

The first line will cause a permanent missing hook: "ok, UsersController does not exist, so try loading it."

But then, reaching the second line, UserController is really already defined at the top level. Thus, hook_ const_missing does not start, and the application will try to use a known constant.

To avoid this, explicitly require the correct classes on top of your specification files:

 #spec/controllers/users_controller_spec.rb: require 'users_controller' 

and

 #spec/controllers/admin/users_controller_spec.rb require 'admin/users_controller' 
+23
source share

All Articles