从Ruby执行Rspec

时间:2011-08-08 17:52:01

标签: ruby rspec

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

system("rspec 'myfilepath'")

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

4 个答案:

答案 0 :(得分:26)

我认为最好的方法是使用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值的示例here

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

其他资源

答案 1 :(得分:8)

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

开始

编辑:好的就是这样:

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

选项 - 目录数组,错误&外流。例如

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

答案 2 :(得分:1)

您的问题是您正在使用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

这应输出总示例数和失败次数 - 根据需要进行调整。

答案 3 :(得分:0)

此文件将打印到控制台,并同时捕获消息。 formatter.stop只是一个存根函数,我通常不知道它是干什么的,我必须包括它才能使用DocumentationFormatter。格式化程序的输出还包含控制台着色代码。

formatter = RSpec::Core::Formatters::DocumentationFormatter.new(StringIO.new)
def formatter.stop(arg1)
end
RSpec.configuration.reporter.register_listener(formatter, :message, :dump_summary, :dump_profile, :stop, :seed, :close, :start, :example_group_started)

RSpec::Core::Runner.run(['test.rb','-fdocumentation'])

puts formatter.output.string