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 14, 2024
1 parent 961e544 commit 3f38ff9
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
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
43 changes: 43 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,47 @@
end
RUBY
end

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

it 'flags bare `expect` in example block' do
expect_offense(<<~RUBY)
it 'something' do
expect
^^^^^^ Do not use `expect()` without `.to` or `.not_to`. Chain the methods or remove it.
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 method expect' do
expect_no_offenses(<<~RUBY)
expect
RUBY
end

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

it 'ignores unrelated expect object method' do
expect_no_offenses(<<~RUBY)
MyObject.expect
RUBY
end
end
end

0 comments on commit 3f38ff9

Please sign in to comment.