Skip to content

Commit

Permalink
Merge pull request #1975 from corsonknowles/require_void_expect_acts_…
Browse files Browse the repository at this point in the history
…inside_an_example_block

Require VoidExpect to operate inside an example block
  • Loading branch information
bquorning authored Oct 25, 2024
2 parents 954a45f + 427d19d commit 530af44
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Master (Unreleased)

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

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 530af44

Please sign in to comment.