Read more

How to find out which type of Spec you are

Arne Hartherz
May 13, 2013Software engineer at makandra GmbH

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+.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2013-05-13 16:06)