【问题标题】:How to programatically get rspec output error backtrace如何以编程方式获取 rspec 输出错误回溯
【发布时间】:2014-07-15 17:53:37
【问题描述】:

我有一个 ruby​​ 脚本,它需要执行 rspec 测试并收集结果。 我正在使用标准 rspec API 来实现这一点:

require 'rspec'
require 'rspec/core'
require 'rspec/core/formatters/json_formatter'
require 'json'

def run_test(test_location)
 config = RSpec.configuration
 json_formatter = RSpec::Core::Formatters::JsonFormatter.new(config.output)
 reporter =  RSpec::Core::Reporter.new(json_formatter)
 config.instance_variable_set(:@reporter, reporter)
 begin
  ::RSpec::Core::Runner.run([test_location,'--format','j'])
  json_formatter.output_hash
 rescue Exception => e
  e.message
 end
end

run_test(<PATH_TO_RSPEC_TEST_SCRIPT>)

现在,当 rspec 测试失败时,我只能收到错误消息,但我想从失败的底层 rspec 测试中获取回溯。有没有办法做到这一点? 我尝试将参数: --backtrace 或 -b 传递给传递给 RSpec::Core::Runner.run 方法的数组,但没有得到太多帮助

提前致谢

【问题讨论】:

    标签: rspec rspec2


    【解决方案1】:

    RSpec::Core::Formatters::JsonFormatter 实例中提供了任何引发异常的示例的回溯。无需将 -b 选项添加到参数中。

    json_formatter.examples.each do |example|
        printf( "Example:  [%s]\n", example.metadata[:description] )
        printf( "Backtrace:\n %s\n", example.exception.backtrace.join("\n ") ) unless example.exception.nil?
    end
    

    Exception 也将包含回溯

    rescue Exception => e
      warn e.message
      e.backtrace
    end
    

    rescue Exception 用作you will catch more than you want 时要小心。

    【讨论】:

    • 谢谢,但我认为这仅在某些规范测试失败并且我们需要回溯时才有效。另一方面,如果有人犯了语法错误,例如,请执行以下操作:描述“测试”执行它“不起作用”执行 1.should eq(1) end end json_formatter_object contains: #<:core::formatters ::jsonformatter:0x007ffcf40f1858>, @failure_count=0, @pending_count=0, @example_count=0, @examples=[], @failed_examples=[], @pending_examples=[], @example_group =nil, @output_hash={}>
    • 另一方面,如果我们从 cmd 运行相同的规范文件,我们将得到:/Users/bjusufbe/Desktop/rspec.rb:1:in &lt;top (required)&gt;': undefined method desscribe' for main: Object (NoMethodError) 我需要的是处理这些情况并检索发生此错误的代码行(与我们在 cmd 行执行中相同)
    • rspec 不会在该级别捕获异常,因此它会在回溯中退出。 JsonFormatter 在发生异常时保持初始状态,因为您正在捕获所有异常并返回异常消息。
    • 您的另一个选择是不深入研究 Rspec 的内部结构。您可以通过system 运行rspec。检查退出状态并从文件 (--format json --out rspec.json ) 或 stderr 中提取结果以了解 rspec 失败时的情况。
    猜你喜欢
    • 2017-11-13
    • 2017-09-19
    • 2011-06-15
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    相关资源
    最近更新 更多