Rspec 控制器进出命名空间的同名 [英] Rspec Controllers in and out of namespace with same name

查看:39
本文介绍了Rspec 控制器进出命名空间的同名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下设置:

class UsersController < ApplicationController
...
end

class Admin::BaseController < ApplicationController
...
end

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

同样的规格:

#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.

路由文件:

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

...

Rails 4,Rspec 2.14

Rails 4, Rspec 2.14

我可以不为不同命名空间中的控制器使用相同的名称吗?

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

推荐答案

这种情况发生在顶级类在使用命名空间之前自动加载.如果您的代码没有预加载任何类:

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

第一行会触发常量丢失钩子:好的,UsersController 不存在,所以让我们尝试加载它".

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

但是,到了第二行,确实已经在顶层定义了 UsersController.因此,不会触发 const_missing 钩子,应用程序将尝试使用已知常量.

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'

#spec/controllers/admin/users_controller_spec.rb

require 'admin/users_controller'

这篇关于Rspec 控制器进出命名空间的同名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆