从 Ruby 执行 Rspec [英] Execute Rspec from Ruby
问题描述
我正在尝试从 ruby 执行 rspec,并从方法或类似的东西中获取状态或失败次数.实际上我正在运行这样的东西:
I am trying to execute rspec from ruby, and get the status or number of failures from a method or something like that. Actually I am running something like this:
system("rspec 'myfilepath'")
但我只能得到函数返回的字符串.有没有办法直接使用对象来做到这一点?
but I only can get the string returned by the function. Is there any way to do this directly using objects?
推荐答案
我认为最好的方法是使用 RSpec 的配置和 Formatter.这将不涉及解析 IO 流,也以编程方式提供更丰富的结果定制.
I think the best way would be using RSpec's configuration and Formatter. This would not involve parsing the IO stream, also gives much richer result customisation programmatically.
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
对象来获取规范测试的结果和摘要.
Now you can use the json_formatter
object to get result and summary of a spec test.
# gets an array of examples executed in this test run
json_formatter.output_hash
output_hash
值的示例可以在 这里找到:
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