Search code examples
rubyrspecnamespacesruby-1.9.3

Including namespace module through RSpec config in Ruby 1.9.3


I like to use RSpec's include configuration method to include modules which are only for namespacing so that I don't have to use fully-qualified names for their inner classes and modules. This worked fine with RSpec 2.11.0 in Ruby 1.9.2. But now on Ruby 1.9.3 this doesn't work anymore. How can I get it working again?

Here an example foobar_spec.rb:

module Foo
  class Bar
  end
end

RSpec.configure do |config|
  config.include Foo
end

describe Foo::Bar do
  it "should work" do
    Bar.new
  end
end

If you call it by the following command:

rspec foobar_spec.rb

It will work in Ruby 1.9.2 just fine. But it will raise the following error in Ruby 1.9.3:

Failure/Error: Bar.new
     NameError:
       uninitialized constant Bar

Solution

  • This mailing list entry discusses the root change in 1.9.3 as to how constants are looked up, so it looks like a deliberate change.

    You could scope the whole test, like this:

    module Foo
      describe Bar do
        it "should work" do
          Bar.new
        end
      end
    end
    

    As another solution, you could extract the new object creation to a before or let or just define the object as the subject of the test.