Get the currently described class in RSpec

If you look at my RSpec, you will probably notice a wide usage of a klass method.

describe Whois::Client do
  context "#initialize" do
    it "accepts a zero parameters" do
      lambda { klass.new }.should_not raise_error
    end

    it "accepts a timeout setting with a value in seconds" do
      client = klass.new(:timeout => 100)
      client.timeout.should == 100
    end
  end
end

The klass method references the currently described object, in the case above Whois::Client.

Here's the method definition.

# /spec/support/helpers.rb
module SupportHelpers
  # Gets the currently described class.
  # Conversely to +subject+, it returns the class
  # instead of an instance.
  def klass
    described_class
  end
end

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

I normally save the definition in a file, and put the file into the /specs/support folder (which is automatically loaded in RSpec 2).

The klass method is very convenient helper to keep your specs cleaned and flexible, specially when using long namespaces.

Before that, I was used to define a @klass instance variable at the beginning of my specs/tests. It worked, but wasn't really that clean.

describe Whois::Client do
  before(:each) do
    @klass = Whois::Client
  end

  context "#initialize" do
    it "accepts a zero parameters" do
      lambda { @klass.new }.should_not raise_error
    end
  end
end

~~~ruby class Whois::ClientTest < Test::Unit::TestCase def setup @klass = Whois::Client end

def test_initialize_with_zero_parameters assert_nothing_raised { @klass.new } end end

I'm very grateful to RSpec because it seems to adapt perfectly to any developers' need.