我想要输出行,它在示例中的 rspec 比较期间失败了,但我不知道如何做到最好。 例如我有这样的测试:
require 'rspec'
describe 'My behaviour' do
it 'should do something' do
test_string = 'test'
expect(test_string).to eq('failed_test')
end
after :each do |example|
puts example.metadata[:expect_line]
end
end
我想在 after :each
中输出行
"expect(test_string).to eq('failed_test')"
我知道,我可以访问 example.metadata[:location]
,它返回类似 "./spec/test_spec.rb:4"
的内容,我可以解析它并提取行,但是是否已经有像我需要的东西隐藏在整个 example
结构中?
更新:
我才明白。 example.metadata[:location]
返回的不是失败行,而是 it
开始的行,所以它对我没有用:(
所以问题仍然存在 - 如何获得失败的线路?
最佳答案
据我所知,此信息并未隐藏在示例结构中的任何位置。 RSpec 的默认输出显示失败的行:
Failures:
1) My Description should fail
Failure/Error: expect(1).to eq(2)
expected: 2
got: 1
如果我们看看 rspec 本身是如何在 rspec/core/formatters/exception_presenter.rb 中得到这个的和 rspec/core/formatters/snippet_extractor.rb ,他们似乎通过示例异常的回溯来查找规范文件并提取该行(类似于您提到的内容)。如果有更简单的方法将其从示例中提取出来,我认为 RSpec 本身会使用它:)
关于ruby - 从元数据访问 `expected` 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34394275/