How to find out which type of Spec you are

Updated . Posted . Visible to the public.

When you need to find out in which kind of spec you are during run-time, it's definitely possible. It's a lot easier in RSpec 2+.

For example, consider this global before block where you'd want to run some code for specific specs only:

config.before do
  # stuff
  that_fancy_method
  # more stuff
end

RSpec 2+

If you want to run such a block for a specific type of specs, you can use filters Show archive.org snapshot :

config.before do
  # stuff
  # more stuff
end

config.before :type => 'controller' do
  that_fancy_method
end

If that's not enough for you, query your example's metadata:

example.metadata[:type]
# => "controller"

From an example itself or a before block, query self.class.metadata.

RSpec 1

Unfortunately, RSpec 1 doesn't offer such filters, and the helpful metadata isn't around either. However, you can still get something similar by looking at self.class.ancestors. For example:

config.before do
  # stuff
  that_fancy_method if is_a? Spec::Rails::Example::ControllerExampleGroup
  # more stuff
end

Find out if you are in a spec that knows about request and response

You can use the RSpec 1 approach to find out if your current example knows about RSpec's request and response, like helper specs or controller specs:

if is_a? Spec::Rails::Example::FunctionalExampleGroup
  that_fancy_request_thing
end

Note that you should not check via something like respond_to?(:request) since that would break horribly in specs that let(:request).

The example above is from RSpec 1 -- the class to check against might be different for RSpec 2.

Arne Hartherz
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2013-05-13 14:06)