forked from rubocop/rubocop-rspec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscattered_setup.rb
67 lines (60 loc) · 1.81 KB
/
scattered_setup.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# Checks for setup scattered across multiple hooks in an example group.
#
# Unify `before`, `after`, and `around` hooks when possible.
#
# @example
# # bad
# describe Foo do
# before { setup1 }
# before { setup2 }
# end
#
# # good
# describe Foo do
# before do
# setup1
# setup2
# end
# end
#
class ScatteredSetup < Base
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)
end
end
end
def repeated_hooks(node)
hooks = RuboCop::RSpec::ExampleGroup.new(node)
.hooks
.select(&:knowable_scope?)
.group_by { |hook| [hook.name, hook.scope, hook.metadata] }
.values
.reject(&:one?)
hooks.map do |hook|
hook.map(&:to_node)
end
end
def lines_msg(numbers)
if numbers.size == 1
"line #{numbers.first}"
else
"lines #{numbers.join(', ')}"
end
end
end
end
end
end