|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module RuboCop |
| 4 | + module Cop |
| 5 | + module RSpec |
| 6 | + # Check for repeated describe and context block body. |
| 7 | + # |
| 8 | + # @example |
| 9 | + # |
| 10 | + # # bad |
| 11 | + # describe 'cool feature x' do |
| 12 | + # it { cool_predicate } |
| 13 | + # end |
| 14 | + # |
| 15 | + # describe 'cool feature y' do |
| 16 | + # it { cool_predicate } |
| 17 | + # end |
| 18 | + # |
| 19 | + # # good |
| 20 | + # describe 'cool feature' do |
| 21 | + # it { cool_predicate } |
| 22 | + # end |
| 23 | + # |
| 24 | + # describe 'another cool feature' do |
| 25 | + # it { another_predicate } |
| 26 | + # end |
| 27 | + # |
| 28 | + # # good |
| 29 | + # context 'when case x', :tag do |
| 30 | + # it { cool_predicate } |
| 31 | + # end |
| 32 | + # |
| 33 | + # context 'when case y' do |
| 34 | + # it { cool_predicate } |
| 35 | + # end |
| 36 | + # |
| 37 | + class RepeatedExampleGroupBody < Cop |
| 38 | + MSG = 'Repeated %<group>s block body on line(s) %<loc>s' |
| 39 | + |
| 40 | + def_node_matcher :several_example_groups?, <<-PATTERN |
| 41 | + (begin <#example_group_with_body? #example_group_with_body? ...>) |
| 42 | + PATTERN |
| 43 | + |
| 44 | + def_node_matcher :metadata, '(block (send _ _ _ $...) ...)' |
| 45 | + def_node_matcher :body, '(block _ args $...)' |
| 46 | + |
| 47 | + def_node_matcher :skip_or_pending?, <<-PATTERN |
| 48 | + (block <(send nil? {:skip :pending}) ...>) |
| 49 | + PATTERN |
| 50 | + |
| 51 | + def on_begin(node) |
| 52 | + return unless several_example_groups?(node) |
| 53 | + |
| 54 | + repeated_group_bodies(node).each do |group, repeats| |
| 55 | + add_offense(group, message: message(group, repeats)) |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + private |
| 60 | + |
| 61 | + def repeated_group_bodies(node) |
| 62 | + node |
| 63 | + .children |
| 64 | + .select { |child| example_group_with_body?(child) } |
| 65 | + .reject { |child| skip_or_pending?(child) } |
| 66 | + .group_by { |group| signature_keys(group) } |
| 67 | + .values |
| 68 | + .reject(&:one?) |
| 69 | + .flat_map { |groups| add_repeated_lines(groups) } |
| 70 | + end |
| 71 | + |
| 72 | + def add_repeated_lines(groups) |
| 73 | + repeated_lines = groups.map(&:first_line) |
| 74 | + groups.map { |group| [group, repeated_lines - [group.first_line]] } |
| 75 | + end |
| 76 | + |
| 77 | + def signature_keys(group) |
| 78 | + [metadata(group), body(group)] |
| 79 | + end |
| 80 | + |
| 81 | + def message(group, repeats) |
| 82 | + format(MSG, group: group.method_name, loc: repeats) |
| 83 | + end |
| 84 | + end |
| 85 | + end |
| 86 | + end |
| 87 | +end |
0 commit comments