Skip to content

Commit

Permalink
Require VoidExpect operate inside an example block
Browse files Browse the repository at this point in the history
  • Loading branch information
corsonknowles committed Oct 18, 2024
1 parent 5850cf3 commit 7e3149d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Master (Unreleased)

- Fix `RSpec/VoidExpect` to only operate inside an example block. ([@corsonknowles])

## 3.1.0 (2024-10-01)

- Add `RSpec/StringAsInstanceDoubleConstant` to check for and correct strings used as instance_doubles. ([@corsonknowles])
Expand Down
7 changes: 6 additions & 1 deletion lib/rubocop/cop/rspec/void_expect.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@ class VoidExpect < Base

def on_send(node)
return unless expect?(node)
return unless inside_example?(node)

check_expect(node)
end

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return unless expect_block?(node)
return unless inside_example?(node)

check_expect(node)
end
Expand All @@ -49,11 +51,14 @@ def check_expect(node)

def void?(expect)
parent = expect.parent
return true unless parent
return true if parent.begin_type?

parent.block_type? && parent.body == expect
end

def inside_example?(node)
node.each_ancestor(:block).any? { |ancestor| example?(ancestor) }
end
end
end
end
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/rspec/void_expect_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,26 @@
end
RUBY
end

it 'ignores unrelated method named expect in an example block' do
expect_no_offenses(<<~RUBY)
it 'something' do
MyObject.expect(:foo)
end
RUBY
end

context 'when expect has no parent node' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
expect(something)
RUBY
end

it 'does not register an offense for unrelated expect with block' do
expect_no_offenses(<<~RUBY)
expect { block_contents }
RUBY
end
end
end

0 comments on commit 7e3149d

Please sign in to comment.