【发布时间】:2017-05-18 14:37:16
【问题描述】:
我有使用 RSpec 3.4.0 测试的 rails 4.1.16 API 应用程序,但在测试不同模块中的同名类时遇到问题。
结构是:
app/controllers/bar/notifications_controller.rb
class Bar::NotificationsController < ApiController
...
end
和不同模块中的同名控制器:
app/controllers/foo/bar/notifications_controller.rb
module Foo
class Bar::NotificationsController < ApiController
...
end
end
Foo 是一个新模块,还没有测试。
添加后,旧Bar::NotificationsController的所有相应控制器测试开始失败。
规范文件:
spec/controllers/bar/notifications_controller_spec.rb
require 'spec_helper'
describe Bar::NotificationsController, type: :controller do
...
end
该规范文件中的所有测试都失败并出现相同的错误:
RuntimeError:
@controller is nil: make sure you set it in your test's setup method.
当我在Foo模块中更改控制器名称时问题不存在:
app/controllers/foo/bar/foo_notifications_controller.rb
module Foo
class Bar::FooNotificationsController < ApiController
...
end
end
我已经尝试在规范文件的顶部添加require 'bar/notifications_controller' 并将类名用作字符串describe "Bar::NotificationsController, type: :controller,但它没有解决问题(同样的错误)。
为什么会这样?解决办法是什么?
我想相信有一件小事我还没有尝试过,我不必为了使规范通过而用无意义的名称污染我的代码和结构。
非常感谢您的帮助!
【问题讨论】:
-
您可以尝试使用
module Bar来定义命名空间,而不是在类名本身中定义吗? -
试试
describe ::Bar::NotificationsController, type: :controller do -
不幸的是它没有用。
标签: ruby-on-rails ruby-on-rails-4 rspec ruby-2.2