lib/rubocop/cop/rspec/scattered_setup.rb in rubocop-rspec-2.19.0 vs lib/rubocop/cop/rspec/scattered_setup.rb in rubocop-rspec-2.20.0

- old
+ new

@@ -21,24 +21,25 @@ # setup2 # end # end # class ScatteredSetup < Base + include RangeHelp + extend AutoCorrector + MSG = 'Do not define multiple `%<hook_name>s` hooks in the same ' \ 'example group (also defined on %<lines>s).' def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler return unless example_group?(node) repeated_hooks(node).each do |occurrences| - lines = occurrences.map(&:first_line) - occurrences.each do |occurrence| - lines_except_current = lines - [occurrence.first_line] - message = format(MSG, hook_name: occurrences.first.method_name, - lines: lines_msg(lines_except_current)) - add_offense(occurrence, message: message) + message = message(occurrences, occurrence) + add_offense(occurrence, message: message) do |corrector| + autocorrect(corrector, occurrences.first, occurrence) + end end end end private @@ -60,9 +61,25 @@ if numbers.size == 1 "line #{numbers.first}" else "lines #{numbers.join(', ')}" end + end + + def message(occurrences, occurrence) + lines = occurrences.map(&:first_line) + lines_except_current = lines - [occurrence.first_line] + format(MSG, hook_name: occurrences.first.method_name, + lines: lines_msg(lines_except_current)) + end + + def autocorrect(corrector, first_occurrence, occurrence) + return if first_occurrence == occurrence || !first_occurrence.body + + corrector.insert_after(first_occurrence.body, + "\n#{occurrence.body.source}") + corrector.remove(range_by_whole_lines(occurrence.source_range, + include_final_newline: true)) end end end end end