我正在尝试在命名空间中测试一些类,目前我有这个代码:
describe Server::SessionController do
it "should create session" do
Server::LoginController.stub(:authenitcate).and_return(session_id)
Server::SessionController....
Server::SessionController....
end
end
如何摆脱可重复的Server
命名空间?
答案 0 :(得分:4)
RSpec Book(http://pragprog.com/book/achbd/the-rspec-book)提供了一个解决方案:
3 module Codebreaker
4 describe Game do
5 describe "#start" do
...第二个语句声明了一个名为Codebreaker的Ruby模块。这不是必需的 为了运行规范,但它提供了一些便利。对于 例如,我们不必在第4行完全符合游戏资格。
因此,请尝试将您的规范放在Server
模块中。
HTH。
答案 1 :(得分:2)
虽然@BernardK给出了适合大多数情况的“正确的东西”解决方案,但也有一个肮脏的HACK。如果你有很多不同的Spec文件测试来自同一名称空间的不同类,并且厌倦了在每个文件中编写module Your::Long::Namespace ... end
并引入额外的标识级别(因为这可能会导致VCS中的巨大差异),这可能会很有用。
所以,如果你把它......
def Object.const_missing(c)
if Your::Long::Namespace.const_defined? c
Your::Long::Namespace.const_get(c)
else
raise NameError, "uninitialized constant #{c}"
end
end
...在你的spec_helper.rb
中,然后在使用这个帮助器的每个规范中,你将能够使用来自Your::Long::Namespace
的所有常量(类也是常量),没有前缀,也不需要输入你的规范在这个模块里面。这非常类似于C ++的using namespace
语句。您可以在我的一个旧项目中看到使用此项的示例:definition here,usage example here。
但请注意:
using namespace
一样,这会导致命名空间混乱和可能的冲突; 你看,使用风险自负:)