从Ruby执行Rspec

我试图从ruby执行rspec,并从方法或类似的东西中获取失败的状态或数量。 其实我正在运行这样的事情:

system("rspec 'myfilepath'") 

但我只能得到函数返回的字符串。 有没有办法直接使用对象?

我认为最好的方法是使用RSpec的配置和Formatter。 这不涉及解析IO流,也以编程方式提供更丰富的结果定制。

RSpec 2:

 require 'rspec' config = RSpec.configuration # optionally set the console output to colourful # equivalent to set --color in .rspec file config.color = true # using the output to create a formatter # documentation formatter is one of the default rspec formatter options json_formatter = RSpec::Core::Formatters::JsonFormatter.new(config.output) # set up the reporter with this formatter reporter = RSpec::Core::Reporter.new(json_formatter) config.instance_variable_set(:@reporter, reporter) # run the test with rspec runner # 'my_spec.rb' is the location of the spec file RSpec::Core::Runner.run(['my_spec.rb']) 

现在,您可以使用json_formatter对象来获取规范测试的结果和摘要。

 # gets an array of examples executed in this test run json_formatter.output_hash 

可以在此处找到output_hash值的示例:

RSpec 3

 require 'rspec' require 'rspec/core/formatters/json_formatter' config = RSpec.configuration formatter = RSpec::Core::Formatters::JsonFormatter.new(config.output_stream) # create reporter with json formatter reporter = RSpec::Core::Reporter.new(config) config.instance_variable_set(:@reporter, reporter) # internal hack # api may not be stable, make sure lock down Rspec version loader = config.send(:formatter_loader) notifications = loader.send(:notifications_for, RSpec::Core::Formatters::JsonFormatter) reporter.register_listener(formatter, *notifications) RSpec::Core::Runner.run(['spec.rb']) # here's your json hash p formatter.output_hash 

其他资源

  • 详细的工作通过
  • 要点示例

我建议你看一下rspec源代码来找出答案。 我想你可以从example_group_runner开始

编辑 :好的就是这样:

 RSpec::Core::Runner::run(options, err, out) 

选项 – 目录数组,错误和输出 – 流。 例如

 RSpec::Core::Runner.run(['spec', 'another_specs'], $stderr, $stdout) 

您的问题是您正在使用Kernel#system方法执行命令,该命令仅根据是否可以找到命令并成功运行它返回true或false。 相反,您希望捕获rspec命令的输出。 基本上你想捕获rspec输出到STDOUT的所有东西。 然后,您可以遍历输出以查找和解析该行,该行将告诉您运行了多少个示例以及有多少个失败。

以下内容:

 require 'open3' stdin, stdout, stderr = Open3.popen3('rspec spec/models/my_crazy_spec.rb') total_examples = 0 total_failures = 0 stdout.readlines.each do |line| if line =~ /(\d*) examples, (\d*) failures/ total_examples = $1 total_failures = $2 end end puts total_examples puts total_failures 

这应输出总示例数和故障数 – 根据需要进行调整。