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')
descr开发者_如何学编程ibe '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?
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...
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
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
or you can use the methods directly:
x.example.description
x.example.file_path
etc.
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
on rspec 2.12.0 "#{x.class.description} #{x.example.description}"
works
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"]
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
精彩评论