Skip to content

Commit

Permalink
[Fix rubocop#1799] Fix RSpec/ExampleWording autocorrection to escap…
Browse files Browse the repository at this point in the history
…e quotes
  • Loading branch information
r7kamura committed Feb 6, 2024
1 parent 31c6344 commit 28ec60b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
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 'keeps single-quote after autocorrection' 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 'keeps double-quote after autocorrection' 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 28ec60b

Please sign in to comment.