Skip to content

Commit 7e3149d

Browse files
committed
Require VoidExpect operate inside an example block
1 parent 5850cf3 commit 7e3149d

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-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+
- Fix `RSpec/VoidExpect` to only operate inside an example block. ([@corsonknowles])
6+
57
## 3.1.0 (2024-10-01)
68

79
- Add `RSpec/StringAsInstanceDoubleConstant` to check for and correct strings used as instance_doubles. ([@corsonknowles])

lib/rubocop/cop/rspec/void_expect.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,14 @@ class VoidExpect < Base
2929

3030
def on_send(node)
3131
return unless expect?(node)
32+
return unless inside_example?(node)
3233

3334
check_expect(node)
3435
end
3536

3637
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
3738
return unless expect_block?(node)
39+
return unless inside_example?(node)
3840

3941
check_expect(node)
4042
end
@@ -49,11 +51,14 @@ def check_expect(node)
4951

5052
def void?(expect)
5153
parent = expect.parent
52-
return true unless parent
5354
return true if parent.begin_type?
5455

5556
parent.block_type? && parent.body == expect
5657
end
58+
59+
def inside_example?(node)
60+
node.each_ancestor(:block).any? { |ancestor| example?(ancestor) }
61+
end
5762
end
5863
end
5964
end

spec/rubocop/cop/rspec/void_expect_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,26 @@
4444
end
4545
RUBY
4646
end
47+
48+
it 'ignores unrelated method named expect in an example block' do
49+
expect_no_offenses(<<~RUBY)
50+
it 'something' do
51+
MyObject.expect(:foo)
52+
end
53+
RUBY
54+
end
55+
56+
context 'when expect has no parent node' do
57+
it 'does not register an offense' do
58+
expect_no_offenses(<<~RUBY)
59+
expect(something)
60+
RUBY
61+
end
62+
63+
it 'does not register an offense for unrelated expect with block' do
64+
expect_no_offenses(<<~RUBY)
65+
expect { block_contents }
66+
RUBY
67+
end
68+
end
4769
end

0 commit comments

Comments
 (0)