如何计算在 git 挂钩中使用 :focus 过滤的 RSpec 个示例?

How to count RSpec examples filtered with :focus in a git hook?

我正在尝试编写一个 Git 预提交挂钩,如果有一个标记为 :focus 的示例,它不会让用户提交。

使用RSpec的API(即使它是私有的也可以),有没有办法用:focus过滤器找出示例数?

我找到了 example_count-instance_method。它可能很有用,但我不确定如何从外部脚本调用它。

我不会调用 RSpec Ruby 代码,而是使用 --dry-run 标志通过 RSpec 的命令行界面来完成。这是一个这样做的预提交挂钩:

#!/bin/bash
if ! (rspec --dry-run --no-color -t focus:true 2>&1 | grep -q '^0 examples'); then
  echo "Please do not commit RSpec examples tagged with :focus."
  exit 1
fi

不完全确定这是否有助于或回答问题,但我目前使用 this set of githooks to make sure I don't commit obvious mistakes, and this pull request 在 [=] 中添加了对 :focus/focus: true/:focus => true 的检查16=] 个文件。

Here is an Overcommit pre_commit 使用 RSpecs private API 的钩子通过 :focus 过滤器查找规范:

require 'rspec'

module Overcommit
  module Hook
    module PreCommit
      # NOTE: This makes use of many methods from RSpecs private API.
      class EnsureFocusFreeSpecs < Base
        def configure_rspec(applicable_files)
          RSpec.configure do |config|
            config.inclusion_filter = :focus
            config.files_or_directories_to_run = applicable_files
            config.inclusion_filter.rules
            config.requires = %w(spec_helper rails_helper)
            config.load_spec_files
          end
        end

        def run
          configure_rspec(applicable_files)

          return :pass if RSpec.world.example_count.zero?

          files = RSpec.world.filtered_examples.reject {|_k, v| v.empty?}.keys.map(&:file_path).uniq
          [:fail, "Trying to commit focused spec(s) in:\n\t#{files.join("\n\t")}"]
        end
      end
    end
  end
end