Skip to content

Commit

Permalink
Fix RSpec/ExampleWording autocorrection to correctly escape quotes …
Browse files Browse the repository at this point in the history
…on str node case
  • Loading branch information
r7kamura committed Feb 6, 2024
1 parent 31c6344 commit a3d4ba5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- Support correcting `assert_not_equal` and `assert_not_nil` in `RSpec/Rails/MinitestAssertions`. ([@G-Rath])
- Fix a false positive for `RSpec/ExpectActual` when used with rspec-rails routing matchers. ([@naveg])
- Add new `RSpec/RepeatedSubjectCall` cop. ([@drcapulet])
- Fix `RSpec/ExampleWording` autocorrection to correctly escape quotes on str node case. ([@r7kamura])

## 2.26.1 (2024-01-05)

Expand Down
11 changes: 10 additions & 1 deletion lib/rubocop/cop/rspec/example_wording.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ def add_wording_offense(node, message)
add_offense(docstring, message: message) do |corrector|
next if node.heredoc?

corrector.replace(docstring, replacement_text(node))
if node.str_type? && needs_escape?(node)
corrector.replace(node, replacement_text(node).inspect)
else
corrector.replace(docstring, replacement_text(node))
end
end
end

Expand All @@ -106,6 +110,11 @@ def docstring(node)
)
end

def needs_escape?(node)
node.value.include?(node.loc.begin.source) ||
node.value.include?(node.loc.end.source)
end

def replacement_text(node)
text = text(node)

Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/rspec/example_wording_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -351,5 +351,31 @@
end
RUBY
end

it 'corrects escaped single-quote' do
expect_offense(<<~'RUBY')
it 'should return foo\'s bar' do
^^^^^^^^^^^^^^^^^^^^^^^^ Do not use should when describing your tests.
end
RUBY

expect_correction(<<~RUBY)
it "returns foo's bar" do
end
RUBY
end

it 'corrects escaped double-quote' do
expect_offense(<<~'RUBY')
it "should return \"foo\"" do
^^^^^^^^^^^^^^^^^^^^^ Do not use should when describing your tests.
end
RUBY

expect_correction(<<~'RUBY')
it "returns \"foo\"" do
end
RUBY
end
end
end

0 comments on commit a3d4ba5

Please sign in to comment.