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 7, 2024
1 parent 31c6344 commit ffc6a8c
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
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` in escaping and `%` string literals. ([@r7kamura])

## 2.26.1 (2024-01-05)

Expand Down
23 changes: 16 additions & 7 deletions lib/rubocop/cop/rspec/example_wording.rb
Expand Up @@ -92,18 +92,27 @@ 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

def docstring(node)
expr = node.source_range
if node.str_type? && !node.heredoc?
node.source_range.with(
begin_pos: node.loc.begin.end_pos,
end_pos: node.loc.end.begin_pos
)
else
node.source_range.adjust(begin_pos: 1, end_pos: -1)
end
end

Parser::Source::Range.new(
expr.source_buffer,
expr.begin_pos + 1,
expr.end_pos - 1
)
def needs_escape?(node)
node.value.include?(node.loc.end.source)
end

def replacement_text(node)
Expand Down
52 changes: 52 additions & 0 deletions spec/rubocop/cop/rspec/example_wording_spec.rb
Expand Up @@ -351,5 +351,57 @@
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

it 'corrects %(...) quote' do
expect_offense(<<~RUBY)
it %q(should return foo (bar)) do
^^^^^^^^^^^^^^^^^^^^^^^ Do not use should when describing your tests.
end
RUBY

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

it 'corrects %!...! 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 ffc6a8c

Please sign in to comment.