diff --git a/lib/rubocop/cop/layout/space_around_method_call_operator.rb b/lib/rubocop/cop/layout/space_around_method_call_operator.rb index 78b9b473fac..160e28b1d3e 100644 --- a/lib/rubocop/cop/layout/space_around_method_call_operator.rb +++ b/lib/rubocop/cop/layout/space_around_method_call_operator.rb @@ -72,7 +72,7 @@ def check_and_add_offense(node, add_left_offense = true) left = previous_token(operator) right = next_token(operator) - if valid_right_token?(right, operator) + if !right.comment? && valid_right_token?(right, operator) no_space_offenses(node, operator, right, MSG) end return unless valid_left_token?(left, operator) @@ -121,7 +121,9 @@ def left_token_for_auto_correction(node, operator) def right_token_for_auto_correction(operator) right_token = next_token(operator) - return right_token if valid_right_token?(right_token, operator) + if !right_token.comment? && valid_right_token?(right_token, operator) + return right_token + end operator end diff --git a/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb b/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb index 970cc6b6961..e4e9e97880a 100644 --- a/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb +++ b/spec/rubocop/cop/layout/space_around_method_call_operator_spec.rb @@ -177,6 +177,28 @@ foo.bar.buzz RUBY end + + context 'when there is a space between `.` operator and a comment' do + it 'does not register an offense when there is not a space before `.`' do + expect_no_offenses(<<~RUBY) + foo. # comment + bar.baz + RUBY + end + + it 'registers an offense when there is a space before `.`' do + expect_offense(<<~RUBY) + foo . # comment + ^ Avoid using spaces around a method call operator. + bar.baz + RUBY + + expect_correction(<<~RUBY) + foo. # comment + bar.baz + RUBY + end + end end context 'safe navigation operator' do