Skip to content

Commit 28ec60b

Browse files
committed
[Fix rubocop#1799] Fix RSpec/ExampleWording autocorrection to escape quotes
1 parent 31c6344 commit 28ec60b

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

lib/rubocop/cop/rspec/example_wording.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,11 @@ def add_wording_offense(node, message)
9292
add_offense(docstring, message: message) do |corrector|
9393
next if node.heredoc?
9494

95-
corrector.replace(docstring, replacement_text(node))
95+
if node.str_type? && needs_escape?(node)
96+
corrector.replace(node, replacement_text(node).inspect)
97+
else
98+
corrector.replace(docstring, replacement_text(node))
99+
end
96100
end
97101
end
98102

@@ -106,6 +110,11 @@ def docstring(node)
106110
)
107111
end
108112

113+
def needs_escape?(node)
114+
node.value.include?(node.loc.begin.source) ||
115+
node.value.include?(node.loc.end.source)
116+
end
117+
109118
def replacement_text(node)
110119
text = text(node)
111120

spec/rubocop/cop/rspec/example_wording_spec.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,5 +351,31 @@
351351
end
352352
RUBY
353353
end
354+
355+
it 'keeps single-quote after autocorrection' do
356+
expect_offense(<<~'RUBY')
357+
it 'should return foo\'s bar' do
358+
^^^^^^^^^^^^^^^^^^^^^^^^ Do not use should when describing your tests.
359+
end
360+
RUBY
361+
362+
expect_correction(<<~RUBY)
363+
it "returns foo's bar" do
364+
end
365+
RUBY
366+
end
367+
368+
it 'keeps double-quote after autocorrection' do
369+
expect_offense(<<~'RUBY')
370+
it "should return \"foo\"" do
371+
^^^^^^^^^^^^^^^^^^^^^ Do not use should when describing your tests.
372+
end
373+
RUBY
374+
375+
expect_correction(<<~'RUBY')
376+
it "returns \"foo\"" do
377+
end
378+
RUBY
379+
end
354380
end
355381
end

0 commit comments

Comments
 (0)