正如his comment 中的Anthony 所指出的,您可以使用RSpec::Core::Runner 基本上从代码或交互式控制台调用命令行行为。但是,如果您使用 Rails 之类的东西,请考虑您的环境可能会设置为开发环境(甚至是生产环境,如果您将在此处执行代码)。因此,请确保您所做的任何事情都不会产生任何不必要的副作用。
要考虑的另一件事是,RSpec 全局存储其配置,包括之前注册的所有示例组。这就是为什么您需要在后续运行之间重置 RSpec。这可以通过RSpec.reset 完成。
所以把它们放在一起,你会得到:
require 'rspec/core'
RSpec::Core::Runner.run(['spec/path/to_spec_1.rb', 'spec/path/to_spec_2.rb'])
RSpec.reset
对RSpec::Core::Runner.run 的调用将输出到标准输出并返回退出代码作为结果(0 表示没有错误,非零退出代码表示测试失败)。
..
Finished in 0.01791 seconds (files took 17.25 seconds to load)
2 example, 0 failures
=> 0
您还可以将其他 IO 对象传递给 RSpec::Core::Runner.run 以指定其应输出到的位置。您还可以将其他命令行参数传递给RSpec::Core::Runner.run 的第一个数组,例如'--format=json' 以 JSON 格式输出结果。
因此,例如,如果您想以 JSON 格式捕获输出,然后进一步对其进行处理,您可以执行以下操作:
require 'rspec/core'
error_stream = StringIO.new
output_stream = StringIO.new
RSpec::Core::Runner.run(
[
'spec/path/to_spec_1.rb',
'spec/path/to_spec_2.rb',
'--format=json'
],
error_stream,
output_stream
)
RSpec.reset
errors =
if error_stream.string.present?
JSON.parse(error_stream.string)
end
results =
if output_stream.string.present?
JSON.parse(output_stream.string)
end