Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 949
aef Avatar asked Oct 24 '12 02:10

aef


2 Answers

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.

like image 152
Shepmaster Avatar answered Sep 25 '22 08:09

Shepmaster


If your goal is to only have to specify the namespace once, then the idiomatic RSpec way is to use described_class. Like this:

module Foo
  class Bar
  end
end

describe Foo::Bar do
  it "should work" do
    described_class.new
  end
end
like image 21
Ritchie Avatar answered Sep 24 '22 08:09

Ritchie