From 0ce6785851510ccb49f0d1edc0220aca46f815f5 Mon Sep 17 00:00:00 2001 From: Jacopo Date: Tue, 3 Oct 2017 10:35:01 +0200 Subject: Replaces `tag: true` into `:tag` in the specs Replaces all the explicit include metadata syntax in the specs (tag: true) into the implicit one (:tag). Added a cop to prevent future errors and handle autocorrection. --- rubocop/cop/rspec/verbose_include_metadata.rb | 74 +++++++++++++++++++++++++++ rubocop/rubocop.rb | 1 + 2 files changed, 75 insertions(+) create mode 100644 rubocop/cop/rspec/verbose_include_metadata.rb (limited to 'rubocop') diff --git a/rubocop/cop/rspec/verbose_include_metadata.rb b/rubocop/cop/rspec/verbose_include_metadata.rb new file mode 100644 index 00000000000..58390622d60 --- /dev/null +++ b/rubocop/cop/rspec/verbose_include_metadata.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +require 'rubocop-rspec' + +module RuboCop + module Cop + module RSpec + # Checks for verbose include metadata used in the specs. + # + # @example + # # bad + # describe MyClass, js: true do + # end + # + # # good + # describe MyClass, :js do + # end + class VerboseIncludeMetadata < Cop + MSG = 'Use `%s` instead of `%s`.' + + SELECTORS = %i[describe context feature example_group it specify example scenario its].freeze + + def_node_matcher :include_metadata, <<-PATTERN + (send {(const nil :RSpec) nil} {#{SELECTORS.map(&:inspect).join(' ')}} + !const + ... + (hash $...)) + PATTERN + + def_node_matcher :invalid_metadata?, <<-PATTERN + (pair + (sym $...) + (true)) + PATTERN + + def on_send(node) + invalid_metadata_matches(node) do |match| + add_offense(node, :expression, format(MSG, good(match), bad(match))) + end + end + + def autocorrect(node) + lambda do |corrector| + invalid_metadata_matches(node) do |match| + corrector.replace(match.loc.expression, good(match)) + end + end + end + + private + + def invalid_metadata_matches(node) + include_metadata(node) do |matches| + matches.select(&method(:invalid_metadata?)).each do |match| + yield match + end + end + end + + def bad(match) + "#{metadata_key(match)}: true" + end + + def good(match) + ":#{metadata_key(match)}" + end + + def metadata_key(match) + match.children[0].source + end + end + end + end +end diff --git a/rubocop/rubocop.rb b/rubocop/rubocop.rb index 1b6e8991a17..1df23899efb 100644 --- a/rubocop/rubocop.rb +++ b/rubocop/rubocop.rb @@ -21,3 +21,4 @@ require_relative 'cop/migration/reversible_add_column_with_default' require_relative 'cop/migration/timestamps' require_relative 'cop/migration/update_column_in_batches' require_relative 'cop/rspec/single_line_hook' +require_relative 'cop/rspec/verbose_include_metadata' -- cgit v1.2.1