如何更改RSpec描述块的模块上下文?

Pee*_*eja 4 ruby rspec activesupport

我有一个针对多个模块级别的对象的规范.像这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

这是很多重复,它使我看起来像是在使用来自其他命名空间的对象.我想将规范的上下文设置为 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
Run Code Online (Sandbox Code Playgroud)

只有一个问题.由于我在Rails中,我依赖于ActiveSupport的依赖关系管理来自动加载Foo::Bar::Baz::Quux 模块.之前,那件事发生在我提到的时候Foo::Bar::Baz::Quux::Widget.现在,我自己定义模块,因此模块的真正定义 foo/bar/baz/quux.rb永远不会被加载.

如何在不自定义模块的情况下更改规范的常量查找上下文?

nak*_*ima 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
Run Code Online (Sandbox Code Playgroud)

或者,对于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
Run Code Online (Sandbox Code Playgroud)