如何计算RSpec示例过滤:焦点在git钩子?

hal*_*ons 5 ruby git rspec rspec3

我正在尝试编写一个Git预提交钩子,如果有一个标记的示例,它将不允许用户提交:focus.

使用RSpec的API(好吧即使它是私有的),有没有办法找出:focus过滤器的例子数量?

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

hal*_*ons 4

这是一个Overcommit pre_commit 挂钩,它使用 RSpecs 私有 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
Run Code Online (Sandbox Code Playgroud)