【问题标题】:How to programmatically run rspec test and capture output?如何以编程方式运行 rspec 测试并捕获输出?
【发布时间】:2017-09-19 02:39:38
【问题描述】:

我正在尝试以编程方式运行一系列 Rspec 测试并捕获每个测试的输出。

到目前为止,我所拥有的是:

RSpec.configure do |config|
  config.formatter = :json
end

out = StringIO.new
err = StringIO.new
RSpec::Core::Runner.run([file], err, out)

这确实正确运行了给定的文件,并且在我运行此脚本的终端中,我看到了我期望的 JSON 输出......但由于我给运行器一个 StringIO 流,我会期待它将 JSON 输出写入其中而不是标准输出。在这种情况下,输出流始终为空。

有人知道我做错了什么吗?

【问题讨论】:

  • 您可以将所有去往$stdout 的内容写入文件。如果这有帮助stackoverflow.com/questions/26894443/…
  • 我已经尝试通过 $stdout = StringIO.new 来做类似的事情,但我仍然在屏幕上看到输出,并且 $stdout 中没有任何内容,它是一个空白的 StringIO 对象。
  • 我最终解决了这个问题,因为我只需要知道规范是否失败,run 函数在成功时返回 0,在失败时返回 1。仍然不知道为什么输出流似乎不起作用。
  • 我发现我在 rspec 3.3 中遇到了这个问题,但在 rspec 3.6 中似乎工作正常......

标签: json ruby rspec


【解决方案1】:

要运行一系列 Rspec 测试,我使用 Rake 并记录它们的输出,我使用 RSpec::Core::RakeTask,我可以在其中指定 rspec_opts,您可以使用它传递 rspecs 输出的位置和格式。 示例:

瑞克文件

require 'rake'
require 'rspec/core/rake_task'

desc "Run tests, recording their output"

RSpec::Core::RakeTask.new(:spec) do |task|
  task.pattern = 'spec/*_spec.rb' 
  task.rspec_opts = '--format documentation' +
  ' --format json --out logs/output.json' 
end

我在https://github.com/SamuelGarratt/rake_demo做了一个基本的 github 项目来演示这个

上述 Rakefile 假设您的 rspec 测试位于名为“spec”的文件夹中,并以“_spec”结尾。在命令行中输入“rake spec”以运行所有 rspec 测试并记录其输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多