gpt4 book ai didi

ruby - 从 Ruby 执行 Rspec

转载 作者:数据小太阳 更新时间:2023-10-29 06:33:09 24 4
gpt4 key购买 nike

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

system("rspec 'myfilepath'")

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

最佳答案

我认为最好的方法是使用 RSpec 的配置和格式化程序。这不涉及解析 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

其他资源

关于ruby - 从 Ruby 执行 Rspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6986319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com