我有一个针对多个模块级别的对象的规范。像这样:
describe Foo::Bar::Baz::Quux::Widget do
it "should == another Widget for the same Doohickey" do
doohickey = stub
Foo::Bar::Baz::Quux::Widget.new(doohickey).should == Foo::Bar::Baz::Quux::Widget.new(doohickey)
end
it "should != another Widget for a different Doohickey" do
one_doohickey = stub
another_doohickey = stub
Foo::Bar::Baz::Quux::Widget.new(one_doohickey).should == Foo::Bar::Baz::Quux::Widget.new(another_doohickey)
end
end
这是很多重复,它使我看起来像是在使用一个对象
来自其他一些命名空间我想将规范的上下文设置为
Foo::Bar::Baz::Quux
。以下工作效果令人惊讶:
module Foo::Bar::Baz::Quux
describe Widget do
it "should == another Widget for the same Doohickey" do
doohickey = stub
Widget.new(doohickey).should == Widget.new(doohickey)
end
it "should != another Widget for a different Doohickey" do
one_doohickey = stub
another_doohickey = stub
Widget.new(one_doohickey).should == Widget.new(another_doohickey)
end
end
end
只有一个问题。因为我在Rails,我依赖
ActiveSupport的依赖关系管理自动加载Foo::Bar::Baz::Quux
模块。之前,当我提到Foo::Bar::Baz::Quux::Widget
时发生了这种情况。
现在,我自己定义模块,所以模块的真正定义
永远不会加载foo/bar/baz/quux.rb
。
如何在没有定义的情况下更改规范的常量查找上下文 我自己的模块?
答案 0 :(得分:5)
您可以使用described_class
帮助程序...
describe Foo::Bar::Baz::Quux::Widget do
it "has described_class helper" do
described_class.should == Foo::Bar::Baz::Quux::Widget
end
end
或者,对于lol:
describe Foo::Bar::Baz::Quux::Widget do
def Widget
described_class
end
it "has described_class helper" do
Widget.should == Foo::Bar::Baz::Quux::Widget
end
end
答案 1 :(得分:0)
您可以将其分配给变量吗?
widget_class = Foo::Bar::Baz::Quux::Widget
这应该稍微干掉代码。只是一个想法。