-
-
Notifications
You must be signed in to change notification settings - Fork 270
/
leading_subject.rb
90 lines (78 loc) · 2.29 KB
/
leading_subject.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
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# Enforce that subject is the first definition in the test.
#
# @example
# # bad
# let(:params) { blah }
# subject { described_class.new(params) }
#
# before { do_something }
# subject { described_class.new(params) }
#
# it { expect_something }
# subject { described_class.new(params) }
# it { expect_something_else }
#
#
# # good
# subject { described_class.new(params) }
# let(:params) { blah }
#
# # good
# subject { described_class.new(params) }
# before { do_something }
#
# # good
# subject { described_class.new(params) }
# it { expect_something }
# it { expect_something_else }
#
class LeadingSubject < Base
extend AutoCorrector
MSG = 'Declare `subject` above any other `%<offending>s` declarations.'
def on_block(node)
return unless subject?(node) && !in_spec_block?(node)
check_previous_nodes(node)
end
def check_previous_nodes(node)
offending_node(node) do |offender|
msg = format(MSG, offending: offender.method_name)
add_offense(node, message: msg) do |corrector|
autocorrect(corrector, node, offender)
end
end
end
private
def offending_node(node)
parent(node).each_child_node.find do |sibling|
break if sibling.equal?(node)
yield sibling if offending?(sibling)
end
end
def parent(node)
node.each_ancestor(:block).first.body
end
def autocorrect(corrector, node, sibling)
RuboCop::RSpec::Corrector::MoveNode.new(
node, corrector, processed_source
).move_before(sibling)
end
def offending?(node)
let?(node) ||
hook?(node) ||
example?(node) ||
spec_group?(node) ||
include?(node)
end
def in_spec_block?(node)
node.each_ancestor(:block).any? do |ancestor|
example?(ancestor)
end
end
end
end
end
end