2012-02-02 68 views
4

我已经获得了一些模块级别的对象的规范。事情是这样的:如何更改RSpec描述块的模块上下文?

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真正的定义。

如何更改我的规范的常量查找上下文没有定义 该模块本身?

回答

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 

或者,对于笑:

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 
+0

呀,'described_class'是我们已经使用过,但我发现很难读书。我希望调用该对象来查看同一名称空间中的任何其他对象将调用它的方式。好吧。我会在接受之前看看是否有人能够胜过这个答案。 – Peeja 2012-02-02 22:15:35

+0

另一件事,如果你想在同一个命名空间describe_class中引用其他类也是不好的。也在寻找更好的解决方案。 – PhilT 2013-02-08 11:24:50

0

可以分配给一个变量?

widget_class = Foo::Bar::Baz::Quux::Widget 

这应该干掉一点点的代码。只是一个想法。