28

RSpec allows you to get the current running test method name in a before(:each) block, by doing the following:

Spec::Runner.configure do |config|
  config.before :each do |x|
    x.method_name # returns 'should be cool'
  end
end

This is for a test like:

require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe 'Hello world' do
  it 'should be cool' do
    # test code
  end 
end

Would it be possible to get the whole test name with what it's describing, (a.k.a. 'Hello World should be cool') in the before block?

8 Answers 8

26

In RSpec 2.0 you can use (I'm not sure if it is a best way but it works)

x.example.metadata[:example_group][:full_description]

As for RSpec 1.X I don't know. And that's probably what you are asking for...

12

I found the answer. Turns out there used to be a method called full_description on x that would do exactly what I want, however it was deprecated. The following produces the string I want:

"#{x.class.description} #{x.description}"

Reference

1
8

With Rspec 3.3 it works like this:

RSpec.configure do |config|
  config.before :example do |x|
    Rails.logger.debug("=== running spec example #{x.metadata[:full_description].inspect}")
  end
end
6

or you can use the methods directly:

x.example.description
x.example.file_path

etc.

2
  • try also: described_class
    – ajahongir
    May 22, 2013 at 4:01
  • This works in RSpec 2.13 (except that it's x.described_class not x.example.described_class as I initially thought).
    – szeryf
    Aug 24, 2013 at 10:41
4

With the latest rspec release as of (04/01/2014) this has changed to

example.metadata[:description]

Checkout https://github.com/rspec/rspec-core#metadata for more information

1

on rspec 2.12.0 "#{x.class.description} #{x.example.description}" works

0
0

You can get the file as well. I used this to track down issues with my poltergeist specs:

  config.before(:each, js: true) do |s|
    md = s.example.metadata
    x = md[:example_group]
    Rails.logger.debug "==>>> #{x[:file_path]}:#{x[:line_number]} #{md[:description_args]}"
  end

Note that this is the line number of the example group (not so useful), but the description of the current example, which should help you determine which one is running.

==>>> ./spec/features/editing_profiles_spec.rb:3 ["User Edits a Profile"]

0

This works in rspec 3.5

example.metadata[:full_description]

Fuller example, of how to access it:

  subject(:example_description) do |example|
    example.metadata[:full_description]
  end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.