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

3

5

I am trying to write a Git pre-commit hook that would not let the user commit if there is an example that is tagged with :focus.

Using RSpec's API (okay even if it is private), is there any way to find out the number of examples with the :focus filter?

I found the example_count-instance_method. It could be useful but I'm not sure how it can be called from an external script.

Maurilla answered 24/5, 2016 at 9:40 Comment(0)
M
4

Here is an Overcommit pre_commit hook that uses RSpecs private API to find out specs with :focus filter:

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
Maurilla answered 27/5, 2016 at 11:53 Comment(0)
H
2

Rather than calling RSpec Ruby code, I'd do it through RSpec's command-line interface using the --dry-run flag. Here's a pre-commit hook that does it that way:

#!/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
Haematogenesis answered 26/5, 2016 at 17:9 Comment(2)
I already had it working this way. But was considering a pure Ruby approach if possible since I was using OverCommit.Maurilla
Though this isn't what OP was after, I like this solution. Thanks! However, the grep pattern should be changed to '^0 examples' so that it does not return a false negative when the number of focused tests ends in a zero.Calicut
Y
1

Not entirely sure if this will help or answer the question, but I currently use this set of githooks to make sure I don't commit obvious mistakes, and this pull request adds a check for :focus/focus: true/:focus => true in RSpec files.

Yazzie answered 26/5, 2016 at 22:25 Comment(3)
I thought it would be better if RSpec is aware of the filters. This will help us to overcome issues like adding a :focus in a code comment failing the git-hook.Maurilla
BTW, you may want to consider :focus => true as well in your commit hook.Maurilla
@hallucinations, nice pick up: I'd completely forgotten about hashrockets. Fixed.Yazzie

© 2022 - 2024 — McMap. All rights reserved.