/
named_subject.rb
76 lines (69 loc) · 2.24 KB
/
named_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
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# Checks for explicitly referenced test subjects.
#
# RSpec lets you declare an "implicit subject" using `subject { ... }`
# which allows for tests like `it { is_expected.to be_valid }`.
# If you need to reference your test subject you should explicitly
# name it using `subject(:your_subject_name) { ... }`. Your test subjects
# should be the most important object in your tests so they deserve
# a descriptive name.
#
# This cop can be configured in your configuration using the
# `IgnoreSharedExamples` which will not report offenses for implicit
# subjects in shared example groups.
#
# @example
# # bad
# RSpec.describe User do
# subject { described_class.new }
#
# it 'is valid' do
# expect(subject.valid?).to be(true)
# end
# end
#
# # good
# RSpec.describe Foo do
# subject(:user) { described_class.new }
#
# it 'is valid' do
# expect(user.valid?).to be(true)
# end
# end
#
# # also good
# RSpec.describe Foo do
# subject(:user) { described_class.new }
#
# it { is_expected.to be_valid }
# end
class NamedSubject < Cop
MSG = 'Name your test subject if you need '\
'to reference it explicitly.'
def_node_matcher :rspec_block?, <<-PATTERN
{
#{Examples::ALL.block_pattern}
#{Hooks::ALL.block_pattern}
}
PATTERN
def_node_matcher :shared_example?, <<-PATTERN
#{SharedGroups::EXAMPLES.block_pattern}
PATTERN
def_node_search :subject_usage, '$(send nil? :subject)'
def on_block(node)
return if !rspec_block?(node) || ignored_shared_example?(node)
subject_usage(node) do |subject_node|
add_offense(subject_node, location: :selector)
end
end
def ignored_shared_example?(node)
cop_config['IgnoreSharedExamples'] &&
node.each_ancestor(:block).any?(&method(:shared_example?))
end
end
end
end
end