Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

ruby on rails - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...