Skip to content

Commit 47cb738

Browse files
committed
Recognize stubbing of described_class in RSpec/SubjectStub
1 parent b0fda47 commit 47cb738

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Master (Unreleased)
44

5+
- Recognize stubbing of `described_class` in `RSpec/SubjectStub`. ([@lovro-bikic])
6+
57
## 3.6.0 (2025-04-18)
68

79
- Fix false positive in `RSpec/Pending`, where it would mark the default block `it` as an offense. ([@bquorning])

lib/rubocop/cop/rspec/subject_stub.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@ module RSpec
3838
# end
3939
# end
4040
#
41+
# # bad - described_class stubs are recognized as well
42+
# describe Article do
43+
# it 'indicates that the author is unknown' do
44+
# article = double(Article, description: 'by an unknown author')
45+
# allow(described_class).to receive(:new).and_return(article)
46+
#
47+
# expect(Article.new.description).to include('by an unknown author')
48+
# end
49+
# end
50+
#
4151
# # good
4252
# describe Article do
4353
# subject(:article) { Article.new(author: nil) }
@@ -141,7 +151,7 @@ def find_subject_expectations(node, subject_names = [], &block)
141151
subject_names = [*subject_names, *@explicit_subjects[node]]
142152
subject_names -= @subject_overrides[node] if @subject_overrides[node]
143153

144-
names = Set[*subject_names, :subject]
154+
names = Set[*subject_names, :subject, :described_class]
145155
expectation_detected = message_expectation?(node, names)
146156
return yield(node) if expectation_detected
147157

spec/rubocop/cop/rspec/subject_stub_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,17 @@
364364
RUBY
365365
end
366366

367+
it 'flags when described_class is mocked' do
368+
expect_offense(<<~RUBY)
369+
describe Foo do
370+
it 'uses described_class' do
371+
expect(described_class).to receive(:bar).and_return(baz)
372+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not stub methods of the object under test.
373+
end
374+
end
375+
RUBY
376+
end
377+
367378
it 'flags when there are several top level example groups' do
368379
expect_offense(<<~RUBY)
369380
RSpec.describe Foo do

0 commit comments

Comments
 (0)