Skip to content

Commit 530af44

Browse files
authored
Merge pull request #1975 from corsonknowles/require_void_expect_acts_inside_an_example_block
Require VoidExpect to operate inside an example block
2 parents 954a45f + 427d19d commit 530af44

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Master (Unreleased)
44

5+
- Fix `RSpec/VoidExpect` to only operate inside an example block. ([@corsonknowles])
56
- Change `RSpec/ContextWording` cop to always report an offense when both `Prefixes` and `AllowedPatterns` are empty. ([@ydah])
67
- Fix an error for `RSpec/ChangeByZero` when `change (...) .by (0)` and `change (...)`, concatenated with `and` and `or`. ([@ydah])
78

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)