【发布时间】:2011-10-22 14:43:55
【问题描述】:
我正在尝试从 ruby 执行 rspec,并从方法或类似的东西获取状态或失败次数。实际上我正在运行这样的东西:
system("rspec 'myfilepath'")
但我只能得到函数返回的字符串。有没有办法直接使用对象来做到这一点?
【问题讨论】:
-
说真的,没有办法单独调用
RSpec::ExampleGroup吗?无需将其保存到文件中?
我正在尝试从 ruby 执行 rspec,并从方法或类似的东西获取状态或失败次数。实际上我正在运行这样的东西:
system("rspec 'myfilepath'")
但我只能得到函数返回的字符串。有没有办法直接使用对象来做到这一点?
【问题讨论】:
RSpec::ExampleGroup 吗?无需将其保存到文件中?
我建议您查看 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
这应该输出总示例数和失败数 - 根据需要进行调整。
【讨论】:
我认为最好的方法是使用 RSpec 的配置和格式化程序。这不涉及解析 IO 流,还以编程方式提供更丰富的结果定制。
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 中找到:
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
【讨论】:
这个打印到控制台并同时捕获消息。 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
【讨论】: