从before(:each)块中获取完整的RSpec测试名称

Joe*_*ert 26 ruby testing rspec ruby-on-rails

RSpec允许您通过执行以下操作来获取before(:each)块中当前运行的测试方法名称:

Spec::Runner.configure do |config|
  config.before :each do |x|
    x.method_name # returns 'should be cool'
  end
end
Run Code Online (Sandbox Code Playgroud)

这是一个测试,如:

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

describe 'Hello world' do
  it 'should be cool' do
    # test code
  end 
end
Run Code Online (Sandbox Code Playgroud)

是否有可能在前面的块中获得整个测试名称(也称为"Hello World应该很酷")?

Rad*_*sky 25

在RSpec 2.0中你可以使用(我不确定它是否是最好的方式,但它有效)

x.example.metadata[:example_group][:full_description]
Run Code Online (Sandbox Code Playgroud)

至于RSpec 1.XI不知道.这可能就是你要求的......


Joe*_*ert 12

我找到了答案.事实证明,曾经有一个名为full_description的方法在x上完全符合我的要求,但不推荐使用.以下产生我想要的字符串:

"#{x.class.description} #{x.description}"
Run Code Online (Sandbox Code Playgroud)

参考

  • `x.class.description`在RSpec 2.13中不起作用 (3认同)
  • https://www.relishapp.com/rspec/rspec-core/v/3-4/docs/metadata/current-example <-- 解释正确方法的文档.. (2认同)

Art*_*iev 7

使用Rspec 3.3,它的工作原理如下:

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


bob*_*ics 6

或者你可以直接使用这些方法:

x.example.description
x.example.file_path
Run Code Online (Sandbox Code Playgroud)

等等