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 24, 2021
1 parent cb5c0dc commit a8d2448
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

* Add missing documentation for `single_statement_only` style of `RSpec/ImplicitSubject` cop. ([@tejasbubane][])
* Fix an exception in `DescribedClass` when accessing a constant on a variable in a spec that is nested in a namespace. ([@rrosenblum][])
* Fix false negative in `RSpec/ExpectChange` cop with block style and chained method call. ([@tejasbubane][])

## 2.3.0 (2021-04-28)

Expand Down
6 changes: 3 additions & 3 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 $_ (sym $_))
PATTERN

# @!method expect_change_with_block(node)
Expand All @@ -55,9 +55,9 @@ 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 'registers an offense for 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 a8d2448

Please sign in to comment.