If you look at my RSpec specs, you will probably notice a wide use of a klass method.
describe Whois::Client do
context "#initialize" do
it "accepts 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 example above Whois::Client.
Here's the method definition.
# /spec/support/helpers.rb
module SupportHelpers
# Gets the currently described class.
# Unlike `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 it in the /spec/support folder (which is automatically loaded in RSpec 2).
The klass method is a very convenient helper to keep your specs clean and flexible, especially when using long namespaces.
Before that, I 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 zero parameters" do
lambda { @klass.new }.should_not raise_error
end
end
end
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.