如何计算 RSpec 测试中的示例数量?

How can I count the number of examples in my RSpec tests?

我想计算一个目录中有多少个测试而不 运行 测试。

我尝试了与我在 中发现的类似的方法,但无法打印除 0 以外的任何内容。


这是我尝试过的(有和没有注释掉的配置内容):

task 'count_specs' do
  RSpec.configure do |config|
    config.pattern = 'features/**/*_spec.rb'
    # config.inclusion_filter.rules
    # config.filter_run focus: true
    # config.run_all_when_everything_filtered = true
    # config.inclusion_filter.rules
    config.requires = ['spec_helper']

    config.load_spec_files

    puts 'count of examples'
    puts config.files_to_run

  puts RSpec.world.example_count
  end

  puts 'count of examples'
  puts RSpec.world.example_count
end

我如何创建一个任务来计算有多少示例与特定模式匹配?

我想 运行 针对两个目录并比较结果。

也许有一些特定的 RSpec 方法,但我建议使用此脚本:

Dir["**/*_spec.rb"].map { |path| File.read(path) }.join.scan(/(  it)|(  scenario)/).count

很幼稚但是很靠谱

此变体搜索 " it"" scenario",但您可以根据需要更改模式。

此变体仅适用于没有块的测试,例如

RSpec.describe 'smth' do
  array.each do |i|
    it { should_smth }
  end
end

在 RSpec 3 中有一个 --dry-run 选项,它可以在没有 运行 任何示例或挂钩的情况下打印套件的格式化程序输出。

rspec --dry-run

如果您需要在 ruby 脚本中计算示例数:

output = `bundle exec rspec --dry-run | grep 'examples, 0 failures'`
example_count = output.split(' ').first.to_i
RSpec.configuration.world.example_count

这没有记录在案,因此在未来的版本中可能会中断。 请注意,这是具有 运行 的测试的累积数量,因此直到每个测试都具有 运行.

之后,该数字才准确