Skip to content

Commit

Permalink
Fix a false positive for Lint/FormatParameterMismatch when format s…
Browse files Browse the repository at this point in the history
…tring is only interpolated string

This PR is Follow up: #11464 (comment)
  • Loading branch information
ydah committed Jan 24, 2023
1 parent a6620d5 commit b5a7217
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11487](https://github.com/rubocop/rubocop/pull/11487): Fix a false positive for `Lint/FormatParameterMismatch` when format string is only interpolated string. ([@ydah][])
1 change: 1 addition & 0 deletions lib/rubocop/cop/lint/format_parameter_mismatch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def offending_node?(node)
num_of_format_args, num_of_expected_fields = count_matches(node)

return false if num_of_format_args == :unknown
return false if num_of_expected_fields.zero? && node.child_nodes.first.dstr_type?

matched_arguments_count?(num_of_expected_fields, num_of_format_args)
end
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/lint/format_parameter_mismatch_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@
RUBY
end

it 'registers an offense when there are no expected format string' do
expect_offense(<<~RUBY)
format("something", 1)
^^^^^^ Number of arguments (1) to `format` doesn't match the number of fields (0).
RUBY
end

it 'registers an offense when there are more arguments than expected' do
expect_offense(<<~RUBY)
format("%s %s", 1, 2, 3)
Expand Down Expand Up @@ -314,6 +321,10 @@
expect_no_offenses('format("#{foo} %s", "bar")')
end

it 'does not register an offense when only interpolated string' do
expect_no_offenses('format("#{foo}", "bar", "baz")')
end

it 'registers an offense for String#% when the fields do not match' do
expect_offense(<<~'RUBY')
"%s %s" % ["#{foo}", 1, 2]
Expand All @@ -324,6 +335,10 @@
it 'does not register an offense for String#% when the fields match' do
expect_no_offenses('"%s %s" % ["#{foo}", 1]')
end

it 'does not register an offense for String#% when only interpolated string' do
expect_no_offenses('"#{foo}" % [1, 2]')
end
end

context 'with interpolated string in argument' do
Expand Down

0 comments on commit b5a7217

Please sign in to comment.