-
-
Notifications
You must be signed in to change notification settings - Fork 269
/
repeated_description.rb
98 lines (87 loc) · 2.46 KB
/
repeated_description.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# Check for repeated description strings in example groups.
#
# @example
# # bad
# RSpec.describe User do
# it 'is valid' do
# # ...
# end
#
# it 'is valid' do
# # ...
# end
# end
#
# # good
# RSpec.describe User do
# it 'is valid when first and last name are present' do
# # ...
# end
#
# it 'is valid when last name only is present' do
# # ...
# end
# end
#
# # good
# RSpec.describe User do
# it 'is valid' do
# # ...
# end
#
# it 'is valid', :flag do
# # ...
# end
# end
#
class RepeatedDescription < Base
MSG = "Don't repeat descriptions within an example group."
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return unless example_group?(node)
repeated_descriptions(node).each do |description|
add_offense(description)
end
repeated_its(node).each do |its|
add_offense(its)
end
end
private
# Select examples in the current scope with repeated description strings
def repeated_descriptions(node)
grouped_examples =
RuboCop::RSpec::ExampleGroup.new(node)
.examples
.reject { |n| n.definition.method?(:its) }
.group_by { |example| example_signature(example) }
grouped_examples
.select { |signatures, group| signatures.any? && group.size > 1 }
.values
.flatten
.map(&:definition)
end
def repeated_its(node)
grouped_its =
RuboCop::RSpec::ExampleGroup.new(node)
.examples
.select { |n| n.definition.method?(:its) }
.group_by { |example| its_signature(example) }
grouped_its
.select { |signatures, group| signatures.any? && group.size > 1 }
.values
.flatten
.map(&:to_node)
end
def example_signature(example)
[example.metadata, example.doc_string]
end
def its_signature(example)
[example.doc_string, example]
end
end
end
end
end