Skip to content

Commit 8d2996e

Browse files
committed
Fix implicit subjects mocked/stubbed not detected
[Implicit Subject](https://relishapp.com/rspec/rspec-core/v/3-8/docs/subject/implicitly-defined-subject) had not been detected by the `Rspec/SubjectStub`, which reported false negative cases. As suggested by [@pirij][], there are solutions to recursively traverse through AST (either upward or downward). However, to the best of my knowledge, they might require a fair amount of changes how the cop is currently working and impact the runtime performance. I've chosen the somewhat safe fix that reports the defaut `:subject` if there is no named nor unnamed subject declared.
1 parent abdb94a commit 8d2996e

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Master (Unreleased)
44

55
* Fix documentation rake task to support Rubocop 0.75. ([@nickcampbell18][])
6+
* Fix `RSpec/SubjectStub` to detect implicit subjects stubbed. ([@QQism][])
67

78
## 1.36.0 (2019-09-27)
89

@@ -455,3 +456,4 @@ Compatibility release so users can upgrade RuboCop to 0.51.0. No new features.
455456
[@nc-holodakg]: https://github.com/nc-holodakg
456457
[@onumis]: https://github.com/onumis
457458
[@nickcampbell18]: https://github.com/nickcampbell18
459+
[@QQism]: https://github.com/QQism

lib/rubocop/cop/rspec/subject_stub.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,10 @@ def redefines_subject?(node)
132132
# @yieldparam subject_name [Symbol] name of subject being defined
133133
# @yieldparam parent [RuboCop::Node] parent of subject definition
134134
def find_subject(node, parent: nil, &block)
135-
subject(node) { |name| yield(name, parent) }
135+
# An implicit subject is defined by RSpec when no subject is declared
136+
subject_name = subject(node) || :subject
137+
138+
yield(subject_name, parent) if parent
136139

137140
node.each_child_node do |child|
138141
find_subject(child, parent: node, &block)

spec/rubocop/cop/rspec/subject_stub_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,4 +290,15 @@
290290
end
291291
RUBY
292292
end
293+
294+
it 'flags when an implicit subject is mocked' do
295+
expect_offense(<<-RUBY)
296+
describe Foo do
297+
it 'uses an implicit subject' do
298+
expect(subject).to receive(:bar).and_return(baz)
299+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not stub methods of the object under test.
300+
end
301+
end
302+
RUBY
303+
end
293304
end

0 commit comments

Comments
 (0)