Skip to content

Commit

Permalink
Merge pull request #1697 from marocchino/fix-receive-messages-autocor…
Browse files Browse the repository at this point in the history
…rect

Fix autocorrect in `RSpec/ReceiveMessages`
  • Loading branch information
ydah committed Aug 18, 2023
2 parents ff30ce1 + b9804ce commit c5cb12a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Master (Unreleased)

- Fix an infinite loop error when `RSpec/ExcessiveDocstringSpacing` finds a description with non-ASCII leading/trailing whitespace. ([@bcgraham])
- Fix an incorrect autocorrect for `RSpec/ReceiveMessages` when return values declared between stubs. ([@marocchino])

## 2.23.2 (2023-08-09)

Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rspec/receive_messages.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def normalize_return_arg(return_arg)

def register_offense(item, repeated_lines, args)
add_offense(item, message: message(repeated_lines)) do |corrector|
if item.loc.line < repeated_lines.min
if item.loc.line > repeated_lines.max
replace_to_receive_messages(corrector, item, args)
else
corrector.remove(item_range_by_whole_lines(item))
Expand Down
26 changes: 24 additions & 2 deletions spec/rubocop/cop/rspec/receive_messages_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,31 @@

expect_correction(<<~RUBY)
before do
allow(Service).to receive_messages(foo: 1, bar: 2)
calling_some_method
calling_another_method
allow(Service).to receive_messages(foo: 1, bar: 2)
end
RUBY
end

it 'registers an offense when multiple messeages stubbed on the ' \
'same object and initialize return value between stubs' do
expect_offense(<<~RUBY)
before do
foo = Service.new
allow(Service).to receive(:foo).and_return(foo)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `receive_messages` instead of multiple stubs on lines [5].
bar = Service.new
allow(Service).to receive(:bar).and_return(bar)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `receive_messages` instead of multiple stubs on lines [3].
end
RUBY

expect_correction(<<~RUBY)
before do
foo = Service.new
bar = Service.new
allow(Service).to receive_messages(foo: foo, bar: bar)
end
RUBY
end
Expand Down Expand Up @@ -267,8 +289,8 @@
expect_correction(<<~RUBY)
before do
allow(Service).to receive(:foo).and_return(bar)
allow(Service).to receive_messages(bar: qux, baz: qux)
allow(Service).to receive(:foo).and_return(qux)
allow(Service).to receive_messages(bar: qux, baz: qux)
end
RUBY
end
Expand Down

0 comments on commit c5cb12a

Please sign in to comment.