Joey Robert
Joey Robert

Reputation: 7584

Getting the full RSpec test name from within a before(:each) block

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?

Upvotes: 28

Views: 12569

Answers (8)

Shiny
Shiny

Reputation: 121

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

Upvotes: 1

Artem Vasilev
Artem Vasilev

Reputation: 2211

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

Upvotes: 9

hybernaut
hybernaut

Reputation: 636

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"]

Upvotes: 0

satyajit
satyajit

Reputation: 1570

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

Upvotes: 5

deepak
deepak

Reputation: 8120

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

Upvotes: 1

bobics
bobics

Reputation: 2321

or you can use the methods directly:

x.example.description
x.example.file_path

etc.

Upvotes: 6

Joey Robert
Joey Robert

Reputation: 7584

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

Upvotes: 12

Radek Paviensky
Radek Paviensky

Reputation: 8486

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

Upvotes: 26

Related Questions