forked from rubocop/rubocop-rspec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiple_subjects.rb
83 lines (72 loc) · 2.34 KB
/
multiple_subjects.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
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# Checks if an example group defines `subject` multiple times.
#
# @example
#
# # bad
# describe Foo do
# subject(:user) { User.new }
# subject(:post) { Post.new }
# end
#
# # good
# describe Foo do
# let(:user) { User.new }
# subject(:post) { Post.new }
# end
#
# The autocorrect behavior for this cop depends on the type of
# duplication:
#
# - If multiple named subjects are defined then this probably indicates
# that the overwritten subjects (all subjects except the last
# definition) are effectively being used to define helpers. In this
# case they are replaced with `let`.
#
# - If multiple unnamed subjects are defined though then this can *only*
# be dead code and we remove the overwritten subject definitions.
#
# - If subjects are defined with `subject!` then we don't autocorrect.
# This is enough of an edge case that people can just move this to
# a `before` hook on their own
class MultipleSubjects < Cop
include RangeHelp
MSG = 'Do not set more than one subject per example group'
def on_block(node)
return unless example_group?(node)
subjects = RuboCop::RSpec::ExampleGroup.new(node).subjects
subjects[0...-1].each do |subject|
add_offense(subject)
end
end
def autocorrect(node)
return unless node.method_name.equal?(:subject) # Ignore `subject!`
if named_subject?(node)
rename_autocorrect(node)
else
remove_autocorrect(node)
end
end
private
def named_subject?(node)
node.send_node.arguments?
end
def rename_autocorrect(node)
lambda do |corrector|
corrector.replace(node.send_node.loc.selector, 'let')
end
end
def remove_autocorrect(node)
lambda do |corrector|
range = range_by_whole_lines(node.source_range,
include_final_newline: true)
corrector.remove(range)
end
end
end
end
end
end