Skip to content

Commit

Permalink
Fix false negative in RSpec/ExpectChange cop with block style and c…
Browse files Browse the repository at this point in the history
…hained method call

Closes #1143
  • Loading branch information
tejasbubane committed May 19, 2021
1 parent 721fd6c commit 67e8f6c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
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 false negative in `RSpec/ExpectChange` cop with block style and chained method call. ([@tejasbubane][])

## 2.3.0 (2021-04-28)

* Allow `RSpec/ContextWording` to accept multi-word prefixes. ([@hosamaly][])
Expand Down
7 changes: 3 additions & 4 deletions lib/rubocop/cop/rspec/expect_change.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class ExpectChange < Base

# @!method expect_change_with_arguments(node)
def_node_matcher :expect_change_with_arguments, <<-PATTERN
(send nil? :change ({const send} nil? $_) (sym $_))
(send nil? :change $({const send} ...) (sym $_))
PATTERN

# @!method expect_change_with_block(node)
Expand All @@ -53,11 +53,10 @@ class ExpectChange < Base

def on_send(node)
return unless style == :block

expect_change_with_arguments(node) do |receiver, message|
msg = format(MSG_CALL, obj: receiver, attr: message)
msg = format(MSG_CALL, obj: receiver.source, attr: message)
add_offense(node, message: msg) do |corrector|
replacement = "change { #{receiver}.#{message} }"
replacement = "change { #{receiver.source}.#{message} }"
corrector.replace(node, replacement)
end
end
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/rspec/expect_change_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,21 @@
RUBY
end

it 'flags change matcher with chained method call' do
expect_offense(<<-RUBY)
it do
expect { paint_users! }.to change(users.green, :count).by(1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `change { users.green.count }`.
end
RUBY

expect_correction(<<-RUBY)
it do
expect { paint_users! }.to change { users.green.count }.by(1)
end
RUBY
end

it 'ignores methods called change' do
expect_no_offenses(<<-RUBY)
it do
Expand Down

0 comments on commit 67e8f6c

Please sign in to comment.