repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/eval_with_location_spec.rb | spec/rubocop/cop/style/eval_with_location_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EvalWithLocation, :config do
it 'registers an offense when using `#eval` without any arguments' do
expect_offense(<<~RUBY)
eval <<-CODE
^^^^^^^^^^^^ Pass a binding, `__FILE__`, and `__LINE__` to `eval`.
do_something
CODE
RUBY
expect_no_corrections
end
it 'registers an offense when using `Kernel.eval` without any arguments' do
expect_offense(<<~RUBY)
Kernel.eval <<-CODE
^^^^^^^^^^^^^^^^^^^ Pass a binding, `__FILE__`, and `__LINE__` to `eval`.
do_something
CODE
RUBY
expect_no_corrections
end
it 'registers an offense when using `::Kernel.eval` without any arguments' do
expect_offense(<<~RUBY)
::Kernel.eval <<-CODE
^^^^^^^^^^^^^^^^^^^^^ Pass a binding, `__FILE__`, and `__LINE__` to `eval`.
do_something
CODE
RUBY
expect_no_corrections
end
it 'does not register an offense if `eval` is called on another object' do
expect_no_offenses(<<~RUBY)
foo.eval "CODE"
RUBY
end
it 'registers an offense when using `#eval` with `binding` only' do
expect_offense(<<~RUBY)
eval <<-CODE, binding
^^^^^^^^^^^^^^^^^^^^^ Pass a binding, `__FILE__`, and `__LINE__` to `eval`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
eval <<-CODE, binding, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `#eval` without lineno' do
expect_offense(<<~RUBY)
eval <<-CODE, binding, __FILE__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass a binding, `__FILE__`, and `__LINE__` to `eval`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
eval <<-CODE, binding, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `#eval` without lineno and with parenthesized method call' do
expect_offense(<<~RUBY)
eval(<<-CODE, binding, __FILE__)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass a binding, `__FILE__`, and `__LINE__` to `eval`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
eval(<<-CODE, binding, __FILE__, __LINE__ + 1)
do_something
CODE
RUBY
end
it 'registers an offense when using `#eval` with an incorrect line number' do
expect_offense(<<~RUBY)
eval 'do_something', binding, __FILE__, __LINE__ + 1
^^^^^^^^^^^^ Incorrect line number for `eval`; use `__LINE__` instead of `__LINE__ + 1`.
RUBY
expect_correction(<<~RUBY)
eval 'do_something', binding, __FILE__, __LINE__
RUBY
end
it 'registers an offense when using `#eval` with a heredoc and an incorrect line number' do
expect_offense(<<~RUBY)
eval <<-CODE, binding, __FILE__, __LINE__ + 2
^^^^^^^^^^^^ Incorrect line number for `eval`; use `__LINE__ + 1` instead of `__LINE__ + 2`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
eval <<-CODE, binding, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `#eval` with a string on a new line' do
expect_offense(<<~RUBY)
eval('puts 42',
binding,
__FILE__,
__LINE__)
^^^^^^^^ Incorrect line number for `eval`; use `__LINE__ - 3` instead of `__LINE__`.
RUBY
expect_correction(<<~RUBY)
eval('puts 42',
binding,
__FILE__,
__LINE__ - 3)
RUBY
end
it 'registers an offense when using `#class_eval` without any arguments' do
expect_offense(<<~RUBY)
C.class_eval <<-CODE
^^^^^^^^^^^^^^^^^^^^ Pass `__FILE__` and `__LINE__` to `class_eval`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
C.class_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `#module_eval` without any arguments' do
expect_offense(<<~RUBY)
M.module_eval <<-CODE
^^^^^^^^^^^^^^^^^^^^^ Pass `__FILE__` and `__LINE__` to `module_eval`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
M.module_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `#instance_eval` without any arguments' do
expect_offense(<<~RUBY)
foo.instance_eval <<-CODE
^^^^^^^^^^^^^^^^^^^^^^^^^ Pass `__FILE__` and `__LINE__` to `instance_eval`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
foo.instance_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `#instance_eval` with a string argument in parentheses' do
expect_offense(<<~RUBY)
instance_eval('@foo = foo')
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pass `__FILE__` and `__LINE__` to `instance_eval`.
RUBY
expect_correction(<<~RUBY)
instance_eval('@foo = foo', __FILE__, __LINE__)
RUBY
end
it 'registers an offense when using `#class_eval` with an incorrect lineno' do
expect_offense(<<~RUBY)
C.class_eval <<-CODE, __FILE__, __LINE__
^^^^^^^^ Incorrect line number for `class_eval`; use `__LINE__ + 1` instead of `__LINE__`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
C.class_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'accepts `eval` with a heredoc, a filename and `__LINE__ + 1`' do
expect_no_offenses(<<~RUBY)
eval <<-CODE, binding, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'accepts `eval` with a code that is a variable' do
expect_no_offenses(<<~RUBY)
code = something
eval code
RUBY
end
it 'accepts `eval` with a string, a filename and `__LINE__`' do
expect_no_offenses(<<~RUBY)
eval 'do_something', binding, __FILE__, __LINE__
RUBY
end
it 'accepts `eval` with a string, a filename and `__LINE__` on a new line' do
expect_no_offenses(<<~RUBY)
eval 'do_something', binding, __FILE__,
__LINE__ - 1
RUBY
end
it 'registers an offense when using `eval` with improper arguments' do
expect_offense(<<~RUBY)
eval <<-CODE, binding, 'foo', 'bar'
^^^^^ Incorrect line number for `eval`; use `__LINE__ + 1` instead of `'bar'`.
^^^^^ Incorrect file for `eval`; use `__FILE__` instead of `'foo'`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
eval <<-CODE, binding, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `instance_eval` with improper arguments' do
expect_offense(<<~RUBY)
instance_eval <<-CODE, 'foo', 'bar'
^^^^^ Incorrect line number for `instance_eval`; use `__LINE__ + 1` instead of `'bar'`.
^^^^^ Incorrect file for `instance_eval`; use `__FILE__` instead of `'foo'`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
instance_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `class_eval` with improper arguments' do
expect_offense(<<~RUBY)
class_eval <<-CODE, 'foo', 'bar'
^^^^^ Incorrect line number for `class_eval`; use `__LINE__ + 1` instead of `'bar'`.
^^^^^ Incorrect file for `class_eval`; use `__FILE__` instead of `'foo'`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
class_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using `module_eval` with improper arguments' do
expect_offense(<<~RUBY)
module_eval <<-CODE, 'foo', 'bar'
^^^^^ Incorrect line number for `module_eval`; use `__LINE__ + 1` instead of `'bar'`.
^^^^^ Incorrect file for `module_eval`; use `__FILE__` instead of `'foo'`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
module_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'registers an offense when using correct file argument but incorrect line' do
expect_offense(<<~RUBY)
module_eval <<-CODE, __FILE__, 'bar'
^^^^^ Incorrect line number for `module_eval`; use `__LINE__ + 1` instead of `'bar'`.
do_something
CODE
RUBY
expect_correction(<<~RUBY)
module_eval <<-CODE, __FILE__, __LINE__ + 1
do_something
CODE
RUBY
end
it 'does not register an offense when using eval with block argument' do
expect_no_offenses(<<~RUBY)
def self.included(base)
base.class_eval do
include OtherModule
end
end
RUBY
end
it 'does not register an offense when using eval with a line number from a method call' do
expect_no_offenses(<<~RUBY)
module_eval(<<~CODE, __FILE__, lineno)
do_something
CODE
RUBY
end
it 'does not register an offense when using eval with a line number from a variable' do
expect_no_offenses(<<~RUBY)
lineno = calc
module_eval(<<~CODE, __FILE__, lineno)
do_something
CODE
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb | spec/rubocop/cop/style/hash_as_last_array_item_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashAsLastArrayItem, :config do
context 'when EnforcedStyle is braces' do
let(:cop_config) { { 'EnforcedStyle' => 'braces' } }
it 'registers an offense and corrects when hash without braces' do
expect_offense(<<~RUBY)
[1, 2, one: 1, two: 2]
^^^^^^^^^^^^^^ Wrap hash in `{` and `}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, {one: 1, two: 2}]
RUBY
end
it 'does not register an offense when hash with braces' do
expect_no_offenses(<<~RUBY)
[1, 2, { one: 1, two: 2 }]
RUBY
end
it 'does not register an offense when hash is not inside array' do
expect_no_offenses(<<~RUBY)
foo(one: 1, two: 2)
RUBY
end
it 'does not register an offense when the array is all hashes' do
expect_no_offenses(<<~RUBY)
[{ one: 1 }, { two: 2 }]
RUBY
end
it 'does not register an offense when the hash is empty' do
expect_no_offenses(<<~RUBY)
[1, {}]
RUBY
end
it 'does not register an offense when using double splat operator' do
expect_no_offenses(<<~RUBY)
[1, **options]
RUBY
end
end
context 'when EnforcedStyle is no_braces' do
let(:cop_config) { { 'EnforcedStyle' => 'no_braces' } }
it 'registers an offense and corrects when hash with braces' do
expect_offense(<<~RUBY)
[{ one: 1 }, { three: 3 }, 2, { three: 3 }]
^^^^^^^^^^^^ Omit the braces around the hash.
RUBY
expect_correction(<<~RUBY)
[{ one: 1 }, { three: 3 }, 2, three: 3 ]
RUBY
end
it 'registers an offense and corrects when hash with braces and trailing comma' do
expect_offense(<<~RUBY)
[1, 2, { one: 1, two: 2, },]
^^^^^^^^^^^^^^^^^^^ Omit the braces around the hash.
RUBY
expect_correction(<<~RUBY)
[1, 2, one: 1, two: 2, ]
RUBY
end
it 'registers an offense and corrects when hash with braces and trailing comma and new line' do
expect_offense(<<~RUBY)
[
1,
2,
{
^ Omit the braces around the hash.
one: 1,
two: 2,
},
]
RUBY
expect_correction(<<~RUBY)
[
1,
2,
#{' '}
one: 1,
two: 2,
#{' '}
]
RUBY
end
it 'does not register an offense when hash is not the last element' do
expect_no_offenses(<<~RUBY)
[
1,
2,
{
one: 1
},
two: 2
]
RUBY
end
it 'does not register an offense when hash without braces' do
expect_no_offenses(<<~RUBY)
[1, 2, one: 1, two: 2]
RUBY
end
it 'does not register an offense when hash is not inside array' do
expect_no_offenses(<<~RUBY)
foo({ one: 1, two: 2 })
RUBY
end
it 'does not register an offense when the array is all hashes' do
expect_no_offenses(<<~RUBY)
[{ one: 1 }, { two: 2 }]
RUBY
end
it 'does not register an offense when the hash is empty' do
expect_no_offenses(<<~RUBY)
[1, {}]
RUBY
end
it 'does not register an offense when passing an implicit array to a setter' do
expect_no_offenses(<<~RUBY)
cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/if_unless_modifier_spec.rb | spec/rubocop/cop/style/if_unless_modifier_spec.rb | # frozen_string_literal: true
######
# Note: most of these tests probably belong in the shared context "condition modifier cop"
######
RSpec.describe RuboCop::Cop::Style::IfUnlessModifier, :config do
let(:allow_cop_directives) { true }
let(:allow_uri) { true }
let(:line_length_config) do
{
'Enabled' => true,
'Max' => 80,
'AllowURI' => allow_uri,
'AllowCopDirectives' => allow_cop_directives,
'URISchemes' => %w[http https]
}
end
let(:other_cops) { { 'Layout/LineLength' => line_length_config } }
extra = ' Another good alternative is the usage of control flow `&&`/`||`.'
it_behaves_like 'condition modifier cop', :if, extra
it_behaves_like 'condition modifier cop', :unless, extra
context 'modifier if that does not fit on one line' do
let(:spaces) { ' ' * 59 }
let(:body) { "puts '#{spaces}'" }
let(:source) { "#{body} if condition" }
let(:long_url) { 'https://some.example.com/with/a/rather?long&and=very&complicated=path' }
context 'when Layout/LineLength is enabled' do
it 'corrects it to normal form' do
expect(source.length).to be(79) # That's 81 including indentation.
expect_offense(<<~RUBY, body: body)
def f
# Comment 1
%{body} if condition # Comment 2
_{body} ^^ Modifier form of `if` makes the line too long.
end
RUBY
expect_correction(<<~RUBY)
def f
# Comment 1
if condition
puts '#{spaces}'
end # Comment 2
end
RUBY
end
context 'and the long line is allowed because AllowURI is true' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
puts 1 if url == '#{long_url}'
RUBY
end
end
context 'and the long line is too long because AllowURI is false' do
let(:allow_uri) { false }
it 'registers an offense' do
expect_offense(<<~RUBY)
puts 1 if url == '#{long_url}'
^^ Modifier form of `if` makes the line too long.
RUBY
expect_correction(<<~RUBY)
if url == '#{long_url}'
puts 1
end
RUBY
end
end
context 'when using multiple `if` modifier in the long one line' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def f
return value if items.filter_map { |item| item.do_something if item.something? }
^^ Modifier form of `if` makes the line too long.
^^ Modifier form of `if` makes the line too long.
end
RUBY
expect_correction(<<~RUBY)
def f
if items.filter_map { |item| item.do_something if item.something? }
return value
end
end
RUBY
end
end
context 'when using a method with heredoc argument' do
it 'registers an offense' do
expect_offense(<<~RUBY)
fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(<<~EOS) if condition
^^ Modifier form of `if` makes the line too long.
string
EOS
RUBY
expect_correction(<<~RUBY)
if condition
fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(<<~EOS)
string
EOS
end
RUBY
end
end
context 'when variable assignment is used in the branch body of if modifier' do
it 'registers an offense' do
expect_offense(<<~RUBY)
variable = foooooooooooooooooooooooooooooooooooooooooooooooooooooooo if condition
^^ Modifier form of `if` makes the line too long.
RUBY
expect_correction(<<~RUBY)
if condition
variable = foooooooooooooooooooooooooooooooooooooooooooooooooooooooo
end
RUBY
end
end
context 'when the line is too long due to long comment with modifier' do
it 'registers an offense' do
expect_offense(<<~RUBY)
some_statement if some_quite_long_condition # The condition might have been long, but this comment is longer. In fact, it is too long for RuboCop
^^ Modifier form of `if` makes the line too long.
RUBY
expect_correction(<<~RUBY)
# The condition might have been long, but this comment is longer. In fact, it is too long for RuboCop
some_statement if some_quite_long_condition
RUBY
end
end
describe 'AllowCopDirectives' do
let(:spaces) { ' ' * 57 }
let(:comment) { '# rubocop:disable Style/For' }
let(:body) { "puts '#{spaces}'" }
context 'and the long line is allowed because AllowCopDirectives is true' do
it 'accepts' do
expect("#{body} if condition".length).to eq(77) # That's 79 including indentation.
expect_no_offenses(<<~RUBY)
def f
#{body} if condition #{comment}
end
RUBY
end
end
context 'and the long line is too long because AllowCopDirectives is false' do
let(:allow_cop_directives) { false }
it 'registers an offense' do
expect_offense(<<~RUBY, body: body)
def f
%{body} if condition #{comment}
_{body} ^^ Modifier form of `if` makes the line too long.
end
RUBY
expect_correction(<<~RUBY)
def f
#{comment}
#{body} if condition
end
RUBY
end
end
end
end
context 'when Layout/LineLength is disabled in configuration' do
let(:line_length_config) { { 'Enabled' => false, 'Max' => 80 } }
it 'accepts' do
expect_no_offenses(<<~RUBY)
def f
#{source}
end
RUBY
end
end
context 'when Layout/LineLength is disabled with enable/disable comments' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
def f
# rubocop:disable Layout/LineLength
#{source}
# rubocop:enable Layout/LineLength
end
RUBY
end
end
context 'when Layout/LineLength is disabled with an EOL comment' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
def f
#{source} # rubocop:disable Layout/LineLength
end
RUBY
end
end
end
context 'multiline if that fits on one line' do
let(:condition) { 'a' * 38 }
let(:body) { 'b' * 38 }
it 'registers an offense' do
# This if statement fits exactly on one line if written as a
# modifier.
expect("#{body} if #{condition}".length).to eq(80)
# Empty lines should make no difference.
expect_offense(<<~RUBY)
if #{condition}
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
#{body}
end
RUBY
expect_correction(<<~RUBY)
#{body} if #{condition}
RUBY
end
context 'and has two statements separated by semicolon' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
if condition
do_this; do_that
end
RUBY
end
end
context 'and has a method call with kwargs splat' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if condition
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
do_this(**options)
end
RUBY
expect_correction(<<~RUBY)
do_this(**options) if condition
RUBY
end
end
end
context 'modifier if that does not fit on one line, but is not the only statement on the line' do
let(:spaces) { ' ' * 59 }
# long lines which have multiple statements on the same line can be flagged
# by Layout/LineLength, Style/Semicolon, etc.
# if they are handled by Style/IfUnlessModifier, there is a danger of
# creating infinite autocorrect loops when autocorrecting
it 'accepts' do
expect_no_offenses(<<~RUBY)
def f
puts '#{spaces}' if condition; some_method_call
end
RUBY
end
end
context 'multiline if that fits on one line with comment on first line' do
it 'registers an offense and preserves comment' do
expect_offense(<<~RUBY)
if a # comment
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
b
end
RUBY
expect_correction(<<~RUBY)
b if a # comment
RUBY
end
end
context 'multiline if that fits on one line with comment near end' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
if a
b
end # comment
if a
b
# comment
end
RUBY
end
end
context 'short multiline if near an else etc' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if x
y
elsif x1
y1
else
z
end
n = a ? 0 : 1
m = 3 if m0
if a
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
b
end
RUBY
expect_correction(<<~RUBY)
if x
y
elsif x1
y1
else
z
end
n = a ? 0 : 1
m = 3 if m0
b if a
RUBY
end
end
context 'multiline unless that fits on one line' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless a
^^^^^^ Favor modifier `unless` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
b
end
RUBY
expect_correction(<<~RUBY)
b unless a
RUBY
end
end
it 'accepts code with EOL comment since user might want to keep it' do
expect_no_offenses(<<~RUBY)
unless a
b # A comment
end
RUBY
end
it 'accepts if-else-end' do
expect_no_offenses(<<~RUBY)
if args.last.is_a? Hash then args.pop else Hash.new end
RUBY
end
it 'accepts if/elsif' do
expect_no_offenses(<<~RUBY)
if test
something
elsif test2
something_else
end
RUBY
end
shared_examples 'one-line pattern matching' do
it 'does not register an offense when using match var in body' do
expect_no_offenses(<<~RUBY)
if [42] in [x]
x
end
RUBY
end
it 'does not register an offense when using some match var in body' do
expect_no_offenses(<<~RUBY)
if { x: 1, y: 2 } in { x:, y: }
a && y
end
RUBY
end
it 'does not register an offense when not using match var in body' do
expect_no_offenses(<<~RUBY)
if [42] in [x]
y
end
RUBY
end
it 'does not register an offense when not using any match var in body' do
expect_no_offenses(<<~RUBY)
if { x: 1, y: 2 } in { x:, y: }
a && b
end
RUBY
end
end
# The node type for one-line `in` pattern matching in Ruby 2.7 is `match_pattern`.
context 'using `match_pattern` as a one-line pattern matching', :ruby27 do
it_behaves_like 'one-line pattern matching'
end
# The node type for one-line `in` pattern matching in Ruby 3.0 is `match_pattern_p`.
context 'using `match_pattern_p` as a one-line pattern matching', :ruby30 do
it_behaves_like 'one-line pattern matching'
end
context 'when using endless method definition', :ruby30 do
it 'does not register an offense when using method definition in the branch' do
expect_no_offenses(<<~RUBY)
if condition
def method_name = body
end
RUBY
end
it 'does not register an offense when using singleton method definition in the branch' do
expect_no_offenses(<<~RUBY)
if condition
def self.method_name = body
end
RUBY
end
end
context 'when using omitted hash values in an assignment', :ruby31 do
it 'registers an offense' do
expect_offense(<<~RUBY)
if condition
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
obj[:key] = { foo: }
end
RUBY
expect_correction(<<~RUBY)
obj[:key] = { foo: } if condition
RUBY
end
end
context 'multiline `if` that fits on one line and using hash value omission syntax', :ruby31 do
it 'registers an offense' do
expect_offense(<<~RUBY)
if condition
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
obj.do_something foo:
end
if condition
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
obj&.do_something foo:
end
RUBY
expect_correction(<<~RUBY)
obj.do_something(foo:) if condition
obj&.do_something(foo:) if condition
RUBY
end
end
context 'multiline `if` that fits on one line and using dot method call with hash value omission syntax', :ruby31 do
it 'corrects it to normal form1' do
expect_offense(<<~RUBY)
if condition
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
obj.(attr:)
end
RUBY
expect_correction(<<~RUBY)
obj.(attr:) if condition
RUBY
end
end
context 'multiline `if` that fits on one line and using safe navigation dot method call with hash value omission syntax', :ruby31 do
it 'corrects it to normal form1' do
expect_offense(<<~RUBY)
if condition
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
obj&.(attr:)
end
RUBY
expect_correction(<<~RUBY)
obj&.(attr:) if condition
RUBY
end
end
context 'using `defined?` in the condition' do
it 'registers for argument value is defined' do
expect_offense(<<~RUBY)
value = :custom
unless defined?(value)
^^^^^^ Favor modifier `unless` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
value = :default
end
RUBY
expect_correction(<<~RUBY)
value = :custom
value = :default unless defined?(value)
RUBY
end
it 'registers for argument value is `yield`' do
expect_offense(<<~RUBY)
unless defined?(yield)
^^^^^^ Favor modifier `unless` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
value = :default
end
RUBY
expect_correction(<<~RUBY)
value = :default unless defined?(yield)
RUBY
end
it 'registers for argument value is `super`' do
expect_offense(<<~RUBY)
unless defined?(super)
^^^^^^ Favor modifier `unless` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
value = :default
end
RUBY
expect_correction(<<~RUBY)
value = :default unless defined?(super)
RUBY
end
it 'accepts `defined?` when argument value is undefined' do
expect_no_offenses(<<~RUBY)
other_value = do_something
unless defined?(value)
value = :default
end
RUBY
end
it 'accepts `defined?` when argument value is undefined and the first condition' do
expect_no_offenses(<<~RUBY)
other_value = do_something
unless defined?(value) && condition
value = :default
end
RUBY
end
it 'accepts `defined?` when argument value is undefined and the last condition' do
expect_no_offenses(<<~RUBY)
other_value = do_something
unless condition && defined?(value)
value = :default
end
RUBY
end
end
context 'with implicit match conditional' do
let(:body) { 'b' * 36 }
context 'when a multiline if fits on one line' do
let(:conditional) { "/#{'a' * 36}/" }
it 'registers an offense' do
expect(" #{body} if #{conditional}".length).to eq(80)
expect_offense(<<-RUBY.strip_margin('|'))
| if #{conditional}
| ^^ Favor modifier `if` usage when having a single-line body. [...]
| #{body}
| end
RUBY
expect_correction(" #{body} if #{conditional}\n")
end
end
context "when a multiline if doesn't fit on one line" do
let(:conditional) { "/#{'a' * 37}/" }
it 'accepts' do
expect(" #{body} if #{conditional}".length).to eq(81)
expect_no_offenses(<<-RUBY.strip_margin('|'))
| if #{conditional}
| #{body}
| end
RUBY
end
end
end
it 'accepts if-end followed by a chained call using `.`' do
expect_no_offenses(<<~RUBY)
if test
something
end.inspect
RUBY
end
it 'accepts if-end followed by a chained call using `&.`' do
expect_no_offenses(<<~RUBY)
if test
something
end&.inspect
RUBY
end
it 'adds parens in autocorrect when if-end used with `||` operator' do
expect_offense(<<~RUBY)
a || if b
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
1
end
RUBY
expect_correction(<<~RUBY)
a || (1 if b)
RUBY
end
it 'adds parens in autocorrect when if-end used with `&&` operator' do
expect_offense(<<~RUBY)
a && if b
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
1
end
RUBY
expect_correction(<<~RUBY)
a && (1 if b)
RUBY
end
it 'accepts if-end when used as LHS of binary arithmetic' do
expect_no_offenses(<<~RUBY)
if test
1
end + 2
RUBY
end
context 'if-end is argument to a parenthesized method call' do
it 'adds parentheses because otherwise it would cause SyntaxError' do
expect_offense(<<~RUBY)
puts("string", if a
^^ Favor modifier `if` usage when having a single-line body. [...]
1
end)
RUBY
expect_correction(<<~RUBY)
puts("string", (1 if a))
RUBY
end
end
context 'if-end is argument to a non-parenthesized method call' do
it 'adds parentheses so as not to change meaning' do
expect_offense(<<~RUBY)
puts "string", if a
^^ Favor modifier `if` usage when having a single-line body. [...]
1
end
RUBY
expect_correction(<<~RUBY)
puts "string", (1 if a)
RUBY
end
end
context 'if-end with conditional as body' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
if condition
foo ? "bar" : "baz"
end
RUBY
end
end
context 'unless-end with conditional as body' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
unless condition
foo ? "bar" : "baz"
end
RUBY
end
end
context 'with a named regexp capture on the LHS' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
if /(?<foo>\d)/ =~ "bar"
foo
end
RUBY
end
end
context 'with tabs used for indentation' do
shared_examples 'with tabs indentation' do
let(:indent) { "\t" * 6 }
let(:body) { 'bbb' }
context 'it fits on one line' do
let(:condition) { 'aaa' }
it 'registers an offense' do
# This if statement fits exactly on one line if written as a
# modifier.
expect("#{body} if #{condition}".length).to eq(10)
expect_offense(<<~RUBY, indent: indent)
%{indent}if #{condition}
_{indent}^^ Favor modifier `if` usage when having a single-line body. [...]
%{indent}\t#{body}
%{indent}end
RUBY
expect_correction(<<~RUBY)
#{indent}#{body} if #{condition}
RUBY
end
end
context "it doesn't fit on one line" do
let(:condition) { 'aaaa' }
it "doesn't register an offense" do
# This if statement fits exactly on one line if written as a
# modifier.
expect("#{body} if #{condition}".length).to eq(11)
expect_no_offenses(<<~RUBY)
#{indent}if #{condition}
#{indent}\t#{body}
#{indent}end
RUBY
end
end
end
context 'with Layout/IndentationStyle: IndentationWidth config' do
let(:other_cops) do
{
'Layout/IndentationStyle' => { 'IndentationWidth' => 2 },
'Layout/LineLength' => { 'Max' => 10 + 12 } # 12 is indentation
}
end
it_behaves_like 'with tabs indentation'
end
context 'with Layout/IndentationWidth: Width config' do
let(:other_cops) do
{
'Layout/IndentationWidth' => { 'Width' => 3 },
'Layout/LineLength' => { 'Max' => 10 + 18 } # 18 is indentation
}
end
it_behaves_like 'with tabs indentation'
end
end
context 'when Layout/LineLength is disabled' do
let(:line_length_config) { { 'Enabled' => false } }
it 'registers an offense even for a long modifier statement' do
expect_offense(<<~RUBY)
if foo
^^ Favor modifier `if` usage when having a single-line body. Another good alternative is the usage of control flow `&&`/`||`.
"This string would make the line longer than eighty characters if combined with the statement."
end
RUBY
expect_correction(<<~RUBY)
"This string would make the line longer than eighty characters if combined with the statement." if foo
RUBY
end
end
context 'when if-end condition is assigned to a variable' do
context 'with variable being on the same line' do
let(:body) { 'b' * body_length }
context 'when it is short enough to fit on a single line' do
let(:body_length) { 69 }
it 'corrects it to the single-line form' do
expect_offense(<<~RUBY, body: body)
x = if a
^^ Favor modifier `if` usage [...]
%{body}
end
RUBY
expect_correction(<<~RUBY)
x = (#{body} if a)
RUBY
end
end
context 'when it is not short enough to fit on a single line' do
let(:body_length) { 70 }
it 'accepts it in the multiline form' do
expect_no_offenses(<<~RUBY)
x = if a
#{body}
end
RUBY
end
end
end
context 'with variable being on the previous line' do
let(:body) { 'b' * body_length }
context 'when it is short enough to fit on a single line' do
let(:body_length) { 71 }
it 'corrects it to the single-line form' do
expect_offense(<<~RUBY, body: body)
x =
if a
^^ Favor modifier `if` usage [...]
%{body}
end
RUBY
expect_correction(<<~RUBY)
x =
(#{body} if a)
RUBY
end
end
context 'when it is not short enough to fit on a single line' do
let(:body_length) { 72 }
it 'accepts it in the multiline form' do
expect_no_offenses(<<~RUBY)
x =
if a
#{body}
end
RUBY
end
end
end
end
context 'when if-end condition is an element of an array' do
let(:body) { 'b' * body_length }
context 'when short enough to fit on a single line' do
let(:body_length) { 71 }
it 'corrects it to the single-line form' do
expect_offense(<<~RUBY, body: body)
[
if a
^^ Favor modifier `if` usage [...]
%{body}
end
]
RUBY
expect_correction(<<~RUBY)
[
(#{body} if a)
]
RUBY
end
end
context 'when not short enough to fit on a single line' do
let(:body_length) { 72 }
it 'accepts it in the multiline form' do
expect_no_offenses(<<~RUBY)
[
if a
#{body}
end
]
RUBY
end
end
end
context 'when if-end condition is a value in a hash' do
let(:body) { 'b' * body_length }
context 'when it is short enough to fit on a single line' do
let(:body_length) { 68 }
it 'corrects it to the single-line form' do
expect_offense(<<~RUBY, body: body)
{
x: if a
^^ Favor modifier `if` usage [...]
%{body}
end
}
RUBY
expect_correction(<<~RUBY)
{
x: (#{body} if a)
}
RUBY
end
end
context 'when it is not short enough to fit on a single line' do
let(:body_length) { 69 }
it 'accepts it in the multiline form' do
expect_no_offenses(<<~RUBY)
{
x: if a
#{body}
end
}
RUBY
end
end
end
context 'when if-end condition has a first line comment' do
let(:comment) { 'c' * comment_length }
context 'when it is short enough to fit on a single line' do
let(:comment_length) { 67 }
it 'corrects it to the single-line form' do
expect_offense(<<~RUBY, comment: comment)
if foo # %{comment}
^^ Favor modifier `if` usage [...]
bar
end
RUBY
expect_correction(<<~RUBY)
bar if foo # #{comment}
RUBY
end
end
context 'when it is not short enough to fit on a single line' do
let(:comment_length) { 68 }
it 'accepts it in the multiline form' do
expect_no_offenses(<<~RUBY)
if foo # #{comment}
bar
end
RUBY
end
end
end
context 'when if-end condition has some code after the end keyword' do
let(:body) { 'b' * body_length }
context 'when it is short enough to fit on a single line' do
let(:body_length) { 53 }
it 'corrects it to the single-line form' do
expect_offense(<<~RUBY, body: body)
[
1, if foo
^^ Favor modifier `if` usage [...]
%{body}
end, 300_000_000
]
RUBY
expect_correction(<<~RUBY)
[
1, (#{body} if foo), 300_000_000
]
RUBY
end
end
context 'when it is not short enough to fit on a single line' do
let(:body_length) { 54 }
it 'accepts it in the multiline form' do
expect_no_offenses(<<~RUBY)
[
1, if foo
#{body}
end, 300_000_000
]
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_initialize_spec.rb | spec/rubocop/cop/style/redundant_initialize_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantInitialize, :config do
let(:cop_config) { { 'AllowComments' => true } }
it 'does not register an offense for an empty method not named `initialize`' do
expect_no_offenses(<<~RUBY)
def do_something
end
RUBY
end
it 'does not register an offense for a method not named `initialize` that only calls super' do
expect_no_offenses(<<~RUBY)
def do_something
super
end
RUBY
end
it 'registers and corrects an offense for an empty `initialize` method' do
expect_offense(<<~RUBY)
def initialize
^^^^^^^^^^^^^^ Remove unnecessary empty `initialize` method.
end
RUBY
expect_correction('')
end
it 'does not register an offense for an `initialize` method with only a comment' do
expect_no_offenses(<<~RUBY)
def initialize
# initializer
end
RUBY
end
it 'registers and corrects an offense for an `initialize` method that only calls `super`' do
expect_offense(<<~RUBY)
def initialize
^^^^^^^^^^^^^^ Remove unnecessary `initialize` method.
super
end
RUBY
expect_correction('')
end
it 'registers and corrects an offense for an `initialize` method with arguments that only calls `super`' do
expect_offense(<<~RUBY)
def initialize(a, b)
^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `initialize` method.
super
end
RUBY
expect_correction('')
end
it 'registers and corrects an offense for an `initialize` method with arguments that only calls `super` with explicit args' do
expect_offense(<<~RUBY)
def initialize(a, b)
^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `initialize` method.
super(a, b)
end
RUBY
expect_correction('')
end
it 'does not register an offense for an `initialize` method that calls another method' do
expect_no_offenses(<<~RUBY)
def initialize(a, b)
do_something
end
RUBY
end
it 'does not register an offense for an `initialize` method that calls another method before `super`' do
expect_no_offenses(<<~RUBY)
def initialize(a, b)
do_something
super
end
RUBY
end
it 'does not register an offense for an `initialize` method that calls another method after `super`' do
expect_no_offenses(<<~RUBY)
def initialize(a, b)
super
do_something
end
RUBY
end
it 'does not register an offense for an `initialize` method that calls `super` with a different argument list' do
expect_no_offenses(<<~RUBY)
def initialize(a, b)
super(a)
end
RUBY
end
it 'does not register an offense for an `initialize` method that calls `super` with no arguments' do
expect_no_offenses(<<~RUBY)
def initialize(a, b)
super()
end
RUBY
end
it 'registers and corrects an offense for an `initialize` method with no arguments that calls `super` with no arguments' do
expect_offense(<<~RUBY)
def initialize()
^^^^^^^^^^^^^^^^ Remove unnecessary `initialize` method.
super()
end
RUBY
expect_correction('')
end
it 'does not register an offense for an `initialize` method with a default argument that calls `super`' do
expect_no_offenses(<<~RUBY)
def initialize(a, b = 5)
super
end
RUBY
end
it 'does not register an offense for an `initialize` method with a default keyword argument that calls `super`' do
expect_no_offenses(<<~RUBY)
def initialize(a, b: 5)
super
end
RUBY
end
it 'does not register an offense for an `initialize` method with a default argument that does nothing' do
expect_no_offenses(<<~RUBY)
def initialize(a, b = 5)
end
RUBY
end
it 'does not register an offense for an `initialize` method with a default keyword argument that does nothing' do
expect_no_offenses(<<~RUBY)
def initialize(a, b: 5)
end
RUBY
end
it 'does not register an offense for an empty `initialize` method with an argument`' do
expect_no_offenses(<<~RUBY)
def initialize(_)
end
RUBY
end
it 'does not register an offense for an empty `initialize` method with a splat`' do
expect_no_offenses(<<~RUBY)
def initialize(*)
end
RUBY
end
it 'does not register an offense for an empty `initialize` method with a splat` and super' do
expect_no_offenses(<<~RUBY)
def initialize(*args)
super(args.first)
end
RUBY
end
it 'does not register an offense for an empty `initialize` method with a kwsplat`' do
expect_no_offenses(<<~RUBY)
def initialize(**)
end
RUBY
end
it 'does not register an offense for an empty `initialize` method with an argument forwarding`', :ruby27 do
expect_no_offenses(<<~RUBY)
def initialize(...)
end
RUBY
end
context 'when `AllowComments: false`' do
let(:cop_config) { { 'AllowComments' => false } }
it 'registers and corrects an offense for an `initialize` method with only a comment' do
expect_offense(<<~RUBY)
def initialize
^^^^^^^^^^^^^^ Remove unnecessary empty `initialize` method.
# initializer
end
RUBY
expect_correction('')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/string_concatenation_spec.rb | spec/rubocop/cop/style/string_concatenation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StringConcatenation, :config do
it 'registers an offense and corrects for string concatenation' do
expect_offense(<<~RUBY)
email_with_name = user.name + ' <' + user.email + '>'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
email_with_name = "\#{user.name} <\#{user.email}>"
RUBY
end
it 'registers an offense and corrects for string concatenation as part of other expression' do
expect_offense(<<~RUBY)
users = (user.name + ' ' + user.email) * 5
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
users = ("\#{user.name} \#{user.email}") * 5
RUBY
end
it 'correctly handles strings with special characters' do
expect_offense(<<~RUBY)
email_with_name = "\\n" + user.name + ' ' + user.email + '\\n'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
email_with_name = "\\n\#{user.name} \#{user.email}\\\\n"
RUBY
end
it 'correctly handles nested concatenatable parts' do
expect_offense(<<~RUBY)
(user.vip? ? greeting + ', ' : '') + user.name + ' <' + user.email + '>'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
"\#{user.vip? ? "\#{greeting}, " : ''}\#{user.name} <\#{user.email}>"
RUBY
end
it 'correctly handles nested concatenatable parts and escaped double-quotes' do
expect_offense(<<~'RUBY')
"foo" + "\"#{bar}\"" + 'baz'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"foo\"#{bar}\"baz"
RUBY
end
it 'correctly handles nested concatenatable parts and escaped single-quotes' do
expect_offense(<<~'RUBY')
"foo" + "\'#{bar}\'" + 'baz'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"foo'#{bar}'baz"
RUBY
end
it 'does not register an offense when using `+` with all non string arguments' do
expect_no_offenses(<<~RUBY)
user.name + user.email
RUBY
end
context 'implicit concatenation' do
it 'registers an offense and corrects with implicit concatenation at the end' do
expect_offense(<<~RUBY)
"a" + "b" "c"
^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
"abc"
RUBY
end
it 'registers an offense and corrects with implicit concatenation at the start' do
expect_offense(<<~RUBY)
"a" "b" + "c"
^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
"abc"
RUBY
end
it 'registers an offense and corrects with implicit concatenation at the middle' do
expect_offense(<<~RUBY)
"a" + "b" "c" + "d"
^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
"abcd"
RUBY
end
it 'registers an offense and corrects with string interpolation' do
expect_offense(<<~'RUBY')
"string #{interpolation}" 'foo' + 'bar'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"string #{interpolation}foobar"
RUBY
end
end
context 'multiline' do
context 'string continuation' do
it 'does not register an offense' do
# handled by `Style/LineEndConcatenation` instead.
expect_no_offenses(<<~RUBY)
"this is a long string " +
"this is a continuation"
RUBY
end
end
context 'simple expressions' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
email_with_name = user.name +
^^^^^^^^^^^ Prefer string interpolation to string concatenation.
' ' +
user.email +
'\\n'
RUBY
expect_correction(<<~RUBY)
email_with_name = "\#{user.name} \#{user.email}\\\\n"
RUBY
end
end
context 'if condition' do
it 'registers an offense but does not correct' do
expect_offense(<<~RUBY)
"result:" + if condition
^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
"true"
else
"false"
end
RUBY
expect_no_corrections
end
end
context 'multiline block' do
it 'registers an offense but does not correct' do
expect_offense(<<~RUBY)
'(' + values.map do |v|
^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
v.titleize
end.join(', ') + ')'
RUBY
expect_no_corrections
end
end
end
context 'nested interpolation' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
"foo" + "bar: #{baz}"
^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"foobar: #{baz}"
RUBY
end
end
context 'inline block' do
it 'registers an offense but does not correct' do
expect_offense(<<~RUBY)
'(' + values.map { |v| v.titleize }.join(', ') + ')'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_no_corrections
end
it 'registers an offense but does not correct for numblocks' do
expect_offense(<<~RUBY)
'(' + values.map { _1.titleize }.join(', ') + ')'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_no_corrections
end
end
context 'heredoc' do
it 'registers an offense but does not correct' do
expect_offense(<<~RUBY)
"foo" + <<~STR
^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
text
STR
RUBY
expect_no_corrections
end
it 'registers an offense but does not correct when string concatenation with multiline heredoc text' do
expect_offense(<<~RUBY)
"foo" + <<~TEXT
^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
bar
baz
TEXT
RUBY
expect_no_corrections
end
end
context 'double quotes inside string' do
it 'registers an offense and corrects with double quotes' do
expect_offense(<<~'RUBY')
email_with_name = "He said " + "\"Arrest that man!\"."
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
email_with_name = "He said \"Arrest that man!\"."
RUBY
end
it 'registers an offense and corrects with percentage quotes' do
expect_offense(<<~RUBY)
email_with_name = %(He said ) + %("Arrest that man!".)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
email_with_name = "He said \"Arrest that man!\"."
RUBY
end
end
context 'empty quotes' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
'"' + "foo" + '"'
^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
'"' + "foo" + "'"
^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
"'" + "foo" + '"'
^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
"'" + "foo" + '"' + "bar"
^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"\"foo\""
"\"foo'"
"'foo\""
"'foo\"bar"
RUBY
end
end
context 'double quotes inside string surrounded single quotes' do
it 'registers an offense and corrects with double quotes' do
expect_offense(<<~RUBY)
'"bar"' + foo
^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"\"bar\"#{foo}"
RUBY
end
end
context 'characters for interpolation inside single quotes' do
it 'registers an offense for `#{}`' do
expect_offense(<<~'RUBY')
"foo" + '#{bar}'
^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"foo\#{bar}"
RUBY
end
it 'registers an offense for `#@`' do
expect_offense(<<~'RUBY')
"foo" + '#@bar'
^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"foo\#@bar"
RUBY
end
it 'registers an offense for `#@@`' do
expect_offense(<<~'RUBY')
"foo" + '#@@bar'
^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"foo\#@@bar"
RUBY
end
it 'registers an offense for `#$`' do
expect_offense(<<~'RUBY')
"foo" + '#$bar'
^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~'RUBY')
"foo\#$bar"
RUBY
end
end
context 'Mode = conservative' do
let(:cop_config) { { 'Mode' => 'conservative' } }
context 'when first operand is not string literal' do
it 'does not register offense' do
expect_no_offenses(<<~RUBY)
user.name + "!!"
user.name + "<"
user.name + "<" + "user.email" + ">"
RUBY
end
end
context 'when first operand is string literal' do
it 'registers an offense' do
expect_offense(<<~RUBY)
"Hello " + user.name
^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
"Hello " + user.name + "!!"
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer string interpolation to string concatenation.
RUBY
expect_correction(<<~RUBY)
"Hello \#{user.name}"
"Hello \#{user.name}!!"
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/non_nil_check_spec.rb | spec/rubocop/cop/style/non_nil_check_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NonNilCheck, :config do
context 'when not allowing semantic changes' do
let(:cop_config) { { 'IncludeSemanticChanges' => false } }
it 'registers an offense for != nil' do
expect_offense(<<~RUBY)
x != nil
^^^^^^^^ Prefer `!x.nil?` over `x != nil`.
RUBY
expect_correction(<<~RUBY)
!x.nil?
RUBY
end
it 'does not register an offense for != 0' do
expect_no_offenses('x != 0')
end
it 'does not register an offense for !x.nil?' do
expect_no_offenses('!x.nil?')
end
it 'does not register an offense for not x.nil?' do
expect_no_offenses('not x.nil?')
end
it 'does not register an offense if only expression in predicate' do
expect_no_offenses(<<~RUBY)
def signed_in?
!current_user.nil?
end
RUBY
end
it 'does not register an offense if only expression in class predicate' do
expect_no_offenses(<<~RUBY)
def Test.signed_in?
current_user != nil
end
RUBY
end
it 'does not register an offense if last expression in predicate' do
expect_no_offenses(<<~RUBY)
def signed_in?
something
current_user != nil
end
RUBY
end
it 'does not register an offense if last expression in class predicate' do
expect_no_offenses(<<~RUBY)
def Test.signed_in?
something
current_user != nil
end
RUBY
end
it 'does not register an offense with implicit receiver' do
expect_no_offenses('!nil?')
end
it 'registers an offense but does not correct when the code was not modified' do
expect_offense(<<~RUBY)
return nil unless (line =~ //) != nil
^^^^^^^^^^^^^^^^^^^ Prefer `!(line =~ //).nil?` over `(line =~ //) != nil`.
RUBY
expect_no_corrections
end
end
context 'when allowing semantic changes' do
let(:cop_config) { { 'IncludeSemanticChanges' => true } }
it 'registers an offense for `!x.nil?`' do
expect_offense(<<~RUBY)
!x.nil?
^^^^^^^ Explicit non-nil checks are usually redundant.
RUBY
expect_correction(<<~RUBY)
x
RUBY
end
it 'registers an offense for unless x.nil?' do
expect_offense(<<~RUBY)
puts b unless x.nil?
^^^^^^ Explicit non-nil checks are usually redundant.
RUBY
expect_correction(<<~RUBY)
puts b if x
RUBY
end
it 'does not register an offense for `x.nil?`' do
expect_no_offenses('x.nil?')
end
it 'does not register an offense for `!x`' do
expect_no_offenses('!x')
end
it 'registers an offense for `not x.nil?`' do
expect_offense(<<~RUBY)
not x.nil?
^^^^^^^^^^ Explicit non-nil checks are usually redundant.
RUBY
expect_correction(<<~RUBY)
x
RUBY
end
it 'does not blow up with ternary operators' do
expect_no_offenses('my_var.nil? ? 1 : 0')
end
it 'autocorrects by changing `x != nil` to `x`' do
expect_offense(<<~RUBY)
x != nil
^^^^^^^^ Explicit non-nil checks are usually redundant.
RUBY
expect_correction(<<~RUBY)
x
RUBY
end
it 'does not blow up when autocorrecting implicit receiver' do
expect_offense(<<~RUBY)
!nil?
^^^^^ Explicit non-nil checks are usually redundant.
RUBY
expect_correction(<<~RUBY)
self
RUBY
end
it 'corrects code that would not be modified if IncludeSemanticChanges were false' do
expect_offense(<<~RUBY)
return nil unless (line =~ //) != nil
^^^^^^^^^^^^^^^^^^^ Explicit non-nil checks are usually redundant.
RUBY
expect_correction(<<~RUBY)
return nil unless (line =~ //)
RUBY
end
end
context 'when `EnforcedStyle: comparison` of `Style/NilComparison` cop' do
let(:other_cops) { { 'Style/NilComparison' => { 'EnforcedStyle' => 'comparison' } } }
context '`IncludeSemanticChanges: false`' do
let(:cop_config) { { 'IncludeSemanticChanges' => false } }
it 'does not register an offense for `foo != nil`' do
expect_no_offenses('foo != nil')
end
end
context '`IncludeSemanticChanges: true`' do
let(:cop_config) { { 'IncludeSemanticChanges' => true } }
it 'registers an offense for `foo != nil`' do
expect_offense(<<~RUBY)
foo != nil
^^^^^^^^^^ Explicit non-nil checks are usually redundant.
RUBY
expect_correction(<<~RUBY)
foo
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/while_until_do_spec.rb | spec/rubocop/cop/style/while_until_do_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::WhileUntilDo, :config do
it 'registers an offense for do in multiline while' do
expect_offense(<<~RUBY)
while cond do
^^ Do not use `do` with multi-line `while`.
end
RUBY
expect_correction(<<~RUBY)
while cond
end
RUBY
end
it 'registers an offense for do in multiline until' do
expect_offense(<<~RUBY)
until cond do
^^ Do not use `do` with multi-line `until`.
end
RUBY
expect_correction(<<~RUBY)
until cond
end
RUBY
end
it 'accepts do in single-line while' do
expect_no_offenses('while cond do something end')
end
it 'accepts do in single-line until' do
expect_no_offenses('until cond do something end')
end
it 'accepts multi-line while without do' do
expect_no_offenses(<<~RUBY)
while cond
end
RUBY
end
it 'accepts multi-line until without do' do
expect_no_offenses(<<~RUBY)
until cond
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/keyword_arguments_merging_spec.rb | spec/rubocop/cop/style/keyword_arguments_merging_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::KeywordArgumentsMerging, :config do
it 'registers an offense and corrects when using `merge` with keyword arguments' do
expect_offense(<<~RUBY)
foo(x, **options.merge(y: 1))
^^^^^^^^^^^^^^^^^^^ Provide additional arguments directly rather than using `merge`.
RUBY
expect_correction(<<~RUBY)
foo(x, **options, y: 1)
RUBY
end
it 'registers an offense and corrects when using `merge` with non-keyword arguments' do
expect_offense(<<~RUBY)
foo(x, **options.merge(other_options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide additional arguments directly rather than using `merge`.
RUBY
expect_correction(<<~RUBY)
foo(x, **options, **other_options)
RUBY
end
it 'registers an offense and corrects when using `merge` with keyword and non-keyword arguments' do
expect_offense(<<~RUBY)
foo(x, **options.merge(y: 1, **other_options, z: 2))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide additional arguments directly rather than using `merge`.
RUBY
expect_correction(<<~RUBY)
foo(x, **options, y: 1, **other_options, z: 2)
RUBY
end
it 'registers an offense and corrects when using `merge` with hash with braces' do
expect_offense(<<~RUBY)
foo(x, **options.merge({ y: 1 }))
^^^^^^^^^^^^^^^^^^^^^^^ Provide additional arguments directly rather than using `merge`.
RUBY
expect_correction(<<~RUBY)
foo(x, **options, y: 1 )
RUBY
end
it 'registers an offense and corrects when using `merge` with complex argument' do
expect_offense(<<~RUBY)
foo(x, **options.merge(other_options, y: 1, **yet_another_options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide additional arguments directly rather than using `merge`.
RUBY
expect_correction(<<~RUBY)
foo(x, **options, **other_options, y: 1, **yet_another_options)
RUBY
end
it 'registers an offense and corrects when using `merge` with multiple hash arguments' do
expect_offense(<<~RUBY)
foo(x, **options.merge(other_options, yet_another_options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide additional arguments directly rather than using `merge`.
RUBY
expect_correction(<<~RUBY)
foo(x, **options, **other_options, **yet_another_options)
RUBY
end
it 'registers an offense and corrects when using a chain of `merge`s' do
expect_offense(<<~RUBY)
foo(x, **options.merge(other_options).merge(more_options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide additional arguments directly rather than using `merge`.
RUBY
expect_correction(<<~RUBY)
foo(x, **options, **other_options, **more_options)
RUBY
end
it 'does not register an offense when not using `merge`' do
expect_no_offenses(<<~RUBY)
foo(x, **options)
RUBY
end
it 'does not register an offense when using `merge!`' do
expect_no_offenses(<<~RUBY)
foo(x, **options.merge!(other_options))
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/proc_spec.rb | spec/rubocop/cop/style/proc_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Proc, :config do
it 'registers an offense for a Proc.new call' do
expect_offense(<<~RUBY)
f = Proc.new { |x| puts x }
^^^^^^^^ Use `proc` instead of `Proc.new`.
RUBY
expect_correction(<<~RUBY)
f = proc { |x| puts x }
RUBY
end
it 'registers an offense for ::Proc.new' do
expect_offense(<<~RUBY)
f = ::Proc.new { |x| puts x }
^^^^^^^^^^ Use `proc` instead of `Proc.new`.
RUBY
expect_correction(<<~RUBY)
f = proc { |x| puts x }
RUBY
end
it 'accepts the Proc.new call without block' do
expect_no_offenses('p = Proc.new')
end
it 'accepts the ::Proc.new call without block' do
expect_no_offenses('p = ::Proc.new')
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for a Proc.new call' do
expect_offense(<<~RUBY)
f = Proc.new { puts _1 }
^^^^^^^^ Use `proc` instead of `Proc.new`.
RUBY
expect_correction(<<~RUBY)
f = proc { puts _1 }
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for a Proc.new call' do
expect_offense(<<~RUBY)
f = Proc.new { puts it }
^^^^^^^^ Use `proc` instead of `Proc.new`.
RUBY
expect_correction(<<~RUBY)
f = proc { puts it }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/missing_else_spec.rb | spec/rubocop/cop/style/missing_else_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MissingElse, :config do
shared_examples 'pattern matching' do
context '>= Ruby 2.7', :ruby27 do
it 'does not register an offense' do
# Pattern matching is allowed to have no `else` branch because unlike `if` and `case`,
# it raises `NoMatchingPatternError` if the pattern doesn't match and without having `else`.
expect_no_offenses('case pattern; in a; foo; end')
end
end
end
context 'UnlessElse enabled' do
let(:config) do
RuboCop::Config.new('Style/MissingElse' => {
'Enabled' => true,
'EnforcedStyle' => 'both',
'SupportedStyles' => %w[if case both]
},
'Style/UnlessElse' => { 'Enabled' => true })
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo elsif b; bar else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if cond; foo end
^^^^^^^^^^^^^^^^ `if` condition requires an `else`-clause.
RUBY
expect_no_corrections
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo end')
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
case v; when a; foo; when b; bar; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `case` condition requires an `else`-clause.
RUBY
expect_no_corrections
end
end
end
it_behaves_like 'pattern matching'
end
context 'UnlessElse disabled' do
let(:config) do
RuboCop::Config.new('Style/MissingElse' => {
'Enabled' => true,
'EnforcedStyle' => 'both',
'SupportedStyles' => %w[if case both]
},
'Style/UnlessElse' => { 'Enabled' => false })
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo elsif b; bar else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if cond; foo end
^^^^^^^^^^^^^^^^ `if` condition requires an `else`-clause.
RUBY
expect_no_corrections
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless cond; foo end
^^^^^^^^^^^^^^^^^^^^ `if` condition requires an `else`-clause.
RUBY
expect_no_corrections
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
case v; when a; foo; when b; bar; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `case` condition requires an `else`-clause.
RUBY
expect_no_corrections
end
end
end
it_behaves_like 'pattern matching'
end
context 'EmptyElse enabled and set to warn on empty' do
let(:config) do
styles = %w[if case both]
RuboCop::Config.new('Style/MissingElse' => {
'Enabled' => true,
'EnforcedStyle' => 'both',
'SupportedStyles' => styles
},
'Style/UnlessElse' => { 'Enabled' => false },
'Style/EmptyElse' => {
'Enabled' => true,
'EnforcedStyle' => 'empty',
'SupportedStyles' => %w[empty nil both]
})
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo elsif b; bar else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if cond; foo end
^^^^^^^^^^^^^^^^ `if` condition requires an `else`-clause with `nil` in it.
RUBY
expect_correction(<<~RUBY)
if cond; foo else; nil; end
RUBY
end
it 'registers an offense with `elsif` clause' do
expect_offense(<<~RUBY)
if cond_1; 1; elsif cond_2; 3; end
^^^^^^^^^^^^^^^ `if` condition requires an `else`-clause with `nil` in it.
RUBY
expect_correction(<<~RUBY)
if cond_1; 1; elsif cond_2; 3; else; nil; end
RUBY
end
it 'registers an offense with multiple `elsif` clauses' do
expect_offense(<<~RUBY)
if cond_1; 1; elsif cond_2; 2; elsif cond_3; 3; end
^^^^^^^^^^^^^^^ `if` condition requires an `else`-clause with `nil` in it.
RUBY
expect_correction(<<~RUBY)
if cond_1; 1; elsif cond_2; 2; elsif cond_3; 3; else; nil; end
RUBY
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless cond; foo end
^^^^^^^^^^^^^^^^^^^^ `if` condition requires an `else`-clause with `nil` in it.
RUBY
expect_correction(<<~RUBY)
unless cond; foo else; nil; end
RUBY
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
case v; when a; foo; when b; bar; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `case` condition requires an `else`-clause with `nil` in it.
RUBY
expect_correction(<<~RUBY)
case v; when a; foo; when b; bar; else; nil; end
RUBY
end
end
end
it_behaves_like 'pattern matching'
end
context 'EmptyElse enabled and set to warn on nil' do
let(:config) do
styles = %w[if case both]
RuboCop::Config.new('Style/MissingElse' => {
'Enabled' => true,
'EnforcedStyle' => 'both',
'SupportedStyles' => styles
},
'Style/UnlessElse' => { 'Enabled' => false },
'Style/EmptyElse' => {
'Enabled' => true,
'EnforcedStyle' => 'nil',
'SupportedStyles' => %w[empty nil both]
})
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo elsif b; bar else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if cond; foo end
^^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
if cond; foo else; end
RUBY
end
it 'registers an offense with `elsif` clause' do
expect_offense(<<~RUBY)
if cond_1; 1; elsif cond_2; 3; end
^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
if cond_1; 1; elsif cond_2; 3; else; end
RUBY
end
it 'registers an offense with multiple `elsif` clauses' do
expect_offense(<<~RUBY)
if cond_1; 1; elsif cond_2; 2; elsif cond_3; 3; end
^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
if cond_1; 1; elsif cond_2; 2; elsif cond_3; 3; else; end
RUBY
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless cond; foo end
^^^^^^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
unless cond; foo else; end
RUBY
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
case v; when a; foo; when b; bar; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `case` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
case v; when a; foo; when b; bar; else; end
RUBY
end
end
end
it_behaves_like 'pattern matching'
end
context 'configured to warn only on empty if' do
let(:config) do
styles = %w[if case both]
RuboCop::Config.new('Style/MissingElse' => {
'Enabled' => true,
'EnforcedStyle' => 'if',
'SupportedStyles' => styles
},
'Style/UnlessElse' => { 'Enabled' => false },
'Style/EmptyElse' => {
'Enabled' => true,
'EnforcedStyle' => 'nil',
'SupportedStyles' => %w[empty nil both]
})
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo elsif b; bar else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if cond; foo end
^^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
if cond; foo else; end
RUBY
end
it 'registers an offense with `elsif` clause' do
expect_offense(<<~RUBY)
if cond_1; 1; elsif cond_2; 3; end
^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
if cond_1; 1; elsif cond_2; 3; else; end
RUBY
end
it 'registers an offense with multiple `elsif` clauses' do
expect_offense(<<~RUBY)
if cond_1; 1; elsif cond_2; 2; elsif cond_3; 3; end
^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
if cond_1; 1; elsif cond_2; 2; elsif cond_3; 3; else; end
RUBY
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless cond; foo end
^^^^^^^^^^^^^^^^^^^^ `if` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
unless cond; foo else; end
RUBY
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; end')
end
end
end
it_behaves_like 'pattern matching'
end
context 'configured to warn only on empty case' do
let(:config) do
styles = %w[if case both]
RuboCop::Config.new('Style/MissingElse' => {
'Enabled' => true,
'EnforcedStyle' => 'case',
'SupportedStyles' => styles
},
'Style/UnlessElse' => { 'Enabled' => false },
'Style/EmptyElse' => {
'Enabled' => true,
'EnforcedStyle' => 'nil',
'SupportedStyles' => %w[empty nil both]
})
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo elsif b; bar else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo end')
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo end')
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
case v; when a; foo; when b; bar; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `case` condition requires an empty `else`-clause.
RUBY
expect_correction(<<~RUBY)
case v; when a; foo; when b; bar; else; end
RUBY
end
end
end
it_behaves_like 'pattern matching'
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/hash_conversion_spec.rb | spec/rubocop/cop/style/hash_conversion_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashConversion, :config do
it 'reports an offense for single-argument Hash[]' do
expect_offense(<<~RUBY)
Hash[ary]
^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
ary.to_h
RUBY
end
it 'reports different offense for multi-argument Hash[]' do
expect_offense(<<~RUBY)
Hash[a, b, c, d]
^^^^^^^^^^^^^^^^ Prefer literal hash to `Hash[arg1, arg2, ...]`.
RUBY
expect_correction(<<~RUBY)
{a => b, c => d}
RUBY
end
it 'reports different offense for hash argument Hash[]' do
expect_offense(<<~RUBY)
Hash[a: b, c: d]
^^^^^^^^^^^^^^^^ Prefer literal hash to `Hash[key: value, ...]`.
RUBY
expect_correction(<<~RUBY)
{a: b, c: d}
RUBY
end
it 'reports different offense for hash argument Hash[] as a method argument with parentheses' do
expect_offense(<<~RUBY)
do_something(Hash[a: b, c: d], 42)
^^^^^^^^^^^^^^^^ Prefer literal hash to `Hash[key: value, ...]`.
RUBY
expect_correction(<<~RUBY)
do_something({a: b, c: d}, 42)
RUBY
end
it 'reports different offense for hash argument Hash[] as a method argument without parentheses' do
expect_offense(<<~RUBY)
do_something Hash[a: b, c: d], 42
^^^^^^^^^^^^^^^^ Prefer literal hash to `Hash[key: value, ...]`.
RUBY
expect_correction(<<~RUBY)
do_something({a: b, c: d}, 42)
RUBY
end
it 'reports different offense for empty Hash[]' do
expect_offense(<<~RUBY)
Hash[]
^^^^^^ Prefer literal hash to `Hash[arg1, arg2, ...]`.
RUBY
expect_correction(<<~RUBY)
{}
RUBY
end
it 'registers and corrects an offense when using multi-argument `Hash[]` as a method argument' do
expect_offense(<<~RUBY)
do_something Hash[a, b, c, d], arg
^^^^^^^^^^^^^^^^ Prefer literal hash to `Hash[arg1, arg2, ...]`.
RUBY
expect_correction(<<~RUBY)
do_something({a => b, c => d}, arg)
RUBY
end
it 'does not try to correct multi-argument Hash with odd number of arguments' do
expect_offense(<<~RUBY)
Hash[a, b, c]
^^^^^^^^^^^^^ Prefer literal hash to `Hash[arg1, arg2, ...]`.
RUBY
expect_no_corrections
end
it 'wraps complex statements in parens if needed' do
expect_offense(<<~RUBY)
Hash[a.foo :bar]
^^^^^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
(a.foo :bar).to_h
RUBY
end
it 'registers and corrects an offense when using argumentless `zip` without parentheses in `Hash[]`' do
expect_offense(<<~RUBY)
Hash[array.zip]
^^^^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
array.zip([]).to_h
RUBY
end
it 'registers and corrects an offense when using argumentless `zip` with parentheses in `Hash[]`' do
expect_offense(<<~RUBY)
Hash[array.zip()]
^^^^^^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
array.zip([]).to_h
RUBY
end
it 'reports different offense for Hash[a || b]' do
expect_offense(<<~RUBY)
Hash[a || b]
^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
(a || b).to_h
RUBY
end
it 'reports different offense for Hash[(a || b)]' do
expect_offense(<<~RUBY)
Hash[(a || b)]
^^^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
(a || b).to_h
RUBY
end
it 'reports different offense for Hash[a && b]' do
expect_offense(<<~RUBY)
Hash[a && b]
^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
(a && b).to_h
RUBY
end
it 'reports different offense for Hash[(a && b)]' do
expect_offense(<<~RUBY)
Hash[(a && b)]
^^^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
(a && b).to_h
RUBY
end
it 'registers and corrects an offense when using `zip` with argument in `Hash[]`' do
expect_offense(<<~RUBY)
Hash[array.zip([1, 2, 3])]
^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
array.zip([1, 2, 3]).to_h
RUBY
end
it 'reports an offense when using nested `Hash[]` without arguments' do
expect_offense(<<~RUBY)
Hash[Hash[]]
^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
Hash[].to_h
RUBY
end
it 'reports an offense when using nested `Hash[]` with arguments' do
expect_offense(<<~RUBY)
Hash[Hash[k, v]]
^^^^^^^^^^^^^^^^ Prefer `ary.to_h` to `Hash[ary]`.
RUBY
expect_correction(<<~RUBY)
Hash[k, v].to_h
RUBY
end
it 'registers an offense and corrects nested `Hash[]` calls with multiple arguments' do
expect_offense(<<~RUBY)
Hash[1, Hash[k, v]]
^^^^^^^^^^^^^^^^^^^ Prefer literal hash to `Hash[arg1, arg2, ...]`.
RUBY
expect_correction(<<~RUBY)
{1 => Hash[k, v]}
RUBY
end
it 'reports an offense for `Hash[].to_h`' do
expect_offense(<<~RUBY)
Hash[].to_h
^^^^^^ Prefer literal hash to `Hash[arg1, arg2, ...]`.
RUBY
expect_correction(<<~RUBY)
{}.to_h
RUBY
end
context 'AllowSplatArgument: true' do
let(:cop_config) { { 'AllowSplatArgument' => true } }
it 'does not register an offense for unpacked array' do
expect_no_offenses(<<~RUBY)
Hash[*ary]
RUBY
end
end
context 'AllowSplatArgument: false' do
let(:cop_config) { { 'AllowSplatArgument' => false } }
it 'reports uncorrectable offense for unpacked array' do
expect_offense(<<~RUBY)
Hash[*ary]
^^^^^^^^^^ Prefer `array_of_pairs.to_h` to `Hash[*array]`.
RUBY
expect_no_corrections
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/optional_arguments_spec.rb | spec/rubocop/cop/style/optional_arguments_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::OptionalArguments, :config do
it 'registers an offense when an optional argument is followed by a required argument' do
expect_offense(<<~RUBY)
def foo(a = 1, b)
^^^^^ Optional arguments should appear at the end of the argument list.
end
RUBY
end
it 'registers an offense for each optional argument when multiple ' \
'optional arguments are followed by a required argument' do
expect_offense(<<~RUBY)
def foo(a = 1, b = 2, c)
^^^^^ Optional arguments should appear at the end of the argument list.
^^^^^ Optional arguments should appear at the end of the argument list.
end
RUBY
end
it 'allows methods without arguments' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
it 'allows methods with only one required argument' do
expect_no_offenses(<<~RUBY)
def foo(a)
end
RUBY
end
it 'allows methods with only required arguments' do
expect_no_offenses(<<~RUBY)
def foo(a, b, c)
end
RUBY
end
it 'allows methods with only one optional argument' do
expect_no_offenses(<<~RUBY)
def foo(a = 1)
end
RUBY
end
it 'allows methods with only optional arguments' do
expect_no_offenses(<<~RUBY)
def foo(a = 1, b = 2, c = 3)
end
RUBY
end
it 'allows methods with multiple optional arguments at the end' do
expect_no_offenses(<<~RUBY)
def foo(a, b = 2, c = 3)
end
RUBY
end
context 'named params' do
context 'with default values' do
it 'allows optional arguments before an optional named argument' do
expect_no_offenses(<<~RUBY)
def foo(a = 1, b: 2)
end
RUBY
end
end
context 'required params', :ruby21 do
it 'registers an offense for optional arguments that come before ' \
'required arguments where there are name arguments' do
expect_offense(<<~RUBY)
def foo(a = 1, b, c:, d: 4)
^^^^^ Optional arguments should appear at the end of the argument list.
end
RUBY
end
it 'allows optional arguments before required named arguments' do
expect_no_offenses(<<~RUBY)
def foo(a = 1, b:)
end
RUBY
end
it 'allows optional arguments to come before a mix of required and optional named argument' do
expect_no_offenses(<<~RUBY)
def foo(a = 1, b:, c: 3)
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/safe_navigation_chain_length_spec.rb | spec/rubocop/cop/style/safe_navigation_chain_length_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SafeNavigationChainLength, :config do
let(:cop_config) { { 'Max' => max } }
let(:max) { 2 }
it 'registers an offense when exceeding safe navigation chain length' do
expect_offense(<<~RUBY)
x&.foo&.bar&.baz
^^^^^^^^^^^^^^^^ Avoid safe navigation chains longer than 2 calls.
RUBY
end
it 'registers an offense when exceeding safe navigation chain length on method call receiver' do
expect_offense(<<~RUBY)
x.foo&.bar&.baz&.zoo
^^^^^^^^^^^^^^^^^^^^ Avoid safe navigation chains longer than 2 calls.
RUBY
end
it 'registers an offense when exceeding safe navigation chain length in the middle of call chain' do
expect_offense(<<~RUBY)
x.foo&.bar&.baz&.zoo.nil?
^^^^^^^^^^^^^^^^^^^^ Avoid safe navigation chains longer than 2 calls.
RUBY
end
it 'does not register an offense when not exceeding safe navigation chain length' do
expect_no_offenses(<<~RUBY)
x&.foo&.bar
RUBY
end
it 'does not register an offense when using regular methods calls' do
expect_no_offenses(<<~RUBY)
x.foo.bar
RUBY
end
context 'Max: 1' do
let(:max) { 1 }
it 'registers an offense when exceeding safe navigation chain length' do
expect_offense(<<~RUBY)
x&.foo&.bar
^^^^^^^^^^^ Avoid safe navigation chains longer than 1 calls.
RUBY
end
end
context 'Max: 3' do
let(:max) { 3 }
it 'registers an offense when exceeding safe navigation chain length' do
expect_offense(<<~RUBY)
x&.foo&.bar&.baz&.zoo
^^^^^^^^^^^^^^^^^^^^^ Avoid safe navigation chains longer than 3 calls.
RUBY
end
it 'does not register an offense when not exceeding safe navigation chain length' do
expect_no_offenses(<<~RUBY)
x&.foo&.bar&.baz
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/nested_parenthesized_calls_spec.rb | spec/rubocop/cop/style/nested_parenthesized_calls_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NestedParenthesizedCalls, :config do
let(:config) do
RuboCop::Config.new('Style/NestedParenthesizedCalls' => { 'AllowedMethods' => ['be'] })
end
context 'on a non-parenthesized method call' do
it "doesn't register an offense" do
expect_no_offenses('puts 1, 2')
end
end
context 'on a method call with no arguments' do
it "doesn't register an offense" do
expect_no_offenses('puts')
end
end
context 'on a nested, parenthesized method call' do
it "doesn't register an offense" do
expect_no_offenses('puts(compute(something))')
end
end
context 'on a non-parenthesized call nested in a parenthesized one' do
context 'with a single argument to the nested call' do
it 'registers an offense' do
expect_offense(<<~RUBY)
puts(compute something)
^^^^^^^^^^^^^^^^^ Add parentheses to nested method call `compute something`.
RUBY
expect_correction(<<~RUBY)
puts(compute(something))
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense' do
expect_offense(<<~RUBY)
puts(receiver&.compute something)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add parentheses to nested method call `receiver&.compute something`.
RUBY
expect_correction(<<~RUBY)
puts(receiver&.compute(something))
RUBY
end
end
end
context 'with multiple arguments to the nested call' do
it 'registers an offense' do
expect_offense(<<~RUBY)
puts(compute first, second)
^^^^^^^^^^^^^^^^^^^^^ Add parentheses to nested method call `compute first, second`.
RUBY
expect_correction(<<~RUBY)
puts(compute(first, second))
RUBY
end
end
end
context 'on a call with no arguments, nested in a parenthesized one' do
it "doesn't register an offense" do
expect_no_offenses('puts(compute)')
end
end
context 'on an aref, nested in a parenthesized method call' do
it "doesn't register an offense" do
expect_no_offenses('method(obj[1])')
end
end
context 'on a deeply nested argument' do
it "doesn't register an offense" do
expect_no_offenses('method(block_taker { another_method 1 })')
end
end
context 'on a permitted method' do
it "doesn't register an offense" do
expect_no_offenses('expect(obj).to(be true)')
end
end
context 'on a call to a setter method' do
it "doesn't register an offense" do
expect_no_offenses('expect(object1.attr = 1).to eq 1')
end
end
context 'backslash newline in method call' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
puts(nex \
^^^^^ Add parentheses to nested method call [...]
5)
RUBY
expect_correction(<<~RUBY)
puts(nex(5))
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/hash_except_spec.rb | spec/rubocop/cop/style/hash_except_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashExcept, :config do
shared_examples 'include?' do
context 'using `include?`' do
it 'does not register an offense when using `reject` and calling `!include?` method with symbol array' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !%i[foo bar].include?(k) }
RUBY
end
it 'registers and corrects an offense when using `select` and calling `!include?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| !%i[foo bar].include?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using `filter` and calling `!include?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.filter { |k, v| ![:foo, :bar].include?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `include?` method with dynamic symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| %I[\#{foo} bar].include?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:"\#{foo}", :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:"\#{foo}", :bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `include?` method with dynamic string array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| %W[\#{foo} bar].include?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except("\#{foo}", 'bar')` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except("\#{foo}", 'bar')
RUBY
end
it 'does not register an offense when using `reject` and calling `!include?` method with variable' do
expect_no_offenses(<<~RUBY)
array = %i[foo bar]
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !array.include?(k) }
RUBY
end
it 'does not register an offense when using `reject` and calling `!include?` method with method call' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !array.include?(k) }
RUBY
end
it 'registers an offense when using `reject` and `include?`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| [:bar].include?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it 'does not register an offense when using `reject` and calling `!include?` method with symbol array and second block value' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| ![1, 2].include?(v) }
RUBY
end
it 'does not register an offense when using `reject` and calling `include?` method on a key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.include?('oo') }
RUBY
end
it 'does not register an offense when using `reject` and calling `!include?` method on a key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !k.include?('oo') }
RUBY
end
it 'does not register an offense when using `reject` with `!include?` with an inclusive range receiver' do
expect_no_offenses(<<~RUBY)
{ foo: 1, bar: 2, baz: 3 }.reject { |k, v| (:baa..:bbb).include?(k) }
RUBY
end
it 'does not register an offense when using `reject` with `!include?` with an exclusive range receiver' do
expect_no_offenses(<<~RUBY)
{ foo: 1, bar: 2, baz: 3 }.reject { |k, v| (:baa...:bbb).include?(k) }
RUBY
end
it 'does not register an offense when using `reject` with `!include?` called on the key block variable' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| !k.include?('foo') }
RUBY
end
it 'does not register an offense when using `reject` with `!include?` called on the value block variable' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| !v.include?(k) }
RUBY
end
end
end
context 'Ruby 3.0 or higher', :ruby30 do
it 'registers and corrects an offense when using `reject` and comparing with `lvar == :sym`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k == :bar }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it 'registers and corrects an offense when using safe navigation `reject` call and comparing with `lvar == :sym`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.reject { |k, v| k == :bar }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.except(:bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and comparing with `:sym == lvar`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar == k }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it 'registers and corrects an offense when using `select` and comparing with `lvar != :sym`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| k != :bar }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it 'registers and corrects an offense when using `select` and comparing with `:sym != lvar`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| :bar != k }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it "registers and corrects an offense when using `reject` and comparing with `lvar == 'str'`" do
expect_offense(<<~RUBY)
hash.reject { |k, v| k == 'str' }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except('str')` instead.
RUBY
expect_correction(<<~RUBY)
hash.except('str')
RUBY
end
it 'registers and corrects an offense when using `reject` and other than comparison by string and symbol using `eql?`' do
expect_offense(<<~RUBY)
hash.reject { |k, v| k.eql?(0.0) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(0.0)` instead.
RUBY
expect_correction(<<~RUBY)
hash.except(0.0)
RUBY
end
it 'registers and corrects an offense when using `filter` and comparing with `lvar != :sym`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.filter { |k, v| k != :bar }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it_behaves_like 'include?'
context 'using `in?`' do
it 'does not register offenses when using `reject` and calling `key.in?` method with symbol array' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.in?(%i[foo bar]) }
RUBY
end
it 'does not register offenses when using safe navigation `reject` and calling `key.in?` method with symbol array' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.reject { |k, v| k.in?(%i[foo bar]) }
RUBY
end
it 'does not register offenses when using `reject` and calling `in?` method with key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| %i[foo bar].in?(k) }
RUBY
end
end
context 'using `exclude?`' do
it 'does not register offenses when using `reject` and calling `!exclude?` method with symbol array' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !%i[foo bar].exclude?(k) }
RUBY
end
it 'does not register offenses when using safe navigation `reject` and calling `!exclude?` method with symbol array' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.reject { |k, v| !%i[foo bar].exclude?(k) }
RUBY
end
it 'does not register an offense when using `reject` and calling `exclude?` method on a key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.exclude?('oo') }
RUBY
end
it 'does not register an offense when using `reject` and calling `!exclude?` method on a key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !k.exclude?('oo') }
RUBY
end
end
it 'does not register an offense when using `reject` and other than comparison by string and symbol using `==`' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| k == 0.0 }
RUBY
end
it 'does not register an offense when using `select` and other than comparison by string and symbol using `!=`' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| k != 0.0 }
RUBY
end
it 'does not register an offense when using `select` and other than comparison by string and symbol using `==` with bang' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| !(k == 0.0) }
RUBY
end
it 'does not register an offense when using `reject` and other than comparison by string and symbol using `!=` with bang' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| !(k != 0.0) }
RUBY
end
it 'does not register an offense when using `delete_if` and comparing with `lvar == :sym`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.delete_if { |k, v| k == :bar }
RUBY
end
it 'does not register an offense when using `keep_if` and comparing with `lvar != :sym`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.keep_if { |k, v| k != :bar }
RUBY
end
it 'does not register an offense when comparing with hash value' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| v.eql? :bar }
RUBY
end
it 'does not register an offense when using more than two block arguments' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v, o| k == :bar }
RUBY
end
it 'does not register an offense when calling `include?` method without a param' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| %i[foo bar].include? }
RUBY
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => {
'TargetRubyVersion' => '3.0',
'ActiveSupportExtensionsEnabled' => true
})
end
it 'registers and corrects an offense when using `reject` and comparing with `lvar == :sym`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k == :bar }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and comparing with `:sym == lvar`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar == k }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it 'registers and corrects an offense when using `select` and comparing with `lvar != :sym`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| k != :bar }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it 'registers and corrects an offense when using `select` and comparing with `:sym != lvar`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| :bar != k }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it "registers and corrects an offense when using `reject` and comparing with `lvar == 'str'`" do
expect_offense(<<~RUBY)
hash.reject { |k, v| k == 'str' }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except('str')` instead.
RUBY
expect_correction(<<~RUBY)
hash.except('str')
RUBY
end
it 'registers and corrects an offense when using `reject` and other than comparison by string and symbol using `eql?`' do
expect_offense(<<~RUBY)
hash.reject { |k, v| k.eql?(0.0) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(0.0)` instead.
RUBY
expect_correction(<<~RUBY)
hash.except(0.0)
RUBY
end
it 'registers and corrects an offense when using `filter` and comparing with `lvar != :sym`' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.filter { |k, v| k != :bar }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
it_behaves_like 'include?'
context 'using `in?`' do
it 'registers and corrects an offense when using `reject` and calling `key.in?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.in?(%i[foo bar]) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using safe navigation `reject` and calling `key.in?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.reject { |k, v| k.in?(%i[foo bar]) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using `select` and calling `!key.in?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| !k.in?(%i[foo bar]) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using `filter` and calling `!key.in?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.filter { |k, v| !k.in?(%i[foo bar]) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `key.in?` method with dynamic symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.in?(%I[\#{foo} bar]) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:"\#{foo}", :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:"\#{foo}", :bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `key.in?` method with dynamic string array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.in?(%W[\#{foo} bar]) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except("\#{foo}", 'bar')` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except("\#{foo}", 'bar')
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `key.in?` method with variable' do
expect_offense(<<~RUBY)
array = %i[foo bar]
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.in?(array) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(*array)` instead.
RUBY
expect_correction(<<~RUBY)
array = %i[foo bar]
{foo: 1, bar: 2, baz: 3}.except(*array)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `key.in?` method with method call' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.in?(array) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(*array)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(*array)
RUBY
end
it 'does not register an offense when using `reject` and calling `!key.in?` method with symbol array' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !k.in?(%i[foo bar]) }
RUBY
end
it 'does not register an offense when using `reject` and calling `in?` method with key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| %i[foo bar].in?(k) }
RUBY
end
it 'does not register an offense when using `reject` and calling `in?` method with symbol array and second block value' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| v.in?([1, 2]) }
RUBY
end
it 'does not register an offense when using `reject` with `!in?` with an inclusive range argument' do
expect_no_offenses(<<~RUBY)
{ foo: 1, bar: 2, baz: 3 }.reject{ |k, v| k.in?(:baa..:bbb) }
RUBY
end
it 'does not register an offense when using `reject` with `!in?` with an exclusive range argument' do
expect_no_offenses(<<~RUBY)
{ foo: 1, bar: 2, baz: 3 }.reject{ |k, v| k.in?(:baa...:bbb) }
RUBY
end
it 'does not register an offense when using `reject` with `in?` called on the key block variable' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| 'foo'.in?(k) }
RUBY
end
it 'does not register an offense when using `reject` with `in?` called on the value block variable' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| k.in?(v) }
RUBY
end
it 'does not register an offense when using `select` with `!in?` called on the key block variable' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| !'foo'.in?(k) }
RUBY
end
it 'does not register an offense when using `select` with `!in?` called on the value block variable' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| !k.in?(v) }
RUBY
end
end
context 'using `exclude?`' do
it 'registers and corrects an offense when using `reject` and calling `!exclude?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !%i[foo bar].exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using safe navigation `reject` and calling `!exclude?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.reject { |k, v| !%i[foo bar].exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}&.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using `select` and calling `exclude?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| %i[foo bar].exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'does not register an offense when using `select` and calling `!exclude?` method with symbol array' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| !%i[foo bar].exclude?(k) }
RUBY
end
it 'registers and corrects an offense when using `filter` and calling `exclude?` method with symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.filter { |k, v| [:foo, :bar].exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:foo, :bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `!exclude?` method with dynamic symbol array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !%I[\#{foo} bar].exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(:"\#{foo}", :bar)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:"\#{foo}", :bar)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `!exclude?` method with dynamic string array' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !%W[\#{foo} bar].exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except("\#{foo}", 'bar')` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except("\#{foo}", 'bar')
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `!exclude?` method with variable' do
expect_offense(<<~RUBY)
array = %i[foo bar]
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !array.exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(*array)` instead.
RUBY
expect_correction(<<~RUBY)
array = %i[foo bar]
{foo: 1, bar: 2, baz: 3}.except(*array)
RUBY
end
it 'registers and corrects an offense when using `reject` and calling `!exclude?` method with method call' do
expect_offense(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !array.exclude?(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `except(*array)` instead.
RUBY
expect_correction(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(*array)
RUBY
end
it 'does not register an offense when using `reject` and calling `exclude?` method with symbol array and second block value' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| ![1, 2].exclude?(v) }
RUBY
end
it 'does not register an offense when using `reject` and calling `exclude?` method on a key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k.exclude?('oo') }
RUBY
end
it 'does not register an offense when using `reject` and calling `!exclude?` method on a key' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| !k.exclude?('oo') }
RUBY
end
it 'does not register an offense when using `select` with `exclude?` called on the key block variable' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| k.exclude?('foo') }
RUBY
end
it 'does not register an offense when using `select` with `exclude?` called on the value block variable' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| v.exclude?(k) }
RUBY
end
it 'does not register an offense when using `reject` with `!exclude?` called on the key block variable' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| !k.exclude?('foo') }
RUBY
end
it 'does not register an offense when using `reject` with `!exclude?` called on the value block variable' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| !v.exclude?(k) }
RUBY
end
end
it 'does not register an offense when using `reject` and other than comparison by string and symbol using `==`' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| k == 0.0 }
RUBY
end
it 'does not register an offense when using `select` and other than comparison by string and symbol using `!=`' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| k != 0.0 }
RUBY
end
it 'does not register an offense when using `select` and other than comparison by string and symbol using `==` with bang' do
expect_no_offenses(<<~RUBY)
hash.select { |k, v| !(k == 0.0) }
RUBY
end
it 'does not register an offense when using `reject` and other than comparison by string and symbol using `!=` with bang' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| !(k != 0.0) }
RUBY
end
it 'does not register an offense when using `delete_if` and comparing with `lvar == :sym`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.delete_if { |k, v| k == :bar }
RUBY
end
it 'does not register an offense when using `keep_if` and comparing with `lvar != :sym`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.keep_if { |k, v| k != :bar }
RUBY
end
it 'does not register an offense when comparing with hash value' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| v.eql? :bar }
RUBY
end
it 'does not register an offense when using more than two block arguments' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v, z| k == :bar }
RUBY
end
it 'does not register an offense when calling `include?` method without a param' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| %i[foo bar].include? }
RUBY
end
end
it 'does not register an offense when using `reject` and comparing with `lvar != :key`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k != :bar }
RUBY
end
it 'does not register an offense when using `reject` and comparing with `:key != lvar`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar != key }
RUBY
end
it 'does not register an offense when using `select` and comparing with `lvar == :key`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| k == :bar }
RUBY
end
it 'does not register an offense when using `select` and comparing with `:key == lvar`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| :bar == key }
RUBY
end
it 'does not register an offense when not using key block argument`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| do_something != :bar }
RUBY
end
it 'does not register an offense when not using block`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject
RUBY
end
it 'does not register an offense when using `Hash#except`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.except(:bar)
RUBY
end
end
context 'Ruby 2.7 or lower', :ruby27, unsupported_on: :prism do
it 'does not register an offense when using `reject` and comparing with `lvar == :key`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| k == :bar }
RUBY
end
it 'does not register an offense when using `reject` and comparing with `:key == lvar`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar == k }
RUBY
end
it 'does not register an offense when using `select` and comparing with `lvar != :key`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| k != :bar }
RUBY
end
it 'does not register an offense when using `select` and comparing with `:key != lvar`' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.select { |k, v| :bar != k }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/array_intersect_spec.rb | spec/rubocop/cop/style/array_intersect_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ArrayIntersect, :config do
context 'when TargetRubyVersion <= 3.0', :ruby30, unsupported_on: :prism do
it 'does not register an offense when using `(array1 & array2).any?`' do
expect_no_offenses(<<~RUBY)
(array1 & array2).any?
RUBY
end
it 'does not register an offense when using `array1.any? { |e| array2.member?(e) }`' do
expect_no_offenses(<<~RUBY)
array1.any? { |e| array2.member?(e) }
RUBY
end
it 'does not register an offense when using `array1.none? { |e| array2.member?(e) }`' do
expect_no_offenses(<<~RUBY)
array1.none? { |e| array2.member?(e) }
RUBY
end
end
context 'when TargetRubyVersion >= 3.1', :ruby31 do
context 'with Array#&' do
it 'registers an offense when using `(array1 & array2).any?`' do
expect_offense(<<~RUBY)
(array1 & array2).any?
^^^^^^^^^^^^^^^^^^^^^^ Use `array1.intersect?(array2)` instead of `(array1 & array2).any?`.
RUBY
expect_correction(<<~RUBY)
array1.intersect?(array2)
RUBY
end
it 'registers an offense when using `(customer_country_codes & SUPPORTED_COUNTRIES).empty?`' do
expect_offense(<<~RUBY)
(customer_country_codes & SUPPORTED_COUNTRIES).empty?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!customer_country_codes.intersect?(SUPPORTED_COUNTRIES)` instead of `(customer_country_codes & SUPPORTED_COUNTRIES).empty?`.
RUBY
expect_correction(<<~RUBY)
!customer_country_codes.intersect?(SUPPORTED_COUNTRIES)
RUBY
end
it 'registers an offense when using `none?`' do
expect_offense(<<~RUBY)
(a & b).none?
^^^^^^^^^^^^^ Use `!a.intersect?(b)` instead of `(a & b).none?`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it 'does not register an offense when using `(array1 & array2).any?` with block' do
expect_no_offenses(<<~RUBY)
(array1 & array2).any? { |x| false }
RUBY
end
it 'does not register an offense when using `(array1 & array2).any?` with symbol block' do
expect_no_offenses(<<~RUBY)
(array1 & array2).any?(&:block)
RUBY
end
it 'does not register an offense when using `(array1 & array2).any?` with numbered block' do
expect_no_offenses(<<~RUBY)
(array1 & array2).any? { do_something(_1) }
RUBY
end
it 'does not register an offense when using `([1, 2, 3] & [4, 5, 6]).present?`' do
expect_no_offenses(<<~RUBY)
([1, 2, 3] & [4, 5, 6]).present?
RUBY
end
it 'does not register an offense when using `([1, 2, 3] & [4, 5, 6]).blank?`' do
expect_no_offenses(<<~RUBY)
([1, 2, 3] & [4, 5, 6]).blank?
RUBY
end
described_class::ARRAY_SIZE_METHODS.each do |method|
it "registers an offense when using `.#{method} > 0`" do
expect_offense(<<~RUBY, method: method)
(a & b).#{method} > 0
^^^^^^^^^{method}^^^^ Use `a.intersect?(b)` instead of `(a & b).#{method} > 0`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method} == 0`" do
expect_offense(<<~RUBY, method: method)
(a & b).#{method} == 0
^^^^^^^^^{method}^^^^^ Use `!a.intersect?(b)` instead of `(a & b).#{method} == 0`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method} != 0`" do
expect_offense(<<~RUBY, method: method)
(a & b).#{method} != 0
^^^^^^^^^{method}^^^^^ Use `a.intersect?(b)` instead of `(a & b).#{method} != 0`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method}.zero?`" do
expect_offense(<<~RUBY, method: method)
(a & b).#{method}.zero?
^^^^^^^^^{method}^^^^^^ Use `!a.intersect?(b)` instead of `(a & b).#{method}.zero?`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method}.positive?`" do
expect_offense(<<~RUBY, method: method)
(a & b).#{method}.positive?
^^^^^^^^^{method}^^^^^^^^^^ Use `a.intersect?(b)` instead of `(a & b).#{method}.positive?`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it "does not register an offense when using `.#{method} > 1`" do
expect_no_offenses(<<~RUBY)
(a & b).#{method} > 1
RUBY
end
it "does not register an offense when using `.#{method} == 1`" do
expect_no_offenses(<<~RUBY)
(a & b).#{method} == 1
RUBY
end
end
end
context 'with Array#intersection' do
it 'registers an offense for `a.intersection(b).any?`' do
expect_offense(<<~RUBY)
a.intersection(b).any?
^^^^^^^^^^^^^^^^^^^^^^ Use `a.intersect?(b)` instead of `a.intersection(b).any?`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it 'registers an offense for `a.intersection(b).none?`' do
expect_offense(<<~RUBY)
a.intersection(b).none?
^^^^^^^^^^^^^^^^^^^^^^^ Use `!a.intersect?(b)` instead of `a.intersection(b).none?`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it 'registers an offense for `a.intersection(b).empty?`' do
expect_offense(<<~RUBY)
a.intersection(b).empty?
^^^^^^^^^^^^^^^^^^^^^^^^ Use `!a.intersect?(b)` instead of `a.intersection(b).empty?`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it 'registers an offense when using safe navigation' do
expect_offense(<<~RUBY)
a&.intersection(b)&.any?
^^^^^^^^^^^^^^^^^^^^^^^^ Use `a&.intersect?(b)` instead of `a&.intersection(b)&.any?`.
RUBY
expect_correction(<<~RUBY)
a&.intersect?(b)
RUBY
end
it 'does not register an offense for `array.intersection` with no arguments' do
expect_no_offenses(<<~RUBY)
array1.intersection.any?
RUBY
end
it 'does not register an offense for `array.intersection` with multiple arguments' do
expect_no_offenses(<<~RUBY)
array1.intersection(array2, array3).any?
RUBY
end
it 'does not register an offense for `intersection(other).any?` without a receiver' do
expect_no_offenses(<<~RUBY)
intersection(other).any?
RUBY
end
described_class::ARRAY_SIZE_METHODS.each do |method|
it "registers an offense when using `.#{method} > 0`" do
expect_offense(<<~RUBY, method: method)
a.intersection(b).#{method} > 0
^^^^^^^^^^^^^^^^^^^{method}^^^^ Use `a.intersect?(b)` instead of `a.intersection(b).#{method} > 0`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method} == 0`" do
expect_offense(<<~RUBY, method: method)
a.intersection(b).#{method} == 0
^^^^^^^^^^^^^^^^^^^{method}^^^^^ Use `!a.intersect?(b)` instead of `a.intersection(b).#{method} == 0`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method} != 0`" do
expect_offense(<<~RUBY, method: method)
a.intersection(b).#{method} != 0
^^^^^^^^^^^^^^^^^^^{method}^^^^^ Use `a.intersect?(b)` instead of `a.intersection(b).#{method} != 0`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method}.zero?`" do
expect_offense(<<~RUBY, method: method)
a.intersection(b).#{method}.zero?
^^^^^^^^^^^^^^^^^^^{method}^^^^^^ Use `!a.intersect?(b)` instead of `a.intersection(b).#{method}.zero?`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it "registers an offense when using `.#{method}.positive?`" do
expect_offense(<<~RUBY, method: method)
a.intersection(b).#{method}.positive?
^^^^^^^^^^^^^^^^^^^{method}^^^^^^^^^^ Use `a.intersect?(b)` instead of `a.intersection(b).#{method}.positive?`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it "registers an offense when using `&.#{method}&.positive?`" do
expect_offense(<<~RUBY, method: method)
a&.intersection(b)&.#{method}&.positive?
^^^^^^^^^^^^^^^^^^^^^{method}^^^^^^^^^^^ Use `a&.intersect?(b)` instead of `a&.intersection(b)&.#{method}&.positive?`.
RUBY
expect_correction(<<~RUBY)
a&.intersect?(b)
RUBY
end
it "does not register an offense when using `.#{method} > 1`" do
expect_no_offenses(<<~RUBY)
a.intersection(b).#{method} > 1
RUBY
end
it "does not register an offense when using `.#{method} == 1`" do
expect_no_offenses(<<~RUBY)
a.intersection(b).#{method} == 1
RUBY
end
it "does not register an offense for `intersection(other).#{method}` without a receiver" do
expect_no_offenses(<<~RUBY)
intersection(other).#{method} == 0
RUBY
end
end
end
context 'with Array#any?' do
it 'registers an offense when using `array1.any? { |e| array2.member?(e) }`' do
expect_offense(<<~RUBY)
array1.any? { |e| array2.member?(e) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `array1.intersect?(array2)` instead of `array1.any? { |e| array2.member?(e) }`.
RUBY
expect_correction(<<~RUBY)
array1.intersect?(array2)
RUBY
end
it 'registers an offense when using `array1&.any? { |e| array2.member?(e) }`' do
expect_offense(<<~RUBY)
array1&.any? { |e| array2.member?(e) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `array1&.intersect?(array2)` instead of `array1&.any? { |e| array2.member?(e) }`.
RUBY
expect_correction(<<~RUBY)
array1&.intersect?(array2)
RUBY
end
it 'registers an offense when using `array1.any? { array2.member?(_1) }`' do
expect_offense(<<~RUBY)
array1.any? { array2.member?(_1) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `array1.intersect?(array2)` instead of `array1.any? { array2.member?(_1) }`.
RUBY
expect_correction(<<~RUBY)
array1.intersect?(array2)
RUBY
end
context '>= Ruby 3.4', :ruby34 do
it 'registers an offense when using `array1.any? { array2.member?(it) }`' do
expect_offense(<<~RUBY)
array1.any? { array2.member?(it) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `array1.intersect?(array2)` instead of `array1.any? { array2.member?(it) }`.
RUBY
expect_correction(<<~RUBY)
array1.intersect?(array2)
RUBY
end
end
context '<= Ruby 3.3', :ruby33 do
it 'does not register an offense when using `array1.any? { array2.member?(it) }`' do
expect_no_offenses(<<~RUBY)
array1.any? { array2.member?(it) }
RUBY
end
end
end
context 'with Array#none?' do
it 'registers an offense when using `array1.none? { |e| array2.member?(e) }`' do
expect_offense(<<~RUBY)
array1.none? { |e| array2.member?(e) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!array1.intersect?(array2)` instead of `array1.none? { |e| array2.member?(e) }`.
RUBY
expect_correction(<<~RUBY)
!array1.intersect?(array2)
RUBY
end
it 'registers an offense when using `array1&.none? { |e| array2.member?(e) }`' do
expect_offense(<<~RUBY)
array1&.none? { |e| array2.member?(e) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!array1&.intersect?(array2)` instead of `array1&.none? { |e| array2.member?(e) }`.
RUBY
expect_correction(<<~RUBY)
!array1&.intersect?(array2)
RUBY
end
it 'registers an offense when using `array1.none? { array2.member?(_1) }`' do
expect_offense(<<~RUBY)
array1.none? { array2.member?(_1) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!array1.intersect?(array2)` instead of `array1.none? { array2.member?(_1) }`.
RUBY
expect_correction(<<~RUBY)
!array1.intersect?(array2)
RUBY
end
context '>= Ruby 3.4', :ruby34 do
it 'registers an offense when using `array1.none? { array2.member?(it) }`' do
expect_offense(<<~RUBY)
array1.none? { array2.member?(it) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!array1.intersect?(array2)` instead of `array1.none? { array2.member?(it) }`.
RUBY
expect_correction(<<~RUBY)
!array1.intersect?(array2)
RUBY
end
end
context '<= Ruby 3.3', :ruby33 do
it 'does not register an offense when using `array1.none? { array2.member?(it) }`' do
expect_no_offenses(<<~RUBY)
array1.none? { array2.member?(it) }
RUBY
end
end
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => {
'TargetRubyVersion' => '3.1',
'ActiveSupportExtensionsEnabled' => true
})
end
it 'registers an offense when using `([1, 2, 3] & [4, 5, 6]).present?`' do
expect_offense(<<~RUBY)
([1, 2, 3] & [4, 5, 6]).present?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[1, 2, 3].intersect?([4, 5, 6])` instead of `([1, 2, 3] & [4, 5, 6]).present?`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].intersect?([4, 5, 6])
RUBY
end
it 'registers an offense when using `(conditions.pluck("type") & %w[customer_country ip_country]).blank?`' do
expect_offense(<<~RUBY)
(conditions.pluck("type") & %w[customer_country ip_country]).blank?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!conditions.pluck("type").intersect?(%w[customer_country ip_country])` instead of `(conditions.pluck("type") & %w[customer_country ip_country]).blank?`.
RUBY
expect_correction(<<~RUBY)
!conditions.pluck("type").intersect?(%w[customer_country ip_country])
RUBY
end
it 'registers an offense for `a.intersection(b).present?`' do
expect_offense(<<~RUBY)
a.intersection(b).present?
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `a.intersect?(b)` instead of `a.intersection(b).present?`.
RUBY
expect_correction(<<~RUBY)
a.intersect?(b)
RUBY
end
it 'registers an offense for `a.intersection(b).blank?`' do
expect_offense(<<~RUBY)
a.intersection(b).blank?
^^^^^^^^^^^^^^^^^^^^^^^^ Use `!a.intersect?(b)` instead of `a.intersection(b).blank?`.
RUBY
expect_correction(<<~RUBY)
!a.intersect?(b)
RUBY
end
it 'does not register an offense when using `alpha & beta`' do
expect_no_offenses(<<~RUBY)
alpha & beta
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/variable_interpolation_spec.rb | spec/rubocop/cop/style/variable_interpolation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::VariableInterpolation, :config do
it 'registers an offense for interpolated global variables in string' do
expect_offense(<<~'RUBY')
puts "this is a #$test"
^^^^^ Replace interpolated variable `$test` with expression `#{$test}`.
RUBY
expect_correction(<<~'RUBY')
puts "this is a #{$test}"
RUBY
end
it 'registers an offense for interpolated global variables in regexp' do
expect_offense(<<~'RUBY')
puts /this is a #$test/
^^^^^ Replace interpolated variable `$test` with expression `#{$test}`.
RUBY
expect_correction(<<~'RUBY')
puts /this is a #{$test}/
RUBY
end
it 'registers an offense for interpolated global variables in backticks' do
expect_offense(<<~'RUBY')
puts `this is a #$test`
^^^^^ Replace interpolated variable `$test` with expression `#{$test}`.
RUBY
expect_correction(<<~'RUBY')
puts `this is a #{$test}`
RUBY
end
it 'registers an offense for interpolated global variables in symbol' do
expect_offense(<<~'RUBY')
puts :"this is a #$test"
^^^^^ Replace interpolated variable `$test` with expression `#{$test}`.
RUBY
expect_correction(<<~'RUBY')
puts :"this is a #{$test}"
RUBY
end
it 'registers an offense for interpolated regexp nth back references' do
expect_offense(<<~'RUBY')
puts "this is a #$1"
^^ Replace interpolated variable `$1` with expression `#{$1}`.
RUBY
expect_correction(<<~'RUBY')
puts "this is a #{$1}"
RUBY
end
it 'registers an offense for interpolated regexp back references' do
expect_offense(<<~'RUBY')
puts "this is a #$+"
^^ Replace interpolated variable `$+` with expression `#{$+}`.
RUBY
expect_correction(<<~'RUBY')
puts "this is a #{$+}"
RUBY
end
it 'registers an offense for interpolated instance variables' do
expect_offense(<<~'RUBY')
puts "this is a #@test"
^^^^^ Replace interpolated variable `@test` with expression `#{@test}`.
RUBY
expect_correction(<<~'RUBY')
puts "this is a #{@test}"
RUBY
end
it 'registers an offense for interpolated class variables' do
expect_offense(<<~'RUBY')
puts "this is a #@@t"
^^^ Replace interpolated variable `@@t` with expression `#{@@t}`.
RUBY
expect_correction(<<~'RUBY')
puts "this is a #{@@t}"
RUBY
end
it 'does not register an offense for variables in expressions' do
expect_no_offenses('puts "this is a #{@test} #{@@t} #{$t} #{$1} #{$+}"')
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_filter_chain_spec.rb | spec/rubocop/cop/style/redundant_filter_chain_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantFilterChain, :config do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => false })
end
%i[select filter find_all].each do |method|
it "registers an offense when using `##{method}` followed by `#any?`" do
expect_offense(<<~RUBY, method: method)
arr.%{method} { |x| x > 1 }.any?
^{method}^^^^^^^^^^^^^^^^^^^ Use `any?` instead of `#{method}.any?`.
RUBY
expect_correction(<<~RUBY)
arr.any? { |x| x > 1 }
RUBY
end
it "registers an offense when using `##{method}` followed by `#empty?`" do
expect_offense(<<~RUBY, method: method)
arr.%{method} { |x| x > 1 }.empty?
^{method}^^^^^^^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.empty?`.
RUBY
expect_correction(<<~RUBY)
arr.none? { |x| x > 1 }
RUBY
end
it "registers an offense when using `##{method}` followed by `#none?`" do
expect_offense(<<~RUBY, method: method)
arr.%{method} { |x| x > 1 }.none?
^{method}^^^^^^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.none?`.
RUBY
expect_correction(<<~RUBY)
arr.none? { |x| x > 1 }
RUBY
end
it "registers an offense when using `##{method}` with block-pass followed by `#none?`" do
expect_offense(<<~RUBY, method: method)
arr.%{method}(&:odd?).none?
^{method}^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.none?`.
RUBY
expect_correction(<<~RUBY)
arr.none?(&:odd?)
RUBY
end
it "does not register an offense when using `##{method}` followed by `#many?`" do
expect_no_offenses(<<~RUBY)
arr.#{method} { |x| x > 1 }.many?
RUBY
end
it "does not register an offense when using `##{method}` followed by `#present?`" do
expect_no_offenses(<<~RUBY)
arr.#{method} { |x| x > 1 }.present?
RUBY
end
it "does not register an offense when using `##{method}` without a block followed by `#any?`" do
expect_no_offenses(<<~RUBY)
relation.#{method}(:name).any?
foo.#{method}.any?
RUBY
end
it "does not register an offense when using `##{method}` followed by `#any?` with arguments" do
expect_no_offenses(<<~RUBY)
arr.#{method}(&:odd?).any?(Integer)
arr.#{method}(&:odd?).any? { |x| x > 10 }
RUBY
end
context 'when using safe navigation operator' do
it "registers an offense when using `##{method}` followed by `#any?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method} { |x| x > 1 }&.any?
^{method}^^^^^^^^^^^^^^^^^^^^ Use `any?` instead of `#{method}.any?`.
RUBY
expect_correction(<<~RUBY)
arr&.any? { |x| x > 1 }
RUBY
end
it "registers an offense when using `##{method}` followed by `#empty?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method} { |x| x > 1 }&.empty?
^{method}^^^^^^^^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.empty?`.
RUBY
expect_correction(<<~RUBY)
arr&.none? { |x| x > 1 }
RUBY
end
it "registers an offense when using `##{method}` followed by `#none?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method} { |x| x > 1 }&.none?
^{method}^^^^^^^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.none?`.
RUBY
expect_correction(<<~RUBY)
arr&.none? { |x| x > 1 }
RUBY
end
it "registers an offense when using `##{method}` with block-pass followed by `#none?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method}(&:odd?)&.none?
^{method}^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.none?`.
RUBY
expect_correction(<<~RUBY)
arr&.none?(&:odd?)
RUBY
end
end
end
it 'does not register an offense when using `#any?`' do
expect_no_offenses(<<~RUBY)
arr.any? { |x| x > 1 }
RUBY
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => true })
end
it 'registers an offense when using `#select` followed by `#many?`' do
expect_offense(<<~RUBY)
arr.select { |x| x > 1 }.many?
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `many?` instead of `select.many?`.
RUBY
expect_correction(<<~RUBY)
arr.many? { |x| x > 1 }
RUBY
end
it 'registers an offense when using `#select` followed by `#present?`' do
expect_offense(<<~RUBY)
arr.select { |x| x > 1 }.present?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead of `select.present?`.
RUBY
expect_correction(<<~RUBY)
arr.any? { |x| x > 1 }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/optional_boolean_parameter_spec.rb | spec/rubocop/cop/style/optional_boolean_parameter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::OptionalBooleanParameter, :config do
let(:cop_config) { { 'AllowedMethods' => [] } }
it 'registers an offense when defining method with optional boolean arg' do
expect_offense(<<~RUBY)
def some_method(bar = false)
^^^^^^^^^^^ Prefer keyword arguments for arguments with a boolean default value; use `bar: false` instead of `bar = false`.
end
RUBY
end
it 'registers an offense when defining method with optional boolean arg that has no space' do
expect_offense(<<~RUBY)
def some_method(bar=false)
^^^^^^^^^ Prefer keyword arguments for arguments with a boolean default value; use `bar: false` instead of `bar=false`.
end
RUBY
end
it 'registers an offense when defining class method with optional boolean arg' do
expect_offense(<<~RUBY)
def self.some_method(bar = false)
^^^^^^^^^^^ Prefer keyword arguments for arguments with a boolean default value; use `bar: false` instead of `bar = false`.
end
RUBY
end
it 'registers an offense when defining method with multiple optional boolean args' do
expect_offense(<<~RUBY)
def some_method(foo = true, bar = 1, baz = false, quux: true)
^^^^^^^^^^ Prefer keyword arguments for arguments with a boolean default value; use `foo: true` instead of `foo = true`.
^^^^^^^^^^^ Prefer keyword arguments for arguments with a boolean default value; use `baz: false` instead of `baz = false`.
end
RUBY
end
it 'does not register an offense when defining method with keyword boolean arg' do
expect_no_offenses(<<~RUBY)
def some_method(bar: false)
end
RUBY
end
it 'does not register an offense when defining method without args' do
expect_no_offenses(<<~RUBY)
def some_method
end
RUBY
end
it 'does not register an offense when defining method with optional non-boolean arg' do
expect_no_offenses(<<~RUBY)
def some_method(bar = 'foo')
end
RUBY
end
context 'when AllowedMethods is not empty' do
let(:cop_config) { { 'AllowedMethods' => %w[respond_to_missing?] } }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def respond_to_missing?(method, include_all = false)
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/documentation_spec.rb | spec/rubocop/cop/style/documentation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Documentation, :config do
let(:config) do
RuboCop::Config.new('Style/CommentAnnotation' => {
'Keywords' => %w[TODO FIXME OPTIMIZE HACK REVIEW]
})
end
it 'registers an offense for non-empty class' do
expect_offense(<<~RUBY)
class MyClass
^^^^^^^^^^^^^ Missing top-level documentation comment for `class MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty cbase class' do
expect_offense(<<~RUBY)
class ::MyClass
^^^^^^^^^^^^^^^ Missing top-level documentation comment for `class ::MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under self' do
expect_offense(<<~RUBY)
class self::MyClass
^^^^^^^^^^^^^^^^^^^ Missing top-level documentation comment for `class self::MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under method call' do
expect_offense(<<~RUBY)
class my_method::MyClass
^^^^^^^^^^^^^^^^^^^^^^^^ Missing top-level documentation comment for `class my_method::MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under safe navigation method call' do
expect_offense(<<~RUBY)
class obj&.my_method::MyClass
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing top-level documentation comment for `class obj&.my_method::MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under local variable' do
expect_offense(<<~RUBY)
m = Module.new
module m::N
^^^^^^^^^^^ Missing top-level documentation comment for `module m::N`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under instance variable' do
expect_offense(<<~RUBY)
module @m::N
^^^^^^^^^^^^ Missing top-level documentation comment for `module @m::N`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under class variable' do
expect_offense(<<~RUBY)
module @@m::N
^^^^^^^^^^^^^ Missing top-level documentation comment for `module @@m::N`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under global variable' do
expect_offense(<<~RUBY)
module $m::N
^^^^^^^^^^^^ Missing top-level documentation comment for `module $m::N`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class nested under local variables' do
expect_offense(<<~RUBY)
m = Module.new
n = Module.new
module m::n::M
^^^^^^^^^^^^^^ Missing top-level documentation comment for `module m::n::M`.
def method
end
end
RUBY
end
it 'does not consider comment followed by empty line to be class documentation' do
expect_offense(<<~RUBY)
# Copyright 2014
# Some company
class MyClass
^^^^^^^^^^^^^ Missing top-level documentation comment for `class MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-namespace' do
expect_offense(<<~RUBY)
module MyModule
^^^^^^^^^^^^^^^ Missing top-level documentation comment for `module MyModule`.
def method
end
end
RUBY
end
it 'registers an offense for empty module without documentation' do
# Because why would you have an empty module? It requires some
# explanation.
expect_offense(<<~RUBY)
module Test
^^^^^^^^^^^ Missing top-level documentation comment for `module Test`.
end
RUBY
end
it 'accepts non-empty class with documentation' do
expect_no_offenses(<<~RUBY)
# class comment
class MyClass
def method
end
end
RUBY
end
it 'registers an offense for non-empty class with annotation comment' do
expect_offense(<<~RUBY)
# OPTIMIZE: Make this faster.
class MyClass
^^^^^^^^^^^^^ Missing top-level documentation comment for `class MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class with directive comment' do
expect_offense(<<~RUBY)
# rubocop:disable Style/For
class MyClass
^^^^^^^^^^^^^ Missing top-level documentation comment for `class MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class with frozen string comment' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
class MyClass
^^^^^^^^^^^^^ Missing top-level documentation comment for `class MyClass`.
def method
end
end
RUBY
end
it 'registers an offense for non-empty class with encoding comment' do
expect_offense(<<~RUBY)
# encoding: ascii-8bit
class MyClass
^^^^^^^^^^^^^ Missing top-level documentation comment for `class MyClass`.
def method
end
end
RUBY
end
it 'accepts non-empty class with annotation comment followed by other comment' do
expect_no_offenses(<<~RUBY)
# OPTIMIZE: Make this faster.
# Class comment.
class MyClass
def method
end
end
RUBY
end
it 'accepts non-empty class with comment that ends with an annotation' do
expect_no_offenses(<<~RUBY)
# Does fooing.
# FIXME: Not yet implemented.
class Foo
def initialize
end
end
RUBY
end
it 'accepts non-empty module with documentation' do
expect_no_offenses(<<~RUBY)
# class comment
module MyModule
def method
end
end
RUBY
end
it 'accepts empty class without documentation' do
expect_no_offenses(<<~RUBY)
class MyClass
end
RUBY
end
it 'accepts namespace module without documentation' do
expect_no_offenses(<<~RUBY)
module Test
class A; end
class B; end
end
RUBY
end
it 'accepts namespace class without documentation' do
expect_no_offenses(<<~RUBY)
class Test
class A; end
class B; end
end
RUBY
end
it 'accepts namespace class which defines constants' do
expect_no_offenses(<<~RUBY)
class Test
A = Class.new
B = Class.new(A)
C = Class.new { call_method }
D = 1
end
RUBY
end
it 'accepts namespace module which defines constants' do
expect_no_offenses(<<~RUBY)
module Test
A = Class.new
B = Class.new(A)
C = Class.new { call_method }
D = 1
end
RUBY
end
context 'without documentation' do
context 'with non-empty module' do
context 'with constants visibility declaration content' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
module Namespace
class Private
end
private_constant :Private
end
RUBY
end
end
end
context 'with non-empty class' do
context 'with constants visibility declaration content' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Namespace
class Private
end
private_constant :Private
end
RUBY
end
end
end
it 'registers an offense with custom macro' do
expect_offense(<<~RUBY)
class Foo < ApplicationRecord
^^^^^^^^^ Missing top-level documentation comment for `class Foo`.
belongs_to :bar
end
RUBY
end
context 'include statement-only class' do
it 'does not register offense with single `include` statements' do
expect_no_offenses(<<~RUBY)
module Foo
include Bar
end
RUBY
end
it 'does not register offense with single `extend` statements' do
expect_no_offenses(<<~RUBY)
module Foo
extend Bar
end
RUBY
end
it 'does not register offense with single `prepend` statements' do
expect_no_offenses(<<~RUBY)
module Foo
prepend Bar
end
RUBY
end
it 'does not register offense with multiple include macros' do
expect_no_offenses(<<~RUBY)
module Foo
include A
include B
extend C
prepend D
end
RUBY
end
it 'registers an offense for include statement with other methods' do
expect_offense(<<~RUBY)
module Foo
^^^^^^^^^^ Missing top-level documentation comment for `module Foo`.
extend B
include C
def foo; end
end
RUBY
end
end
end
it 'does not raise an error for an implicit match conditional' do
expect do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Missing top-level documentation comment for `class Test`.
if //
end
end
RUBY
end.not_to raise_error
end
it 'registers an offense if the comment line contains code' do
expect_offense(<<~RUBY)
module A # The A Module
class B
^^^^^^^ Missing top-level documentation comment for `class A::B`.
C = 1
def method
end
end
end
RUBY
end
it 'registers an offense for compact-style nested module' do
expect_offense(<<~RUBY)
module A::B
^^^^^^^^^^^ Missing top-level documentation comment for `module A::B`.
C = 1
def method
end
end
RUBY
end
it 'registers an offense for compact-style nested class' do
expect_offense(<<~RUBY)
class A::B
^^^^^^^^^^ Missing top-level documentation comment for `class A::B`.
C = 1
def method
end
end
RUBY
end
it 'registers an offense for a deeply nested class' do
expect_offense(<<~RUBY)
module A::B
module C
class D
class E::F
^^^^^^^^^^ Missing top-level documentation comment for `class A::B::C::D::E::F`.
def method
end
end
end
end
end
RUBY
end
context 'sparse and trailing comments' do
%w[class module].each do |keyword|
it "ignores comments after #{keyword} node end" do
expect_no_offenses(<<~RUBY)
module TestModule
# documentation comment
#{keyword} Test
def method
end
end # decorating comment
end
RUBY
end
it "ignores sparse comments inside #{keyword} node" do
expect_offense(<<~RUBY, keyword: keyword)
module TestModule
%{keyword} Test
^{keyword}^^^^^ Missing top-level documentation comment for `#{keyword} TestModule::Test`.
def method
end
# sparse comment
end
end
RUBY
end
end
end
context 'with # :nodoc:' do
%w[class module].each do |keyword|
it "accepts non-namespace #{keyword} without documentation" do
expect_no_offenses(<<~RUBY)
#{keyword} Test #:nodoc:
def method
end
end
RUBY
end
it "accepts compact-style nested #{keyword} without documentation" do
expect_no_offenses(<<~RUBY)
#{keyword} A::B::Test #:nodoc:
def method
end
end
RUBY
end
it "registers an offense for nested #{keyword} without documentation" do
expect_offense(<<~RUBY, keyword: keyword)
module TestModule #:nodoc:
TEST = 20
%{keyword} Test
^{keyword}^^^^^ Missing top-level documentation comment for `#{keyword} TestModule::Test`.
def method
end
end
end
RUBY
end
context 'with `all` modifier' do
it "accepts nested #{keyword} without documentation" do
expect_no_offenses(<<~RUBY)
module A #:nodoc: all
module B
TEST = 20
#{keyword} Test
TEST = 20
end
end
end
RUBY
end
end
end
context 'on a subclass' do
it 'accepts non-namespace subclass without documentation' do
expect_no_offenses(<<~RUBY)
class Test < Parent #:nodoc:
def method
end
end
RUBY
end
it 'registers an offense for nested subclass without documentation' do
expect_offense(<<~RUBY)
module TestModule #:nodoc:
TEST = 20
class Test < Parent
^^^^^^^^^^ Missing top-level documentation comment for `class TestModule::Test`.
def method
end
end
end
RUBY
end
context 'with `all` modifier' do
it 'accepts nested subclass without documentation' do
expect_no_offenses(<<~RUBY)
module A #:nodoc: all
module B
TEST = 20
class Test < Parent
TEST = 20
end
end
end
RUBY
end
end
describe 'when AllowedConstants is configured' do
before { config['Style/Documentation'] = { 'AllowedConstants' => ['ClassMethods'] } }
it 'ignores the constants in the config' do
expect_no_offenses(<<~RUBY)
module A
module ClassMethods
def do_something
end
end
end
RUBY
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/symbol_proc_spec.rb | spec/rubocop/cop/style/symbol_proc_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SymbolProc, :config do
it 'registers an offense for a block with parameterless method call on param' do
expect_offense(<<~RUBY)
coll.map { |e| e.upcase }
^^^^^^^^^^^^^^^^ Pass `&:upcase` as an argument to `map` instead of a block.
RUBY
expect_correction(<<~RUBY)
coll.map(&:upcase)
RUBY
end
it 'registers an offense for a block with parameterless method call on param and no space between method name and opening brace' do
expect_offense(<<~RUBY)
foo.map{ |a| a.nil? }
^^^^^^^^^^^^^^ Pass `&:nil?` as an argument to `map` instead of a block.
RUBY
expect_correction(<<~RUBY)
foo.map(&:nil?)
RUBY
end
it 'registers an offense for safe navigation operator' do
expect_offense(<<~RUBY)
coll&.map { |e| e.upcase }
^^^^^^^^^^^^^^^^ Pass `&:upcase` as an argument to `map` instead of a block.
RUBY
expect_correction(<<~RUBY)
coll&.map(&:upcase)
RUBY
end
it 'registers an offense for a block when method in body is unary -/+' do
expect_offense(<<~RUBY)
something.map { |x| -x }
^^^^^^^^^^ Pass `&:-@` as an argument to `map` instead of a block.
RUBY
expect_correction(<<~RUBY)
something.map(&:-@)
RUBY
end
it 'accepts block with more than 1 arguments' do
expect_no_offenses('something { |x, y| x.method }')
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => true })
end
it 'accepts lambda with 1 argument' do
expect_no_offenses('->(x) { x.method }')
end
it 'accepts proc with 1 argument' do
expect_no_offenses('proc { |x| x.method }')
end
it 'accepts Proc.new with 1 argument' do
expect_no_offenses('Proc.new { |x| x.method }')
end
it 'accepts ::Proc.new with 1 argument' do
expect_no_offenses('::Proc.new { |x| x.method }')
end
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: false`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => false })
end
it 'registers lambda `->` with 1 argument' do
expect_offense(<<~RUBY)
->(x) { x.method }
^^^^^^^^^^^^ Pass `&:method` as an argument to `lambda` instead of a block.
RUBY
expect_correction(<<~RUBY)
lambda(&:method)
RUBY
end
it 'registers lambda `->` with 1 argument and multiline `do`...`end` block' do
expect_offense(<<~RUBY)
->(arg) do
^^ Pass `&:do_something` as an argument to `lambda` instead of a block.
arg.do_something
end
RUBY
expect_correction(<<~RUBY)
lambda(&:do_something)
RUBY
end
it 'registers proc with 1 argument' do
expect_offense(<<~RUBY)
proc { |x| x.method }
^^^^^^^^^^^^^^^^ Pass `&:method` as an argument to `proc` instead of a block.
RUBY
expect_correction(<<~RUBY)
proc(&:method)
RUBY
end
it 'registers Proc.new with 1 argument' do
expect_offense(<<~RUBY)
Proc.new { |x| x.method }
^^^^^^^^^^^^^^^^ Pass `&:method` as an argument to `new` instead of a block.
RUBY
expect_correction(<<~RUBY)
Proc.new(&:method)
RUBY
end
it 'registers ::Proc.new with 1 argument' do
expect_offense(<<~RUBY)
::Proc.new { |x| x.method }
^^^^^^^^^^^^^^^^ Pass `&:method` as an argument to `new` instead of a block.
RUBY
expect_correction(<<~RUBY)
::Proc.new(&:method)
RUBY
end
end
context 'when AllowedMethods is enabled' do
let(:cop_config) { { 'AllowedMethods' => %w[respond_to] } }
it 'accepts ignored method' do
expect_no_offenses('respond_to { |format| format.xml }')
end
end
context 'when AllowedPatterns is enabled' do
let(:cop_config) { { 'AllowedPatterns' => ['respond_'] } }
it 'accepts ignored method' do
expect_no_offenses('respond_to { |format| format.xml }')
end
end
it 'accepts block with no arguments' do
expect_no_offenses('something { x.method }')
end
it 'accepts empty block body' do
expect_no_offenses('something { |x| }')
end
it 'accepts block with more than 1 expression in body' do
expect_no_offenses('something { |x| x.method; something_else }')
end
it 'accepts block when method in body is not called on block arg' do
expect_no_offenses('something { |x| y.method }')
end
it 'accepts block with a block argument' do
expect_no_offenses('something { |&x| x.call }')
end
it 'accepts block with splat params' do
expect_no_offenses('something { |*x| x.first }')
end
it 'accepts block with adding a comma after the sole argument' do
expect_no_offenses('something { |x,| x.first }')
end
it 'accepts a block with an unused argument with a method call' do
expect_no_offenses('something { |_x| y.call }')
end
it 'accepts a block with an unused argument with an lvar' do
expect_no_offenses(<<~RUBY)
y = Y.new
something { |_x| y.call }
RUBY
end
context 'when the method has arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
method(one, 2) { |x| x.test }
^^^^^^^^^^^^^^ Pass `&:test` as an argument to `method` instead of a block.
RUBY
expect_correction(<<~RUBY)
method(one, 2, &:test)
RUBY
end
end
it 'autocorrects multiple aliases with symbols as proc' do
expect_offense(<<~RUBY)
coll.map { |s| s.upcase }.map { |s| s.downcase }
^^^^^^^^^^^^^^^^^^ Pass `&:downcase` as an argument to `map` instead of a block.
^^^^^^^^^^^^^^^^ Pass `&:upcase` as an argument to `map` instead of a block.
RUBY
expect_correction(<<~RUBY)
coll.map(&:upcase).map(&:downcase)
RUBY
end
it 'autocorrects correctly when there are no arguments in parentheses' do
expect_offense(<<~RUBY)
coll.map( ) { |s| s.upcase }
^^^^^^^^^^^^^^^^ Pass `&:upcase` as an argument to `map` instead of a block.
RUBY
expect_correction(<<~RUBY)
coll.map(&:upcase)
RUBY
end
it 'does not crash with a bare method call' do
run = -> { expect_no_offenses('coll.map { |s| bare_method }') }
expect(&run).not_to raise_error
end
%w[reject select].each do |method|
it "registers an offense when receiver is an array literal and using `#{method}` with a block" do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method} {|item| item.foo }
_{method} ^^^^^^^^^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{method}(&:foo)
RUBY
end
it "registers an offense when receiver is some value and using `#{method}` with a block" do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].#{method} {|item| item.foo }
_{method} ^^^^^^^^^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{method}(&:foo)
RUBY
end
it "does not register an offense when receiver is a hash literal and using `#{method}` with a block" do
expect_no_offenses(<<~RUBY)
{foo: 42}.#{method} {|item| item.foo }
RUBY
end
end
%w[min max].each do |method|
it "registers an offense when receiver is a hash literal and using `#{method}` with a block" do
expect_offense(<<~RUBY, method: method)
{foo: 42}.%{method} {|item| item.foo }
_{method} ^^^^^^^^^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
{foo: 42}.#{method}(&:foo)
RUBY
end
it "does not register an offense when receiver is an array literal and using `#{method}` with a block" do
expect_no_offenses(<<~RUBY)
[1, 2, 3].#{method} {|item| item.foo }
RUBY
end
end
context 'when `AllowMethodsWithArguments: true`' do
let(:cop_config) { { 'AllowMethodsWithArguments' => true } }
context 'when method has arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
do_something(one, two) { |x| x.test }
RUBY
end
end
context 'when `super` has arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
super(one, two) { |x| x.test }
RUBY
end
end
context 'when method has no arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
coll.map { |e| e.upcase }
^^^^^^^^^^^^^^^^ Pass `&:upcase` as an argument to `map` instead of a block.
RUBY
end
end
end
context 'when `AllowMethodsWithArguments: false`' do
let(:cop_config) { { 'AllowMethodsWithArguments' => false } }
context 'when method has arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
do_something(one, two) { |x| x.test }
^^^^^^^^^^^^^^ Pass `&:test` as an argument to `do_something` instead of a block.
RUBY
expect_correction(<<~RUBY)
do_something(one, two, &:test)
RUBY
end
end
context 'when `super` has arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
super(one, two) { |x| x.test }
^^^^^^^^^^^^^^ Pass `&:test` as an argument to `super` instead of a block.
RUBY
expect_correction(<<~RUBY)
super(one, two, &:test)
RUBY
end
end
end
context 'AllowComments: true' do
let(:cop_config) { { 'AllowComments' => true } }
it 'registers an offense for a block with parameterless method call on param' \
'and not contains a comment' do
expect_offense(<<~RUBY)
# comment a
something do |e|
^^^^^^ Pass `&:upcase` as an argument to `something` instead of a block.
e.upcase
end # comment b
# comment c
RUBY
expect_correction(<<~RUBY)
# comment a
something(&:upcase) # comment b
# comment c
RUBY
end
it 'accepts block with parameterless method call on param and contains a comment' do
expect_no_offenses(<<~RUBY)
something do |e| # comment
e.upcase
end
RUBY
expect_no_offenses(<<~RUBY)
something do |e|
# comment
e.upcase
end
RUBY
expect_no_offenses(<<~RUBY)
something
something do |e|
# comment
e.upcase
end
RUBY
expect_no_offenses(<<~RUBY)
something do |e|
e.upcase # comment
end
RUBY
expect_no_offenses(<<~RUBY)
something do |e|
e.upcase
# comment
end
RUBY
end
end
context 'when `super` has no arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
super { |x| x.test }
^^^^^^^^^^^^^^ Pass `&:test` as an argument to `super` instead of a block.
RUBY
expect_correction(<<~RUBY)
super(&:test)
RUBY
end
end
it 'autocorrects correctly when args have a trailing comma' do
expect_offense(<<~RUBY)
mail(
to: 'foo',
subject: 'bar',
) { |format| format.text }
^^^^^^^^^^^^^^^^^^^^^^^^ Pass `&:text` as an argument to `mail` instead of a block.
RUBY
expect_correction(<<~RUBY)
mail(
to: 'foo',
subject: 'bar', &:text
)
RUBY
end
context 'numblocks', :ruby27 do
%w[reject select].each do |method|
it "registers an offense when receiver is an array literal and using `#{method}` with a numblock" do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method} { _1.foo }
_{method} ^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{method}(&:foo)
RUBY
end
it "registers an offense when receiver is some value and using `#{method}` with a numblock" do
expect_offense(<<~RUBY, method: method)
do_something.%{method} { _1.foo }
_{method} ^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
do_something.#{method}(&:foo)
RUBY
end
it "does not register an offense when receiver is a hash literal and using `#{method}` with a numblock" do
expect_no_offenses(<<~RUBY)
{foo: 42}.#{method} { _1.foo }
RUBY
end
end
%w[min max].each do |method|
it "registers an offense when receiver is a hash literal and using `#{method}` with a numblock" do
expect_offense(<<~RUBY, method: method)
{foo: 42}.%{method} { _1.foo }
_{method} ^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
{foo: 42}.#{method}(&:foo)
RUBY
end
it "does not register an offense when receiver is an array literal and using `#{method}` with a numblock" do
expect_no_offenses(<<~RUBY)
[1, 2, 3].#{method} { _1.foo }
RUBY
end
end
it 'registers an offense for a block with a numbered parameter' do
expect_offense(<<~RUBY)
something { _1.foo }
^^^^^^^^^^ Pass `&:foo` as an argument to `something` instead of a block.
RUBY
expect_correction(<<~RUBY)
something(&:foo)
RUBY
end
it 'accepts block with multiple numbered parameters' do
expect_no_offenses('something { _1 + _2 }')
end
end
context 'itblocks', :ruby34 do
%w[reject select].each do |method|
it "registers an offense when receiver is an array literal and using `#{method}` with a itblock" do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method} { it.foo }
_{method} ^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{method}(&:foo)
RUBY
end
it "registers an offense when receiver is some value and using `#{method}` with a itblock" do
expect_offense(<<~RUBY, method: method)
do_something.%{method} { it.foo }
_{method} ^^^^^^^^^^ Pass `&:foo` as an argument to `#{method}` instead of a block.
RUBY
expect_correction(<<~RUBY)
do_something.#{method}(&:foo)
RUBY
end
it "does not register an offense when receiver is a hash literal and using `#{method}` with a itblock" do
expect_no_offenses(<<~RUBY)
{foo: 42}.#{method} { it.foo }
RUBY
end
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => true })
end
it 'accepts lambda with 1 numbered parameter' do
expect_no_offenses('-> { _1.method }')
end
it 'accepts proc with 1 numbered parameter' do
expect_no_offenses('proc { _1.method }')
end
it 'accepts block with only second numbered parameter' do
expect_no_offenses('something { _2.first }')
end
it 'accepts Proc.new with 1 numbered parameter' do
expect_no_offenses('Proc.new { _1.method }')
end
it 'accepts ::Proc.new with 1 numbered parameter' do
expect_no_offenses('::Proc.new { _1.method }')
end
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: false`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => false })
end
it 'registers lambda with 1 numbered parameter' do
expect_offense(<<~RUBY)
-> { _1.method }
^^^^^^^^^^^^^ Pass `&:method` as an argument to `lambda` instead of a block.
RUBY
expect_correction(<<~RUBY)
lambda(&:method)
RUBY
end
it 'registers proc with 1 numbered parameter' do
expect_offense(<<~RUBY)
proc { _1.method }
^^^^^^^^^^^^^ Pass `&:method` as an argument to `proc` instead of a block.
RUBY
expect_correction(<<~RUBY)
proc(&:method)
RUBY
end
it 'does not register block with only second numbered parameter' do
expect_no_offenses(<<~RUBY)
something { _2.first }
RUBY
end
it 'registers Proc.new with 1 numbered parameter' do
expect_offense(<<~RUBY)
Proc.new { _1.method }
^^^^^^^^^^^^^ Pass `&:method` as an argument to `new` instead of a block.
RUBY
expect_correction(<<~RUBY)
Proc.new(&:method)
RUBY
end
it 'registers ::Proc.new with 1 numbered parameter' do
expect_offense(<<~RUBY)
::Proc.new { _1.method }
^^^^^^^^^^^^^ Pass `&:method` as an argument to `new` instead of a block.
RUBY
expect_correction(<<~RUBY)
::Proc.new(&:method)
RUBY
end
end
context 'AllowComments: true' do
let(:cop_config) { { 'AllowComments' => true } }
it 'accepts blocks containing comments' do
expect_no_offenses(<<~RUBY)
something do
# comment
_1.upcase
end
RUBY
expect_no_offenses(<<~RUBY)
something do
_1.upcase # comment
end
RUBY
expect_no_offenses(<<~RUBY)
something
something do
# comment
_1.upcase
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/concat_array_literals_spec.rb | spec/rubocop/cop/style/concat_array_literals_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ConcatArrayLiterals, :config do
it 'registers an offense when using `concat` with single element array literal argument' do
expect_offense(<<~RUBY)
arr.concat([item])
^^^^^^^^^^^^^^ Use `push(item)` instead of `concat([item])`.
RUBY
expect_correction(<<~RUBY)
arr.push(item)
RUBY
end
it 'registers an offense when using safe navigation `concat` with single element array literal argument' do
expect_offense(<<~RUBY)
arr&.concat([item])
^^^^^^^^^^^^^^ Use `push(item)` instead of `concat([item])`.
RUBY
expect_correction(<<~RUBY)
arr&.push(item)
RUBY
end
it 'registers an offense when using `concat` with multiple elements array literal argument' do
expect_offense(<<~RUBY)
arr.concat([foo, bar])
^^^^^^^^^^^^^^^^^^ Use `push(foo, bar)` instead of `concat([foo, bar])`.
RUBY
expect_correction(<<~RUBY)
arr.push(foo, bar)
RUBY
end
it 'registers an offense when using `concat` with multiline multiple elements array literal argument' do
expect_offense(<<~RUBY)
arr.concat([
^^^^^^^^ Use `push(foo, bar)` instead of `concat([[...]
foo,
bar
])
RUBY
expect_correction(<<~RUBY)
arr.push(
foo,
bar
)
RUBY
end
it 'registers an offense when using `concat` with multiple array literal arguments' do
expect_offense(<<~RUBY)
arr.concat([foo, bar], [baz])
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `push(foo, bar, baz)` instead of `concat([foo, bar], [baz])`.
RUBY
expect_correction(<<~RUBY)
arr.push(foo, bar, baz)
RUBY
end
it 'registers an offense when using `concat` with single element `%i` array literal argument' do
expect_offense(<<~RUBY)
arr.concat(%i[item])
^^^^^^^^^^^^^^^^ Use `push(:item)` instead of `concat(%i[item])`.
RUBY
expect_correction(<<~RUBY)
arr.push(:item)
RUBY
end
it 'registers an offense when using `concat` with `%I` array literal argument consisting of non basic literals' do
expect_offense(<<~RUBY)
arr.concat(%I[item \#{foo}])
^^^^^^^^^^^^^^^^^^^^^^^ Use `push` with elements as arguments without array brackets instead of `concat(%I[item \#{foo}])`.
RUBY
expect_no_corrections
end
it 'registers an offense when using `concat` with `%W` array literal argument consisting of non basic literals' do
expect_offense(<<~RUBY)
arr.concat(%W[item \#{foo}])
^^^^^^^^^^^^^^^^^^^^^^^ Use `push` with elements as arguments without array brackets instead of `concat(%W[item \#{foo}])`.
RUBY
expect_no_corrections
end
it 'registers an offense when using `concat` with single element `%w` array literal argument' do
expect_offense(<<~RUBY)
arr.concat(%w[item])
^^^^^^^^^^^^^^^^ Use `push("item")` instead of `concat(%w[item])`.
RUBY
expect_correction(<<~RUBY)
arr.push("item")
RUBY
end
it 'does not register an offense when using `concat` with variable argument' do
expect_no_offenses(<<~RUBY)
arr.concat(items)
RUBY
end
it 'does not register an offense when using `concat` with array literal and variable arguments' do
expect_no_offenses(<<~RUBY)
arr.concat([foo, bar], baz)
RUBY
end
it 'does not register an offense when using `concat` with no arguments' do
expect_no_offenses(<<~RUBY)
arr.concat
RUBY
end
it 'does not register an offense when using `push`' do
expect_no_offenses(<<~RUBY)
arr.push(item)
RUBY
end
it 'does not register an offense when using `<<`' do
expect_no_offenses(<<~RUBY)
arr << item
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/ascii_comments_spec.rb | spec/rubocop/cop/style/ascii_comments_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::AsciiComments, :config do
it 'registers an offense for a comment with non-ascii chars' do
expect_offense(<<~RUBY)
# 这是什么?
^^^^^ Use only ascii symbols in comments.
RUBY
end
it 'registers an offense for comments with mixed chars' do
expect_offense(<<~RUBY)
# foo ∂ bar
^ Use only ascii symbols in comments.
RUBY
end
it 'accepts comments with only ascii chars' do
expect_no_offenses('# AZaz1@$%~,;*_`|')
end
context 'when certain non-ascii chars are allowed' do
let(:cop_config) { { 'AllowedChars' => ['∂'] } }
it 'accepts comment with allowed non-ascii chars' do
expect_no_offenses('# foo ∂ bar')
end
it 'registers an offense for comments with non-allowed non-ascii chars' do
expect_offense(<<~RUBY)
# 这是什么?
^^^^^ Use only ascii symbols in comments.
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/in_pattern_then_spec.rb | spec/rubocop/cop/style/in_pattern_then_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::InPatternThen, :config do
context '>= Ruby 2.7', :ruby27 do
it 'registers an offense for `in b;`' do
expect_offense(<<~RUBY)
case a
in b; c
^ Do not use `in b;`. Use `in b then` instead.
end
RUBY
expect_correction(<<~RUBY)
case a
in b then c
end
RUBY
end
it 'registers an offense for `in b, c, d;` (array pattern)' do
expect_offense(<<~RUBY)
case a
in b, c, d; e
^ Do not use `in b, c, d;`. Use `in b, c, d then` instead.
end
RUBY
expect_correction(<<~RUBY)
case a
in b, c, d then e
end
RUBY
end
it 'registers an offense for `in 0 | 1 | 2;` (alternative pattern)' do
expect_offense(<<~RUBY)
case a
in 0 | 1 | 2; x
^ Do not use `in 0 | 1 | 2;`. Use `in 0 | 1 | 2 then` instead.
end
RUBY
expect_correction(<<~RUBY)
case a
in 0 | 1 | 2 then x
end
RUBY
end
it 'registers an offense for `in 0 | 1 | 2 | 3;` (alternative pattern)' do
expect_offense(<<~RUBY)
case a
in 0 | 1 | 2 | 3; x
^ Do not use `in 0 | 1 | 2 | 3;`. Use `in 0 | 1 | 2 | 3 then` instead.
end
RUBY
expect_correction(<<~RUBY)
case a
in 0 | 1 | 2 | 3 then x
end
RUBY
end
it 'registers an offense for `in 0, 1 | 2;`' do
expect_offense(<<~RUBY)
case a
in 0, 1 | 2; x
^ Do not use `in 0, 1 | 2;`. Use `in 0, 1 | 2 then` instead.
end
RUBY
expect_correction(<<~RUBY)
case a
in 0, 1 | 2 then x
end
RUBY
end
it 'accepts `;` separating statements in the body of `in`' do
expect_no_offenses(<<~RUBY)
case a
in b then c; d
end
case e
in f
g; h
end
RUBY
end
context 'when inspecting a case statement with an empty branch' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
case condition
in pattern
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/symbol_array_spec.rb | spec/rubocop/cop/style/symbol_array_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SymbolArray, :config do
before do
# Reset data which is shared by all instances of SymbolArray
described_class.largest_brackets = -Float::INFINITY
end
let(:other_cops) do
{
'Style/PercentLiteralDelimiters' => {
'PreferredDelimiters' => {
'default' => '()'
}
}
}
end
context 'when EnforcedStyle is percent' do
let(:cop_config) { { 'MinSize' => 0, 'EnforcedStyle' => 'percent' } }
it 'registers an offense for arrays of symbols' do
expect_offense(<<~RUBY)
[:one, :two, :three]
^^^^^^^^^^^^^^^^^^^^ Use `%i` or `%I` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
%i(one two three)
RUBY
end
it 'autocorrects arrays of one symbol' do
expect_offense(<<~RUBY)
[:one]
^^^^^^ Use `%i` or `%I` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
%i(one)
RUBY
end
it 'autocorrects arrays of symbols with embedded newlines and tabs' do
expect_offense(<<~RUBY, tab: "\t")
[:"%{tab}", :"two
^^^^{tab}^^^^^^^^ Use `%i` or `%I` for an array of symbols.
", :three]
RUBY
expect_correction(<<~'RUBY')
%I(\t two\n three)
RUBY
end
it 'autocorrects arrays of symbols with new line' do
expect_offense(<<~RUBY)
[:one,
^^^^^^ Use `%i` or `%I` for an array of symbols.
:two, :three,
:four]
RUBY
expect_correction(<<~RUBY)
%i(one
two three
four)
RUBY
end
it 'uses %I when appropriate' do
expect_offense(<<~'RUBY')
[:"\t", :"\n", :three]
^^^^^^^^^^^^^^^^^^^^^^ Use `%i` or `%I` for an array of symbols.
RUBY
expect_correction(<<~'RUBY')
%I(\t \n three)
RUBY
end
it 'does not register an offense for array with non-syms' do
expect_no_offenses('[:one, :two, "three"]')
end
it 'does not register an offense for array starting with %i' do
expect_no_offenses('%i(one two three)')
end
it 'does not register an offense for array containing delimiters without spaces' do
expect_no_offenses('%i[zero (one) [two] three[4] five[six] seven(8) nine(ten) ([]) [] ()]')
end
it 'does not register an offense for a percent array with interpolations' do
expect_no_offenses('%I[one_#{two} three #{four}_five six#{seven}eight [nine_#{ten}]]')
end
it 'does not register an offense if symbol contains whitespace' do
expect_no_offenses('[:one, :two, :"space here"]')
end
it 'does not register an offense if a symbol contains unclosed delimiters' do
expect_no_offenses('[:one, :")", :two, :"(", :"]"]')
end
it 'does not register an offense if a symbol contains a delimiter with spaces' do
expect_no_offenses('[:one, :two, :"[ ]", :"( )"]')
end
it 'registers an offense in a non-ambiguous block context' do
expect_offense(<<~RUBY)
foo([:bar, :baz]) { qux }
^^^^^^^^^^^^ Use `%i` or `%I` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
foo(%i(bar baz)) { qux }
RUBY
end
it 'detects right value for MinSize to use for --auto-gen-config' do
expect_offense(<<~RUBY)
[:one, :two, :three]
^^^^^^^^^^^^^^^^^^^^ Use `%i` or `%I` for an array of symbols.
%i(a b c d)
RUBY
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'percent', 'MinSize' => 4)
end
it 'detects when the cop must be disabled to avoid offenses' do
expect_offense(<<~RUBY)
[:one, :two, :three]
^^^^^^^^^^^^^^^^^^^^ Use `%i` or `%I` for an array of symbols.
%i(a b)
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it 'registers an offense for a %i array containing escaped [ ]' do
expect_offense(<<~'RUBY')
%i[one \[ \] two]
^^^^^^^^^^^^^^^^^ Use `[:one, :'[', :']', :two]` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :'[', :']', :two]
RUBY
end
it 'does not register an offense for a %i array containing unescaped [ ]' do
expect_no_offenses(<<~RUBY)
%i(one [ ] two)
RUBY
end
it 'registers an offense for a %i array containing whitespace between brackets' do
expect_offense(<<~'RUBY')
%i[one two \[three\ four\ five\]]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[:one, :two, :'[three four five]']` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :two, :'[three four five]']
RUBY
end
it 'registers an offense for a %i array containing brackets between brackets' do
expect_offense(<<~'RUBY')
%i[one two \[\[\]]
^^^^^^^^^^^^^^^^^^ Use `[:one, :two, :'[[]']` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :two, :'[[]']
RUBY
end
it 'registers an offense for a %i array containing escaped ( )' do
expect_offense(<<~'RUBY')
%i(one \( \) two)
^^^^^^^^^^^^^^^^^ Use `[:one, :'(', :')', :two]` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :'(', :')', :two]
RUBY
end
it 'does not register an offense for a %i array containing unescaped ( )' do
expect_no_offenses(<<~RUBY)
%i[one ( ) two]
RUBY
end
it 'registers an offense for a %i array containing parentheses between parentheses' do
expect_offense(<<~'RUBY')
%i(one two \(\(\))
^^^^^^^^^^^^^^^^^^ Use `[:one, :two, :'(()']` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :two, :'(()']
RUBY
end
it 'registers an offense for a %i array containing whitespace between parentheses' do
expect_offense(<<~'RUBY')
%i(one two \(three\ four\ five\))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[:one, :two, :'(three four five)']` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :two, :'(three four five)']
RUBY
end
context 'when PreferredDelimiters is specified' do
let(:other_cops) do
{
'Style/PercentLiteralDelimiters' => {
'PreferredDelimiters' => {
'default' => '[]'
}
}
}
end
it 'autocorrects an array in multiple lines' do
expect_offense(<<~RUBY)
[
^ Use `%i` or `%I` for an array of symbols.
:foo,
:bar,
:baz
]
RUBY
expect_correction(<<~RUBY)
%i[
foo
bar
baz
]
RUBY
end
it 'autocorrects an array using partial newlines' do
expect_offense(<<~RUBY)
[:foo, :bar, :baz,
^^^^^^^^^^^^^^^^^^ Use `%i` or `%I` for an array of symbols.
:boz, :buz,
:biz]
RUBY
expect_correction(<<~RUBY)
%i[foo bar baz
boz buz
biz]
RUBY
end
it 'autocorrects balanced pairs of delimiters without excessive escaping' do
expect_offense(<<~RUBY)
[:a, :'b[]', :'c[][]']
^^^^^^^^^^^^^^^^^^^^^^ Use `%i` or `%I` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
%i[a b[] c[][]]
RUBY
end
end
end
context 'when EnforcedStyle is brackets' do
let(:cop_config) { { 'EnforcedStyle' => 'brackets', 'MinSize' => 0 } }
it 'does not register an offense for arrays of symbols' do
expect_no_offenses('[:one, :two, :three]')
end
it 'registers an offense for array starting with %i' do
expect_offense(<<~RUBY)
%i(one two three)
^^^^^^^^^^^^^^^^^ Use `[:one, :two, :three]` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :two, :three]
RUBY
end
it 'registers an offense for empty array starting with %i' do
expect_offense(<<~RUBY)
%i()
^^^^ Use `[]` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[]
RUBY
end
it 'autocorrects an array starting with %i' do
expect_offense(<<~RUBY)
%i(one @two $three four-five)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[:one, :@two, :$three, :'four-five']` for an array of symbols.
RUBY
expect_correction(<<~RUBY)
[:one, :@two, :$three, :'four-five']
RUBY
end
it 'autocorrects multiline %i array' do
expect_offense(<<~RUBY)
%i(
^^^ Use an array literal `[...]` for an array of symbols.
one
two
three
)
RUBY
expect_correction(<<~RUBY)
[
:one,
:two,
:three
]
RUBY
end
it 'autocorrects an array has interpolations' do
expect_offense(<<~'RUBY')
%I(#{foo} #{foo}bar foo#{bar} foo)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[:"#{foo}", :"#{foo}bar", :"foo#{bar}", :foo]` for an array of symbols.
RUBY
expect_correction(<<~'RUBY')
[:"#{foo}", :"#{foo}bar", :"foo#{bar}", :foo]
RUBY
end
end
context 'with non-default MinSize' do
let(:cop_config) { { 'MinSize' => 2, 'EnforcedStyle' => 'percent' } }
it 'does not autocorrect array of one symbol if MinSize > 1' do
expect_no_offenses('[:one]')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/begin_block_spec.rb | spec/rubocop/cop/style/begin_block_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::BeginBlock, :config do
it 'reports an offense for a BEGIN block' do
expect_offense(<<~RUBY)
BEGIN { test }
^^^^^ Avoid the use of `BEGIN` blocks.
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/document_dynamic_eval_definition_spec.rb | spec/rubocop/cop/style/document_dynamic_eval_definition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DocumentDynamicEvalDefinition, :config do
it 'registers an offense when using eval-type method with string interpolation without comment docs' do
expect_offense(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
^^^^^^^^^^ Add a comment block showing its appearance if interpolated.
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
RUBY
end
it 'does not register an offense when using eval-type method without string interpolation' do
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
def capitalize(*params, &block)
to_str.capitalize(*params, &block)
end
EOT
RUBY
end
it 'does not register an offense when using eval-type method with string interpolation with comment docs' do
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
def \#{unsafe_method}(*params, &block) # def capitalize(*params, &block)
to_str.\#{unsafe_method}(*params, &block) # to_str.capitalize(*params, &block)
end # end
EOT
RUBY
end
it 'registers an offense when using eval-type method with interpolated string ' \
'that is not heredoc without comment doc' do
expect_offense(<<~'RUBY')
stringio.instance_eval("def original_filename; 'stringio#{n}.txt'; end")
^^^^^^^^^^^^^ Add a comment block showing its appearance if interpolated.
RUBY
end
it 'does not register an offense when using eval-type method with interpolated string ' \
'that is not heredoc with comment doc' do
expect_no_offenses(<<~'RUBY')
stringio.instance_eval("def original_filename; 'stringio#{n}.txt'; end # def original_filename; 'stringiofoo.txt'; end")
RUBY
end
context 'block comment in heredoc' do
it 'does not register an offense for a matching block comment' do
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
RUBY
end
it 'does not evaluate comments if there is no interpolation' do
expect(cop).not_to receive(:comment_block_docs?)
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
def capitalize(*params, &block)
to_str.capitalize(*params, &block)
end
EOT
RUBY
end
it 'does not register an offense when using inline comments' do
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block) # { note: etc. }
end
EOT
RUBY
end
it 'does not register an offense when using other text' do
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
# EXAMPLE: def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
RUBY
end
it 'does not register an offense when using multiple methods' do
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
#
# def capitalize!(*params)
# @dirty = true
# super
# end
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
def \#{unsafe_method}!(*params)
@dirty = true
super
end
EOT
RUBY
end
it 'does not register an offense when using multiple methods with split comments' do
expect_no_offenses(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
# def capitalize!(*params)
# @dirty = true
# super
# end
def \#{unsafe_method}!(*params)
@dirty = true
super
end
EOT
RUBY
end
it 'registers an offense if the comment does not match the method' do
expect_offense(<<~RUBY)
class_eval <<-EOT, __FILE__, __LINE__ + 1
^^^^^^^^^^ Add a comment block showing its appearance if interpolated.
# def capitalize(*params, &block)
# str.capitalize(*params, &block)
# end
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
RUBY
end
end
context 'block comment outside heredoc' do
it 'does not register an offense for a matching block comment before the heredoc' do
expect_no_offenses(<<~RUBY)
class_eval(
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
<<-EOT, __FILE__, __LINE__ + 1
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
)
RUBY
end
it 'does not register an offense for a matching block comment after the heredoc' do
expect_no_offenses(<<~RUBY)
class_eval(
<<-EOT, __FILE__, __LINE__ + 1
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
)
RUBY
end
it 'does not register an offense when using inline comments' do
expect_no_offenses(<<~RUBY)
class_eval(
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
<<-EOT, __FILE__, __LINE__ + 1
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block) # { note: etc. }
end
EOT
)
RUBY
end
it 'does not register an offense when using other text' do
expect_no_offenses(<<~RUBY)
class_eval(
# EXAMPLE: def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
<<-EOT, __FILE__, __LINE__ + 1
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
)
RUBY
end
it 'registers an offense if the comment does not match the method' do
expect_offense(<<~RUBY)
class_eval(
^^^^^^^^^^ Add a comment block showing its appearance if interpolated.
# def capitalize(*params, &block)
# str.capitalize(*params, &block)
# end
<<-EOT, __FILE__, __LINE__ + 1
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
EOT
)
RUBY
end
it 'does not register an offense when using multiple methods' do
expect_no_offenses(<<~RUBY)
class_eval(
# def capitalize(*params, &block)
# to_str.capitalize(*params, &block)
# end
#
# def capitalize!(*params)
# @dirty = true
# super
# end
<<-EOT, __FILE__, __LINE__ + 1
def \#{unsafe_method}(*params, &block)
to_str.\#{unsafe_method}(*params, &block)
end
def \#{unsafe_method}!(*params)
@dirty = true
super
end
EOT
)
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/multiline_when_then_spec.rb | spec/rubocop/cop/style/multiline_when_then_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineWhenThen, :config do
it 'registers an offense for empty when statement with then' do
expect_offense(<<~RUBY)
case foo
when bar then
^^^^ Do not use `then` for multiline `when` statement.
end
RUBY
expect_correction(<<~RUBY)
case foo
when bar
end
RUBY
end
it 'registers an offense for multiline (one line in a body) when statement with then' do
expect_offense(<<~RUBY)
case foo
when bar then
^^^^ Do not use `then` for multiline `when` statement.
do_something
end
RUBY
expect_correction(<<~RUBY)
case foo
when bar
do_something
end
RUBY
end
it 'registers an offense for multiline (two lines in a body) when statement with then' do
expect_offense(<<~RUBY)
case foo
when bar then
^^^^ Do not use `then` for multiline `when` statement.
do_something1
do_something2
end
RUBY
expect_correction(<<~RUBY)
case foo
when bar
do_something1
do_something2
end
RUBY
end
it "doesn't register an offense for singleline when statement with then" do
expect_no_offenses(<<~RUBY)
case foo
when bar then do_something
end
RUBY
end
it "doesn't register an offense when `then` required for a body of `when` is used" do
expect_no_offenses(<<~RUBY)
case cond
when foo then do_something(arg1,
arg2)
end
RUBY
end
it "doesn't register an offense for multiline when statement" \
'with then followed by other lines' do
expect_no_offenses(<<~RUBY)
case foo
when bar then do_something
do_another_thing
end
RUBY
end
it "doesn't register an offense for empty when statement without then" do
expect_no_offenses(<<~RUBY)
case foo
when bar
end
RUBY
end
it "doesn't register an offense for multiline when statement without then" do
expect_no_offenses(<<~RUBY)
case foo
when bar
do_something
end
RUBY
end
it 'does not register an offense for hash when statement with then' do
expect_no_offenses(<<~RUBY)
case condition
when foo then {
key: 'value'
}
end
RUBY
end
it 'does not register an offense for array when statement with then' do
expect_no_offenses(<<~RUBY)
case condition
when foo then [
'element'
]
end
RUBY
end
it 'autocorrects when the body of `when` branch starts with `then`' do
expect_offense(<<~RUBY)
case foo
when bar
then do_something
^^^^ Do not use `then` for multiline `when` statement.
end
RUBY
expect_correction(<<~RUBY)
case foo
when bar
do_something
end
RUBY
end
it 'registers an offense when one line for multiple candidate values of `when`' do
expect_offense(<<~RUBY)
case foo
when bar, baz then
^^^^ Do not use `then` for multiline `when` statement.
end
RUBY
expect_correction(<<~RUBY)
case foo
when bar, baz
end
RUBY
end
it 'does not register an offense when line break for multiple candidate values of `when`' do
expect_no_offenses(<<~RUBY)
case foo
when bar,
baz then do_something
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/map_compact_with_conditional_block_spec.rb | spec/rubocop/cop/style/map_compact_with_conditional_block_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MapCompactWithConditionalBlock, :config do
context 'With multiline block' do
it 'registers an offense and corrects to `select` with `if` condition' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
if item.bar?
item
else
next
end
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with `if` condition when using `filter_map`' do
expect_offense(<<~RUBY)
foo.filter_map do |item|
^^^^^^^^^^^^^^^^^^^^ Replace `filter_map { ... }` with `select`.
if item.bar?
item
else
next
end
end
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with `if` condition when using `filter_map` with redundant `compact`' do
expect_offense(<<~RUBY)
foo.filter_map do |item|
^^^^^^^^^^^^^^^^^^^^ Replace `filter_map { ... }.compact` with `select`.
if item.bar?
item
else
next
end
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to safe navigation `select` call with `if` condition' do
expect_offense(<<~RUBY)
foo&.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
if item.bar?
item
else
next
end
end&.compact
RUBY
expect_correction <<~RUBY
foo&.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with multi-line `if` condition' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
if item.bar? &&
bar.baz
item
else
next
end
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? &&
bar.baz }
RUBY
end
it 'registers an offense and corrects to `select` if `next value` in if_branch and `nil` in else_branch' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
if item.bar?
next item
else
nil
end
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with `if` condition' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
if item.bar?
next
else
item
end
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` if `next value` in else_branch and `nil` in if_branch' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
if item.bar?
nil
else
next item
end
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with ternary expression' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
item.bar? ? item : next
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with ternary expression' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
item.bar? ? next : item
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with modifier form of `if` condition' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
item if item.bar?
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with modifier form of `unless` condition' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
item unless item.bar?
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with guard clause of `if`' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
next if item.bar?
item
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with guard clause of `unless`' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
next unless item.bar?
item
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with guard clause of `if` and `next` has a value' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
next item if item.bar?
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with guard clause of `unless` and `next` has a value' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
next item unless item.bar?
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with guard clause of `if` and `next` has a value and return nil' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
next item if item.bar?
nil
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with guard clause of `unless` and `next` has a value and return nil' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
next item unless item.bar?
nil
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with guard clause of `if` and next explicitly nil' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
next nil if item.bar?
item
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with guard clause of `unless` and `next` explicitly nil' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
next nil unless item.bar?
item
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` if condition has not else branch' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
if item.bar?
item
end
end.compact
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with `unless` condition' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
unless item.bar?
item
end
end.compact
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'does not register offenses if `compact` is not chained to `map`' do
expect_no_offenses(<<~RUBY)
foo.map do |item|
if item.bar?
item
else
next
end
end
RUBY
end
it 'does not register an offense when `map` is used with methods other than `compact`' do
expect_no_offenses(<<~RUBY)
foo.map do |item|
if item.bar?
item
else
next
end
end.do_something
RUBY
end
it 'does not register an offense when using `map` with custom `compact`' do
expect_no_offenses(<<~RUBY)
foo.map do |item|
if item.bar?
item
else
next
end
end.compact(arg)
RUBY
end
it 'does not register offenses if return value is not same as block argument' do
expect_no_offenses(<<~RUBY)
foo.map do |item|
if item.bar?
1
else
2
end
end.compact
RUBY
end
it 'does not register offenses if condition has elsif branch' do
expect_no_offenses(<<~RUBY)
foo.map do |item|
if item.bar?
item
elsif
baz
else
next
end
end.compact
RUBY
end
it 'does not register offenses if there are multiple guard clauses' do
expect_no_offenses(<<~RUBY)
return unless item.bar?
return unless item.baz?
item
RUBY
end
end
context 'With single line block' do
it 'registers an offense and corrects to `select` with ternary expression' do
expect_offense(<<~RUBY)
foo.map { |item| item.bar? ? item : next }.compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with ternary expression' do
expect_offense(<<~RUBY)
foo.map { |item| item.bar? ? next : item }.compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `select` with modifier form of `if` condition' do
expect_offense(<<~RUBY)
foo.map { |item| item if item.bar? }.compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
RUBY
expect_correction <<~RUBY
foo.select { |item| item.bar? }
RUBY
end
it 'registers an offense and corrects to `reject` with modifier form of `unless` condition' do
expect_offense(<<~RUBY)
foo.map { |item| item unless item.bar? }.compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
RUBY
expect_correction <<~RUBY
foo.reject { |item| item.bar? }
RUBY
end
it 'does not register offenses if `compact` is not chained to `map`' do
expect_no_offenses(<<~RUBY)
foo.map { |item| item if item.bar }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_fetch_block_spec.rb | spec/rubocop/cop/style/redundant_fetch_block_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantFetchBlock, :config do
context 'with SafeForConstants: true' do
let(:config) do
RuboCop::Config.new('Style/RedundantFetchBlock' => { 'SafeForConstants' => true })
end
it 'registers an offense and corrects when using `#fetch` with Integer in the block' do
expect_offense(<<~RUBY)
hash.fetch(:key) { 5 }
^^^^^^^^^^^^^^^^^ Use `fetch(:key, 5)` instead of `fetch(:key) { 5 }`.
RUBY
expect_correction(<<~RUBY)
hash.fetch(:key, 5)
RUBY
end
it 'registers an offense and corrects when using `&.fetch` with Integer in the block' do
expect_offense(<<~RUBY)
hash&.fetch(:key) { 5 }
^^^^^^^^^^^^^^^^^ Use `fetch(:key, 5)` instead of `fetch(:key) { 5 }`.
RUBY
expect_correction(<<~RUBY)
hash&.fetch(:key, 5)
RUBY
end
it 'registers an offense and corrects when using `#fetch` with Float in the block' do
expect_offense(<<~RUBY)
hash.fetch(:key) { 2.5 }
^^^^^^^^^^^^^^^^^^^ Use `fetch(:key, 2.5)` instead of `fetch(:key) { 2.5 }`.
RUBY
expect_correction(<<~RUBY)
hash.fetch(:key, 2.5)
RUBY
end
it 'registers an offense and corrects when using `#fetch` with Symbol in the block' do
expect_offense(<<~RUBY)
hash.fetch(:key) { :value }
^^^^^^^^^^^^^^^^^^^^^^ Use `fetch(:key, :value)` instead of `fetch(:key) { :value }`.
RUBY
expect_correction(<<~RUBY)
hash.fetch(:key, :value)
RUBY
end
it 'registers an offense and corrects when using `#fetch` with Rational in the block' do
expect_offense(<<~RUBY)
hash.fetch(:key) { 2.0r }
^^^^^^^^^^^^^^^^^^^^ Use `fetch(:key, 2.0r)` instead of `fetch(:key) { 2.0r }`.
RUBY
expect_correction(<<~RUBY)
hash.fetch(:key, 2.0r)
RUBY
end
it 'registers an offense and corrects when using `#fetch` with Complex in the block' do
expect_offense(<<~RUBY)
hash.fetch(:key) { 1i }
^^^^^^^^^^^^^^^^^^ Use `fetch(:key, 1i)` instead of `fetch(:key) { 1i }`.
RUBY
expect_correction(<<~RUBY)
hash.fetch(:key, 1i)
RUBY
end
it 'registers an offense and corrects when using `#fetch` with empty block' do
expect_offense(<<~RUBY)
hash.fetch(:key) {}
^^^^^^^^^^^^^^ Use `fetch(:key, nil)` instead of `fetch(:key) {}`.
RUBY
expect_correction(<<~RUBY)
hash.fetch(:key, nil)
RUBY
end
it 'registers an offense and corrects when using `#fetch` with constant in the block' do
expect_offense(<<~RUBY)
hash.fetch(:key) { CONSTANT }
^^^^^^^^^^^^^^^^^^^^^^^^ Use `fetch(:key, CONSTANT)` instead of `fetch(:key) { CONSTANT }`.
RUBY
expect_correction(<<~RUBY)
hash.fetch(:key, CONSTANT)
RUBY
end
it 'registers an offense and corrects when using `#fetch` with String in the block and strings are frozen' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
hash.fetch(:key) { 'value' }
^^^^^^^^^^^^^^^^^^^^^^^ Use `fetch(:key, 'value')` instead of `fetch(:key) { 'value' }`.
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
hash.fetch(:key, 'value')
RUBY
end
it 'does not register an offense when using `#fetch` with String in the block and strings are not frozen' do
expect_no_offenses(<<~RUBY)
hash.fetch(:key) { 'value' }
RUBY
end
it 'does not register an offense when using `#fetch` with argument fallback' do
expect_no_offenses(<<~RUBY)
hash.fetch(:key, :value)
RUBY
end
it 'does not register an offense when using `#fetch` with interpolated Symbol in the block' do
expect_no_offenses('hash.fetch(:key) { :"value_#{value}" }')
end
it 'does not register an offense when using `#fetch` with an argument in the block' do
expect_no_offenses('hash.fetch(:key) { |k| "missing-#{k}" }')
end
it 'does not register an offense when using `#fetch` with `Rails.cache`' do
expect_no_offenses(<<~RUBY)
Rails.cache.fetch(:key) { :value }
RUBY
end
end
context 'with SafeForConstants: false' do
let(:config) do
RuboCop::Config.new('Style/RedundantFetchBlock' => { 'SafeForConstants' => false })
end
it 'does not register an offense when using `#fetch` with constant in the block' do
expect_no_offenses(<<~RUBY)
hash.fetch(:key) { CONSTANT }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_self_assignment_spec.rb | spec/rubocop/cop/style/redundant_self_assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantSelfAssignment, :config do
context 'when lhs and receiver are the same' do
it 'registers an offense and corrects when assigning to local variable' do
expect_offense(<<~RUBY)
foo = foo.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
foo.concat(ary)
RUBY
end
it 'registers an offense and corrects when assigning to instance variable' do
expect_offense(<<~RUBY)
@foo = @foo.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
@foo.concat(ary)
RUBY
end
it 'registers an offense and corrects when assigning to class variable' do
expect_offense(<<~RUBY)
@@foo = @@foo.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
@@foo.concat(ary)
RUBY
end
it 'registers an offense and corrects when assigning to global variable' do
expect_offense(<<~RUBY)
$foo = $foo.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
$foo.concat(ary)
RUBY
end
it 'registers an offense and corrects when the rhs uses safe navigation' do
expect_offense(<<~RUBY)
foo = foo&.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
foo&.concat(ary)
RUBY
end
it 'registers an offense and corrects when the rhs receives a block' do
expect_offense(<<~RUBY)
foo = foo.delete_if { true }
^ Redundant self assignment detected. Method `delete_if` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
foo.delete_if { true }
RUBY
end
end
it 'does not register an offense when lhs and receiver are different' do
expect_no_offenses(<<~RUBY)
foo = bar.concat(ary)
RUBY
end
it 'does not register an offense when there is no a receiver' do
expect_no_offenses(<<~RUBY)
foo = concat(ary)
RUBY
end
it 'does not register an offense when assigning to attribute of `self`' do
expect_no_offenses(<<~RUBY)
self.foo = foo.concat(ary)
RUBY
end
it 'does not register an offense when assigning to attribute of `self` with safe navigation' do
expect_no_offenses(<<~RUBY)
self.foo = foo&.concat(ary)
RUBY
end
it 'registers an offense and corrects when assigning to attribute of non `self`' do
expect_offense(<<~RUBY)
other.foo = other.foo.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
other.foo.concat(ary)
RUBY
end
it 'registers an offense and corrects when assigning to attribute of non `self` with safe assignment' do
expect_offense(<<~RUBY)
other.foo = other.foo&.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
other.foo&.concat(ary)
RUBY
end
it 'registers an offense and corrects when assigning to attribute of non `self` with safe assignment chain' do
expect_offense(<<~RUBY)
other&.foo = other&.foo&.concat(ary)
^ Redundant self assignment detected. Method `concat` modifies its receiver in place.
RUBY
expect_correction(<<~RUBY)
other&.foo&.concat(ary)
RUBY
end
it 'does not register an offense when assigning to attribute of `self` the result from other object' do
expect_no_offenses(<<~RUBY)
self.foo = bar.concat(ary)
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/negated_if_spec.rb | spec/rubocop/cop/style/negated_if_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NegatedIf do
subject(:cop) do
config = RuboCop::Config.new(
'Style/NegatedIf' => {
'SupportedStyles' => %w[both prefix postfix],
'EnforcedStyle' => 'both'
}
)
described_class.new(config)
end
describe 'with “both” style' do
it 'registers an offense for if with exclamation point condition' do
expect_offense(<<~RUBY)
if !a_condition
^^^^^^^^^^^^^^^ Favor `unless` over `if` for negative conditions.
some_method
end
some_method if !a_condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `unless` over `if` for negative conditions.
RUBY
expect_correction(<<~RUBY)
unless a_condition
some_method
end
some_method unless a_condition
RUBY
end
it 'registers an offense for if with "not" condition' do
expect_offense(<<~RUBY)
if not a_condition
^^^^^^^^^^^^^^^^^^ Favor `unless` over `if` for negative conditions.
some_method
end
some_method if not a_condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `unless` over `if` for negative conditions.
RUBY
expect_correction(<<~RUBY)
unless a_condition
some_method
end
some_method unless a_condition
RUBY
end
it 'accepts an if/else with negative condition' do
expect_no_offenses(<<~RUBY)
if !a_condition
some_method
else
something_else
end
if not a_condition
some_method
elsif other_condition
something_else
end
RUBY
end
it 'accepts an if where only part of the condition is negated' do
expect_no_offenses(<<~RUBY)
if !condition && another_condition
some_method
end
if not condition or another_condition
some_method
end
some_method if not condition or another_condition
RUBY
end
it 'accepts an if where the condition is doubly negated' do
expect_no_offenses(<<~RUBY)
if !!condition
some_method
end
some_method if !!condition
RUBY
end
it 'is not confused by negated elsif' do
expect_no_offenses(<<~RUBY)
if test.is_a?(String)
3
elsif test.is_a?(Array)
2
elsif !test.nil?
1
end
RUBY
end
it 'autocorrects by replacing parenthesized if not with unless' do
expect_offense(<<~RUBY)
something if (!x.even?)
^^^^^^^^^^^^^^^^^^^^^^^ Favor `unless` over `if` for negative conditions.
RUBY
expect_correction(<<~RUBY)
something unless (x.even?)
RUBY
end
end
describe 'with “prefix” style' do
subject(:cop) do
config = RuboCop::Config.new(
'Style/NegatedIf' => {
'SupportedStyles' => %w[both prefix postfix],
'EnforcedStyle' => 'prefix'
}
)
described_class.new(config)
end
it 'registers an offense for prefix' do
expect_offense(<<~RUBY)
if !foo
^^^^^^^ Favor `unless` over `if` for negative conditions.
end
RUBY
expect_correction(<<~RUBY)
unless foo
end
RUBY
end
it 'does not register an offense for postfix' do
expect_no_offenses('foo if !bar')
end
end
describe 'with “postfix” style' do
subject(:cop) do
config = RuboCop::Config.new(
'Style/NegatedIf' => {
'SupportedStyles' => %w[both prefix postfix],
'EnforcedStyle' => 'postfix'
}
)
described_class.new(config)
end
it 'registers an offense for postfix' do
expect_offense(<<~RUBY)
foo if !bar
^^^^^^^^^^^ Favor `unless` over `if` for negative conditions.
RUBY
expect_correction(<<~RUBY)
foo unless bar
RUBY
end
it 'does not register an offense for prefix' do
expect_no_offenses(<<~RUBY)
if !foo
end
RUBY
end
end
it 'does not blow up for ternary ops' do
expect_no_offenses('a ? b : c')
end
it 'does not blow up on a negated ternary operator' do
expect_no_offenses('!foo.empty? ? :bar : :baz')
end
it 'does not blow up for empty if condition' do
expect_no_offenses(<<~RUBY)
if ()
end
RUBY
end
it 'does not blow up for empty unless condition' do
expect_no_offenses(<<~RUBY)
unless ()
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/ternary_parentheses_spec.rb | spec/rubocop/cop/style/ternary_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TernaryParentheses, :config do
shared_examples 'safe assignment disabled' do |style, message|
let(:cop_config) { { 'EnforcedStyle' => style, 'AllowSafeAssignment' => false } }
it 'registers an offense for parens around assignment' do
expect_offense(<<~RUBY)
foo = (bar = find_bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_no_corrections
end
it 'registers an offense for parens around inner assignment' do
expect_offense(<<~RUBY)
foo = bar = (baz = find_baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_no_corrections
end
it 'registers an offense for parens around outer assignment' do
expect_offense(<<~RUBY)
foo = (bar = baz = find_baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_no_corrections
end
end
context 'when configured to enforce parentheses inclusion' do
let(:cop_config) { { 'EnforcedStyle' => 'require_parentheses' } }
context 'with a simple condition' do
it 'registers an offense for query method in condition' do
expect_offense(<<~RUBY)
foo = bar? ? a : b
^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar?) ? a : b
RUBY
end
it 'registers an offense for yield in condition' do
expect_offense(<<~RUBY)
foo = yield ? a : b
^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (yield) ? a : b
RUBY
end
it 'registers an offense for accessor in condition' do
expect_offense(<<~RUBY)
foo = bar[:baz] ? a : b
^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar[:baz]) ? a : b
RUBY
end
end
context 'with a complex condition' do
it 'registers an offense for arithmetic condition' do
expect_offense(<<~RUBY)
foo = 1 + 1 == 2 ? a : b
^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (1 + 1 == 2) ? a : b
RUBY
end
it 'registers an offense for boolean expression' do
expect_offense(<<~RUBY)
foo = bar && baz ? a : b
^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar && baz) ? a : b
RUBY
end
it 'registers an offense for equality check' do
expect_offense(<<~RUBY)
foo = foo1 == foo2 ? a : b
^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (foo1 == foo2) ? a : b
RUBY
end
it 'registers an offense when calling method on a receiver' do
expect_offense(<<~RUBY)
foo = bar.baz? ? a : b
^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar.baz?) ? a : b
RUBY
end
it 'registers an offense for boolean expression containing parens' do
expect_offense(<<~RUBY)
foo = bar && (baz || bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar && (baz || bar)) ? a : b
RUBY
end
it 'registers an offense for boolean expression using keyword' do
expect_offense(<<~RUBY)
foo = bar or baz ? a : b
^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar or (baz) ? a : b
RUBY
end
it 'registers an offense for negated condition' do
expect_offense(<<~RUBY)
not bar ? a : b
^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
not (bar) ? a : b
RUBY
end
it 'registers an offense for defined? with variable in condition' do
expect_offense(<<~RUBY)
foo = defined?(bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (defined?(bar)) ? a : b
RUBY
end
it 'registers an offense for defined? with method chain in condition' do
expect_offense(<<~RUBY)
foo = defined?(bar.baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (defined?(bar.baz)) ? a : b
RUBY
end
it 'registers an offense for defined? with class method in condition' do
expect_offense(<<~RUBY)
foo = defined?(Bar.baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (defined?(Bar.baz)) ? a : b
RUBY
end
it 'registers an offense for defined? with nested constant in condition' do
expect_offense(<<~RUBY)
foo = defined?(Bar::BAZ) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = (defined?(Bar::BAZ)) ? a : b
RUBY
end
end
context 'with an assignment condition' do
it 'registers an offense for double assignment' do
expect_offense(<<~RUBY)
foo = bar = baz ? a : b
^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar = (baz) ? a : b
RUBY
end
it 'registers an offense for triple assignment' do
expect_offense(<<~RUBY)
foo = bar = baz = find_baz ? a : b
^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar = baz = (find_baz) ? a : b
RUBY
end
it 'registers an offense for double assignment with equality check in condition' do
expect_offense(<<~RUBY)
foo = bar = baz == 1 ? a : b
^^^^^^^^^^^^^^^^ Use parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar = (baz == 1) ? a : b
RUBY
end
it 'accepts safe assignment in condition' do
expect_no_offenses('foo = (bar = baz = find_baz) ? a : b')
end
end
end
context 'when configured to enforce parentheses omission' do
let(:cop_config) { { 'EnforcedStyle' => 'require_no_parentheses' } }
context 'with a simple condition' do
it 'registers an offense for query method in condition' do
expect_offense(<<~RUBY)
foo = (bar?) ? a : b
^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar? ? a : b
RUBY
end
it 'registers an offense for yield in condition' do
expect_offense(<<~RUBY)
foo = (yield) ? a : b
^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = yield ? a : b
RUBY
end
it 'registers an offense for accessor in condition' do
expect_offense(<<~RUBY)
foo = (bar[:baz]) ? a : b
^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar[:baz] ? a : b
RUBY
end
it 'registers an offense for multi-line boolean expression' do
expect_offense(<<~RUBY)
(foo ||
^^^^^^^ Omit parentheses for ternary conditions.
bar) ? a : b
RUBY
expect_correction(<<~RUBY)
foo ||
bar ? a : b
RUBY
end
it 'accepts multi-line boolean expression starting on following line' do
expect_no_offenses(<<~RUBY)
(
foo || bar
) ? a : b
RUBY
end
end
context 'with a complex condition' do
it 'registers an offense for arithmetic expression' do
expect_offense(<<~RUBY)
foo = (1 + 1 == 2) ? a : b
^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = 1 + 1 == 2 ? a : b
RUBY
end
it 'registers an offense for equality check' do
expect_offense(<<~RUBY)
foo = (foo1 == foo2) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = foo1 == foo2 ? a : b
RUBY
end
it 'registers an offense for boolean expression' do
expect_offense(<<~RUBY)
foo = (bar && baz) ? a : b
^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar && baz ? a : b
RUBY
end
it 'registers an offense for query method on object' do
expect_offense(<<~RUBY)
foo = (bar.baz?) ? a : b
^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar.baz? ? a : b
RUBY
end
it 'accepts parens around inner boolean expression' do
expect_no_offenses('foo = bar && (baz || bar) ? a : b')
end
it 'registers an offense for boolean expression using keyword' do
expect_offense(<<~RUBY)
foo = (foo or bar) ? a : b
^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_no_corrections
end
it 'registers an offense for negated condition' do
expect_offense(<<~RUBY)
foo = (not bar) ? a : b
^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_no_corrections
end
it 'registers an offense for defined with variable in condition' do
expect_offense(<<~RUBY)
foo = (defined? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(bar) ? a : b
RUBY
end
it 'registers an offense for defined with method chain in condition' do
expect_offense(<<~RUBY)
foo = (defined? bar.baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(bar.baz) ? a : b
RUBY
end
it 'registers an offense for defined with class method in condition' do
expect_offense(<<~RUBY)
foo = (defined? Bar.baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(Bar.baz) ? a : b
RUBY
end
it 'registers an offense for defined with nested constant in condition' do
expect_offense(<<~RUBY)
foo = (defined? Bar::BAZ) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(Bar::BAZ) ? a : b
RUBY
end
end
# In Ruby 2.7, `match-pattern` node represents one line pattern matching.
#
# $ ruby-parse --27 -e 'foo in bar'
# (match-pattern (send nil :foo) (match-var :bar))
#
context 'with one line pattern matching', :ruby27, unsupported_on: :prism do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
(foo in bar) ? a : b
RUBY
end
end
context 'with one line pattern matching', :ruby30 do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
(foo in bar) ? a : b
RUBY
end
end
context 'with an assignment condition' do
it 'accepts safe assignment' do
expect_no_offenses('foo = (bar = find_bar) ? a : b')
end
it 'accepts safe assignment as part of multiple assignment' do
expect_no_offenses('foo = bar = (baz = find_baz) ? a : b')
end
it 'registers an offense for equality check' do
expect_offense(<<~RUBY)
foo = bar = (baz == 1) ? a : b
^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar = baz == 1 ? a : b
RUBY
end
it 'accepts double safe assignment' do
expect_no_offenses('foo = (bar = baz = find_baz) ? a : b')
end
it_behaves_like 'safe assignment disabled',
'require_no_parentheses',
'Omit parentheses for ternary conditions.'
end
context 'with a parenthesized method call condition' do
it 'registers an offense for defined check' do
expect_offense(<<~RUBY)
foo = (defined?(bar)) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(bar) ? a : b
RUBY
end
it 'registers an offense when calling method with a parameter' do
expect_offense(<<~RUBY)
foo = (baz?(bar)) ? a : b
^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = baz?(bar) ? a : b
RUBY
end
it 'registers an offense calling an operator method with a dot' do
expect_offense(<<~RUBY)
foo = (bar.<(10)) ? 1000 : 2000
^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar.<(10) ? 1000 : 2000
RUBY
end
it 'registers an offense calling an operator method with safe navigation' do
expect_offense(<<~RUBY)
foo = (bar&.<(10)) ? 1000 : 2000
^^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar&.<(10) ? 1000 : 2000
RUBY
end
end
context 'with an unparenthesized method call condition' do
it 'registers an offense for defined check' do
expect_offense(<<~RUBY)
foo = (defined? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(bar) ? a : b
RUBY
end
it 'registers an offense when calling method with a parameter' do
expect_offense(<<~RUBY)
foo = (baz? bar) ? a : b
^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = baz?(bar) ? a : b
RUBY
end
it 'registers an offense calling method with safe navigation' do
expect_offense(<<~RUBY)
foo = (bar&.foo 10) ? 1000 : 2000
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar&.foo(10) ? 1000 : 2000
RUBY
end
context 'when calling method on a receiver' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = (baz.foo? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = baz.foo?(bar) ? a : b
RUBY
end
end
context 'when calling method on a literal receiver' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = ("bar".foo? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = "bar".foo?(bar) ? a : b
RUBY
end
end
context 'when calling method on a constant receiver' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = (Bar.foo? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = Bar.foo?(bar) ? a : b
RUBY
end
end
context 'when calling method with multiple arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = (baz.foo? bar, baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = baz.foo?(bar, baz) ? a : b
RUBY
end
end
context 'when calling an operator method with a dot' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = (bar.< 10) ? 1000 : 2000
^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar.<(10) ? 1000 : 2000
RUBY
end
end
context 'when calling an operator method with save navigation' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = (bar&.< 10) ? 1000 : 2000
^^^^^^^^^^^^^^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar&.<(10) ? 1000 : 2000
RUBY
end
end
end
it 'accepts condition including a range' do
expect_no_offenses('(foo..bar).include?(baz) ? a : b')
end
context 'with no space between the parentheses and question mark' do
it 'registers an offense' do
expect_offense(<<~RUBY)
(foo)? a : b
^^^^^^^^^^^^ Omit parentheses for ternary conditions.
RUBY
expect_correction(<<~RUBY)
foo ? a : b
RUBY
end
end
end
context 'configured for parentheses on complex and there are parens' do
let(:cop_config) { { 'EnforcedStyle' => 'require_parentheses_when_complex' } }
context 'with a simple condition' do
it 'registers an offense for query method in condition' do
expect_offense(<<~RUBY)
foo = (bar?) ? a : b
^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar? ? a : b
RUBY
end
it 'registers an offense for yield in condition' do
expect_offense(<<~RUBY)
foo = (yield) ? a : b
^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = yield ? a : b
RUBY
end
it 'registers an offense for accessor in condition' do
expect_offense(<<~RUBY)
foo = (bar[:baz]) ? a : b
^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar[:baz] ? a : b
RUBY
end
it 'registers an offense with preceding boolean keyword expression' do
expect_offense(<<~RUBY)
foo = bar or (baz) ? a : b
^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar or baz ? a : b
RUBY
end
it 'registers an offense for save navigation' do
expect_offense(<<~RUBY)
foo = (bar&.baz) ? a : b
^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar&.baz ? a : b
RUBY
end
end
context 'with a complex condition' do
it 'registers an offense when calling method on a receiver' do
expect_offense(<<~RUBY)
foo = (bar.baz?) ? a : b
^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar.baz? ? a : b
RUBY
end
it 'accepts boolean expression using keywords' do
expect_no_offenses('foo = (baz or bar) ? a : b')
end
it 'accepts boolean expression' do
expect_no_offenses('foo = (bar && (baz || bar)) ? a : b')
end
it 'registers an offense for defined with variable in condition' do
expect_offense(<<~RUBY)
foo = (defined? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(bar) ? a : b
RUBY
end
it 'registers an offense for defined with method chain in condition' do
expect_offense(<<~RUBY)
foo = (defined? bar.baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(bar.baz) ? a : b
RUBY
end
it 'registers an offense for defined with class method in condition' do
expect_offense(<<~RUBY)
foo = (defined? Bar.baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(Bar.baz) ? a : b
RUBY
end
it 'registers an offense for defined with nested constant in condition' do
expect_offense(<<~RUBY)
foo = (defined? Bar::BAZ) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(Bar::BAZ) ? a : b
RUBY
end
end
context 'with an assignment condition' do
it 'accepts safe assignment' do
expect_no_offenses('foo = (bar = find_bar) ? a : b')
end
it 'accepts safe assignment as part of multiple assignment' do
expect_no_offenses('foo = baz = (bar = find_bar) ? a : b')
end
it 'accepts equality check' do
expect_no_offenses('foo = bar = (bar == 1) ? a : b')
end
it 'accepts safe multiple assignment' do
expect_no_offenses('foo = (bar = baz = find_bar) ? a : b')
end
it_behaves_like 'safe assignment disabled',
'require_parentheses_when_complex',
'Only use parentheses for ternary expressions with complex conditions.'
end
context 'with method call condition' do
it 'registers an offense for defined check' do
expect_offense(<<~RUBY)
foo = (defined? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = defined?(bar) ? a : b
RUBY
end
context 'with accessor in method call parameters' do
it 'registers an offense for array include? without parens' do
expect_offense(<<~RUBY)
(%w(a b).include? params[:t]) ? "ab" : "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
%w(a b).include?(params[:t]) ? "ab" : "c"
RUBY
end
it 'registers an offense for array include? with multiple parameters without parens' do
expect_offense(<<~RUBY)
(%w(a b).include? params[:t], 3) ? "ab" : "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
%w(a b).include?(params[:t], 3) ? "ab" : "c"
RUBY
end
it 'registers an offense for array include? with multiple parameters with parens' do
expect_offense(<<~RUBY)
(%w(a b).include?(params[:t], x)) ? "ab" : "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
%w(a b).include?(params[:t], x) ? "ab" : "c"
RUBY
end
end
context 'without accessor in method call parameters' do
it 'registers an offense for array include? without parens' do
expect_offense(<<~RUBY)
(%w(a b).include? "a") ? "ab" : "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
%w(a b).include?("a") ? "ab" : "c"
RUBY
end
it 'registers an offense for array include? with parens' do
expect_offense(<<~RUBY)
(%w(a b).include?("a")) ? "ab" : "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
%w(a b).include?("a") ? "ab" : "c"
RUBY
end
end
it 'registers an offense when calling method with a parameter' do
expect_offense(<<~RUBY)
foo = (baz? bar) ? a : b
^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = baz?(bar) ? a : b
RUBY
end
it 'registers an offense when calling method on a receiver' do
expect_offense(<<~RUBY)
foo = (baz.foo? bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Only use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = baz.foo?(bar) ? a : b
RUBY
end
end
it 'accepts condition including a range' do
expect_no_offenses('(foo..bar).include?(baz) ? a : b')
end
end
context 'configured for parentheses on complex and there are no parens' do
let(:cop_config) { { 'EnforcedStyle' => 'require_parentheses_when_complex' } }
context 'with complex condition' do
it 'registers an offense for arithmetic and equality check' do
expect_offense(<<~RUBY)
foo = 1 + 1 == 2 ? a : b
^^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (1 + 1 == 2) ? a : b
RUBY
end
it 'registers an offense for boolean expression' do
expect_offense(<<~RUBY)
foo = bar && baz ? a : b
^^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar && baz) ? a : b
RUBY
end
it 'registers an offense for compound boolean expression' do
expect_offense(<<~RUBY)
foo = bar && baz || bar ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar && baz || bar) ? a : b
RUBY
end
it 'registers an offense for boolean expression with inner parens' do
expect_offense(<<~RUBY)
foo = bar && (baz != bar) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar && (baz != bar)) ? a : b
RUBY
end
it 'registers an offense for comparison with method call on receiver' do
expect_offense(<<~RUBY)
foo = 1 < (bar.baz?) ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (1 < (bar.baz?)) ? a : b
RUBY
end
it 'registers an offense comparison with exponentiation' do
expect_offense(<<~RUBY)
foo = 1 <= (bar ** baz) ? a : b
^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (1 <= (bar ** baz)) ? a : b
RUBY
end
it 'registers an offense for comparison with multiplication' do
expect_offense(<<~RUBY)
foo = 1 >= bar * baz ? a : b
^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (1 >= bar * baz) ? a : b
RUBY
end
it 'registers an offense for addition expression' do
expect_offense(<<~RUBY)
foo = bar + baz ? a : b
^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar + baz) ? a : b
RUBY
end
it 'registers an offense for subtraction expression' do
expect_offense(<<~RUBY)
foo = bar - baz ? a : b
^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar - baz) ? a : b
RUBY
end
it 'registers an offense for comparison' do
expect_offense(<<~RUBY)
foo = bar < baz ? a : b
^^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = (bar < baz) ? a : b
RUBY
end
end
context 'with an assignment condition' do
it 'registers an offense for equality check' do
expect_offense(<<~RUBY)
foo = bar = baz == 1 ? a : b
^^^^^^^^^^^^^^^^ Use parentheses for ternary expressions with complex conditions.
RUBY
expect_correction(<<~RUBY)
foo = bar = (baz == 1) ? a : b
RUBY
end
it 'accepts safe assignment' do
expect_no_offenses('foo = (bar = baz == 1) ? a : b')
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/format_string_spec.rb | spec/rubocop/cop/style/format_string_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FormatString, :config do
context 'when enforced style is sprintf' do
let(:cop_config) { { 'EnforcedStyle' => 'sprintf' } }
it 'registers an offense for a string followed by something' do
expect_offense(<<~RUBY)
puts "%d" % 10
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%d", 10)
RUBY
end
it 'registers an offense for something followed by an array' do
expect_offense(<<~RUBY)
puts x % [10, 11]
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf(x, 10, 11)
RUBY
end
it 'registers an offense for String#% with a hash argument' do
expect_offense(<<~RUBY)
puts x % { a: 10, b: 11 }
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf(x, a: 10, b: 11)
RUBY
end
context 'when using a known autocorrectable method that does not convert to an array' do
it 'registers an offense for `to_s`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_s
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%s", a.to_s)
RUBY
end
it 'registers an offense for `to_h`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_h
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%s", a.to_h)
RUBY
end
it 'registers an offense for `to_i`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_i
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%s", a.to_i)
RUBY
end
it 'registers an offense for `to_f`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_f
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%s", a.to_f)
RUBY
end
it 'registers an offense for `to_r`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_r
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%s", a.to_r)
RUBY
end
it 'registers an offense for `to_d`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_d
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%s", a.to_d)
RUBY
end
it 'registers an offense for `to_sym`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_sym
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts sprintf("%s", a.to_sym)
RUBY
end
end
it 'registers an offense for variable argument but does not autocorrect' do
expect_offense(<<~RUBY)
puts "%f" % a
^ Favor `sprintf` over `String#%`.
RUBY
expect_no_corrections
end
it 'registers an offense for variable argument and assignment but does not autocorrect' do
expect_offense(<<~RUBY)
a = something()
puts "%d" % a
^ Favor `sprintf` over `String#%`.
RUBY
expect_no_corrections
end
it 'does not register an offense for numbers' do
expect_no_offenses('puts 10 % 4')
end
it 'does not register an offense for ambiguous cases' do
expect_no_offenses('puts x % Y')
end
it 'works if the first operand contains embedded expressions' do
expect_offense(<<~'RUBY')
puts "#{x * 5} %d #{@test}" % 10
^ Favor `sprintf` over `String#%`.
RUBY
expect_correction(<<~'RUBY')
puts sprintf("#{x * 5} %d #{@test}", 10)
RUBY
end
it 'registers an offense for format' do
expect_offense(<<~RUBY)
format(something, a, b)
^^^^^^ Favor `sprintf` over `format`.
RUBY
expect_correction(<<~RUBY)
sprintf(something, a, b)
RUBY
end
it 'registers an offense for format with 2 arguments' do
expect_offense(<<~RUBY)
format("%X", 123)
^^^^^^ Favor `sprintf` over `format`.
RUBY
expect_correction(<<~RUBY)
sprintf("%X", 123)
RUBY
end
end
context 'when enforced style is format' do
let(:cop_config) { { 'EnforcedStyle' => 'format' } }
it 'registers an offense for a string followed by something' do
expect_offense(<<~RUBY)
puts "%d" % 10
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%d", 10)
RUBY
end
it 'registers an offense for something followed by an array' do
expect_offense(<<~RUBY)
puts x % [10, 11]
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format(x, 10, 11)
RUBY
end
it 'registers an offense for something followed by a hash' do
expect_offense(<<~RUBY)
puts x % { a: 10, b: 11 }
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format(x, a: 10, b: 11)
RUBY
end
context 'when using a known conversion method that does not convert to an array' do
it 'registers an offense for `to_s`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_s
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%s", a.to_s)
RUBY
end
it 'registers an offense for `to_h`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_h
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%s", a.to_h)
RUBY
end
it 'registers an offense for `to_i`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_i
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%s", a.to_i)
RUBY
end
it 'registers an offense for `to_f`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_f
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%s", a.to_f)
RUBY
end
it 'registers an offense for `to_r`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_r
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%s", a.to_r)
RUBY
end
it 'registers an offense for `to_d`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_d
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%s", a.to_d)
RUBY
end
it 'registers an offense for `to_sym`' do
expect_offense(<<~RUBY)
puts "%s" % a.to_sym
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~RUBY)
puts format("%s", a.to_sym)
RUBY
end
end
it 'registers an offense for variable argument but does not autocorrect' do
expect_offense(<<~RUBY)
puts "%f" % a
^ Favor `format` over `String#%`.
RUBY
expect_no_corrections
end
it 'does not register an offense for numbers' do
expect_no_offenses('puts 10 % 4')
end
it 'does not register an offense for ambiguous cases' do
expect_no_offenses('puts x % Y')
end
it 'works if the first operand contains embedded expressions' do
expect_offense(<<~'RUBY')
puts "#{x * 5} %d #{@test}" % 10
^ Favor `format` over `String#%`.
RUBY
expect_correction(<<~'RUBY')
puts format("#{x * 5} %d #{@test}", 10)
RUBY
end
it 'registers an offense for sprintf' do
expect_offense(<<~RUBY)
sprintf(something, a, b)
^^^^^^^ Favor `format` over `sprintf`.
RUBY
expect_correction(<<~RUBY)
format(something, a, b)
RUBY
end
it 'registers an offense for sprintf with 2 arguments' do
expect_offense(<<~RUBY)
sprintf('%020d', 123)
^^^^^^^ Favor `format` over `sprintf`.
RUBY
expect_correction(<<~RUBY)
format('%020d', 123)
RUBY
end
it 'does not autocorrect String#% with variable argument and assignment' do
expect_offense(<<~RUBY)
a = something()
puts "%d" % a
^ Favor `format` over `String#%`.
RUBY
expect_no_corrections
end
end
context 'when enforced style is percent' do
let(:cop_config) { { 'EnforcedStyle' => 'percent' } }
it 'registers an offense for format' do
expect_offense(<<~RUBY)
format(something, a)
^^^^^^ Favor `String#%` over `format`.
RUBY
expect_correction(<<~RUBY)
something % a
RUBY
end
it 'registers an offense for format with 3 arguments' do
expect_offense(<<~RUBY)
format(something, a, b)
^^^^^^ Favor `String#%` over `format`.
RUBY
expect_correction(<<~RUBY)
something % [a, b]
RUBY
end
it 'registers an offense for format with a hash argument' do
expect_offense(<<~RUBY)
format(something, a: 10, b: 11)
^^^^^^ Favor `String#%` over `format`.
RUBY
expect_correction(<<~RUBY)
something % { a: 10, b: 11 }
RUBY
end
it 'registers an offense for sprintf' do
expect_offense(<<~RUBY)
sprintf(something, a)
^^^^^^^ Favor `String#%` over `sprintf`.
RUBY
expect_correction(<<~RUBY)
something % a
RUBY
end
it 'registers an offense and corrects when using sprintf with second argument that uses an operator' do
expect_offense(<<~RUBY)
format(something, a + 42)
^^^^^^ Favor `String#%` over `format`.
RUBY
expect_correction(<<~RUBY)
something % (a + 42)
RUBY
end
it 'registers an offense for sprintf with 3 arguments' do
expect_offense(<<~RUBY)
format("%d %04x", 123, 123)
^^^^^^ Favor `String#%` over `format`.
RUBY
expect_correction(<<~RUBY)
"%d %04x" % [123, 123]
RUBY
end
it 'registers an offense for sprintf with a hash argument' do
expect_offense(<<~RUBY)
sprintf(something, a: 10, b: 11)
^^^^^^^ Favor `String#%` over `sprintf`.
RUBY
expect_correction(<<~RUBY)
something % { a: 10, b: 11 }
RUBY
end
it 'accepts format with 1 argument' do
expect_no_offenses('format :xml')
end
it 'accepts sprintf with 1 argument' do
expect_no_offenses('sprintf :xml')
end
it 'accepts format without arguments' do
expect_no_offenses('format')
end
it 'accepts sprintf without arguments' do
expect_no_offenses('sprintf')
end
it 'accepts String#%' do
expect_no_offenses('puts "%d" % 10')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/date_time_spec.rb | spec/rubocop/cop/style/date_time_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DateTime, :config do
let(:cop_config) { { 'AllowCoercion' => false } }
it 'registers an offense when using DateTime for current time' do
expect_offense(<<~RUBY)
DateTime.now
^^^^^^^^^^^^ Prefer `Time` over `DateTime`.
RUBY
expect_correction(<<~RUBY)
Time.now
RUBY
end
it 'registers an offense when using DateTime for current time with safe navigation operator' do
expect_offense(<<~RUBY)
DateTime&.now
^^^^^^^^^^^^^ Prefer `Time` over `DateTime`.
RUBY
expect_correction(<<~RUBY)
Time&.now
RUBY
end
it 'registers an offense when using ::DateTime for current time' do
expect_offense(<<~RUBY)
::DateTime.now
^^^^^^^^^^^^^^ Prefer `Time` over `DateTime`.
RUBY
expect_correction(<<~RUBY)
::Time.now
RUBY
end
it 'registers an offense when using DateTime for modern date' do
expect_offense(<<~RUBY)
DateTime.iso8601('2016-06-29')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `Time` over `DateTime`.
RUBY
expect_correction(<<~RUBY)
Time.iso8601('2016-06-29')
RUBY
end
it 'does not register an offense when using Time for current time' do
expect_no_offenses('Time.now')
end
it 'does not register an offense when using Date for modern date' do
expect_no_offenses("Date.iso8601('2016-06-29')")
end
it 'does not register an offense when using DateTime for historic date' do
expect_no_offenses("DateTime.iso8601('2016-06-29', Date::ENGLAND)")
end
it 'does not register an offense when using ::DateTime for historic date' do
expect_no_offenses("::DateTime.iso8601('2016-06-29', ::Date::ITALY)")
end
it 'does not register an offense when using DateTime in another namespace' do
expect_no_offenses('Icalendar::Values::DateTime.new(start_at)')
end
describe 'when configured to not allow #to_datetime' do
before { cop_config['AllowCoercion'] = false }
it 'registers an offense' do
expect_offense(<<~RUBY)
thing.to_datetime
^^^^^^^^^^^^^^^^^ Do not use `#to_datetime`.
RUBY
end
it 'registers an offense when using safe navigation operator' do
expect_offense(<<~RUBY)
thing&.to_datetime
^^^^^^^^^^^^^^^^^^ Do not use `#to_datetime`.
RUBY
end
end
describe 'when configured to allow #to_datetime' do
before { cop_config['AllowCoercion'] = true }
it 'does not register an offense' do
expect_no_offenses('thing.to_datetime')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/multiline_in_pattern_then_spec.rb | spec/rubocop/cop/style/multiline_in_pattern_then_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineInPatternThen, :config do
context '>= Ruby 2.7', :ruby27 do
it 'registers an offense for empty `in` statement with `then`' do
expect_offense(<<~RUBY)
case foo
in bar then
^^^^ Do not use `then` for multiline `in` statement.
end
RUBY
expect_correction(<<~RUBY)
case foo
in bar
end
RUBY
end
it 'registers an offense for multiline (one line in a body) `in` statement with `then`' do
expect_offense(<<~RUBY)
case foo
in bar then
^^^^ Do not use `then` for multiline `in` statement.
do_something
end
RUBY
expect_correction(<<~RUBY)
case foo
in bar
do_something
end
RUBY
end
it 'registers an offense for multiline (two lines in a body) `in` statement with `then`' do
expect_offense(<<~RUBY)
case foo
in bar then
^^^^ Do not use `then` for multiline `in` statement.
do_something1
do_something2
end
RUBY
expect_correction(<<~RUBY)
case foo
in bar
do_something1
do_something2
end
RUBY
end
it "doesn't register an offense for singleline `in` statement with `then`" do
expect_no_offenses(<<~RUBY)
case foo
in bar then do_something
end
RUBY
end
it "doesn't register an offense when `then` required for a body of `in` is used" do
expect_no_offenses(<<~RUBY)
case cond
in foo then do_something(arg1,
arg2)
end
RUBY
end
it "doesn't register an offense for multiline `in` statement with `then` followed by other lines" do
expect_no_offenses(<<~RUBY)
case foo
in bar then do_something
do_another_thing
end
RUBY
end
it "doesn't register an offense for empty `in` statement without `then`" do
expect_no_offenses(<<~RUBY)
case foo
in bar
end
RUBY
end
it "doesn't register an offense for multiline `in` statement without `then`" do
expect_no_offenses(<<~RUBY)
case foo
in bar
do_something
end
RUBY
end
it 'does not register an offense for hash `in` statement with `then`' do
expect_no_offenses(<<~RUBY)
case condition
in foo then {
key: 'value'
}
end
RUBY
end
it 'does not register an offense for array `when` statement with `then`' do
expect_no_offenses(<<~RUBY)
case condition
in foo then [
'element'
]
end
RUBY
end
it 'autocorrects when the body of `in` branch starts with `then`' do
expect_offense(<<~RUBY)
case foo
in bar
then do_something
^^^^ Do not use `then` for multiline `in` statement.
end
RUBY
expect_correction(<<~RUBY)
case foo
in bar
do_something
end
RUBY
end
it 'registers an offense when one line for multiple candidate values of `in`' do
expect_offense(<<~RUBY)
case foo
in bar, baz then
^^^^ Do not use `then` for multiline `in` statement.
end
RUBY
expect_correction(<<~RUBY)
case foo
in bar, baz
end
RUBY
end
it 'does not register an offense when line break for multiple candidate values of `in`' do
expect_no_offenses(<<~RUBY)
case foo
in bar,
baz then do_something
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trivial_accessors_spec.rb | spec/rubocop/cop/style/trivial_accessors_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrivialAccessors, :config do
let(:cop_config) { {} }
it 'registers an offense on instance reader' do
expect_offense(<<~RUBY)
class Foo
def foo
^^^ Use `attr_reader` to define trivial reader methods.
@foo
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :foo
end
RUBY
end
it 'registers an offense on instance writer' do
expect_offense(<<~RUBY)
class Foo
def foo=(val)
^^^ Use `attr_writer` to define trivial writer methods.
@foo = val
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_writer :foo
end
RUBY
end
it 'registers an offense on class reader' do
expect_offense(<<~RUBY)
class Foo
def self.foo
^^^ Use `attr_reader` to define trivial reader methods.
@foo
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
class << self
attr_reader :foo
end
end
RUBY
end
it 'registers an offense on class writer' do
expect_offense(<<~RUBY)
class Foo
def self.foo=(val)
^^^ Use `attr_writer` to define trivial writer methods.
@foo = val
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
class << self
attr_writer :foo
end
end
RUBY
end
it 'registers an offense on reader with braces' do
expect_offense(<<~RUBY)
class Foo
def foo()
^^^ Use `attr_reader` to define trivial reader methods.
@foo
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :foo
end
RUBY
end
it 'registers an offense on writer without braces' do
expect_offense(<<~RUBY)
class Foo
def foo= val
^^^ Use `attr_writer` to define trivial writer methods.
@foo = val
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_writer :foo
end
RUBY
end
it 'registers an offense on one-liner reader' do
expect_offense(<<~RUBY)
class Foo
def foo; @foo; end
^^^ Use `attr_reader` to define trivial reader methods.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :foo
end
RUBY
end
it 'registers an offense on one-liner writer' do
expect_offense(<<~RUBY)
class Foo
def foo=(val); @foo=val; end
^^^ Use `attr_writer` to define trivial writer methods.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_writer :foo
end
RUBY
end
it 'does not register an offense on DSL-style writer' do
expect_no_offenses(<<~RUBY)
class Foo
def foo(val)
@foo = val
end
end
RUBY
end
it 'registers an offense on reader with `private`' do
expect_offense(<<~RUBY)
class Foo
private def foo
^^^ Use `attr_reader` to define trivial reader methods.
@foo
end
end
RUBY
expect_no_corrections
end
it 'accepts non-trivial reader' do
expect_no_offenses(<<~RUBY)
class Foo
def test
some_function_call
@test
end
end
RUBY
end
it 'accepts non-trivial writer' do
expect_no_offenses(<<~RUBY)
class Foo
def test(val)
some_function_call(val)
@test = val
log(val)
end
end
RUBY
end
it 'accepts splats' do
expect_no_offenses(<<~RUBY)
class Foo
def splatomatic(*values)
@splatomatic = values
end
end
RUBY
end
it 'accepts blocks' do
expect_no_offenses(<<~RUBY)
class Foo
def something(&block)
@b = block
end
end
RUBY
end
it 'accepts expressions within reader' do
expect_no_offenses(<<~RUBY)
class Foo
def bar
@bar + foo
end
end
RUBY
end
it 'accepts expressions within writer' do
expect_no_offenses(<<~RUBY)
class Foo
def bar(val)
@bar = val + foo
end
end
RUBY
end
it 'accepts an initialize method looking like a writer' do
expect_no_offenses(<<~RUBY)
class Foo
def initialize(value)
@top = value
end
end
RUBY
end
it 'accepts reader with different ivar name' do
expect_no_offenses(<<~RUBY)
class Foo
def foo
@fo
end
end
RUBY
end
it 'accepts writer with different ivar name' do
expect_no_offenses(<<~RUBY)
class Foo
def foo(val)
@fo = val
end
end
RUBY
end
it 'accepts writer in a module' do
expect_no_offenses(<<~RUBY)
module Foo
def bar=(bar)
@bar = bar
end
end
RUBY
end
it 'accepts writer nested within a module' do
expect_no_offenses(<<~RUBY)
module Foo
begin
def bar=(bar)
@bar = bar
end
end
end
RUBY
end
it 'accepts reader nested within a module' do
expect_no_offenses(<<~RUBY)
module Foo
begin
def bar
@bar
end
end
end
RUBY
end
it 'accepts reader using top level' do
expect_no_offenses(<<~RUBY)
def bar
@bar
end
RUBY
end
it 'accepts writer using top level' do
expect_no_offenses(<<~RUBY)
def bar=(bar)
@bar = bar
end
RUBY
end
it 'accepts writer nested within an instance_eval call' do
expect_no_offenses(<<~RUBY)
something.instance_eval do
begin
def bar=(bar)
@bar = bar
end
end
end
RUBY
end
it 'accepts writer nested within an instance_eval numblock call' do
expect_no_offenses(<<~RUBY)
something.instance_eval do
_1
begin
def bar=(bar)
@bar = bar
end
end
end
RUBY
end
it 'accepts reader nested within an instance_eval call' do
expect_no_offenses(<<~RUBY)
something.instance_eval do
begin
def bar
@bar
end
end
end
RUBY
end
it 'flags a reader inside a class, inside an instance_eval call' do
expect_offense(<<~RUBY)
something.instance_eval do
class << @blah
begin
def bar
^^^ Use `attr_reader` to define trivial reader methods.
@bar
end
end
end
end
RUBY
expect_correction(<<~RUBY)
something.instance_eval do
class << @blah
begin
attr_reader :bar
end
end
end
RUBY
end
context 'exact name match disabled' do
let(:cop_config) { { 'ExactNameMatch' => false } }
it 'registers an offense when names mismatch in writer' do
expect_offense(<<~RUBY)
class Foo
def foo=(val)
^^^ Use `attr_writer` to define trivial writer methods.
@f = val
end
end
RUBY
expect_no_corrections
end
it 'registers an offense when names mismatch in reader' do
expect_offense(<<~RUBY)
class Foo
def foo
^^^ Use `attr_reader` to define trivial reader methods.
@f
end
end
RUBY
expect_no_corrections
end
end
context 'disallow predicates' do
let(:cop_config) { { 'AllowPredicates' => false } }
it 'does not accept predicate-like reader' do
expect_offense(<<~RUBY)
class Foo
def foo?
^^^ Use `attr_reader` to define trivial reader methods.
@foo
end
end
RUBY
expect_no_corrections
end
end
context 'allow predicates' do
let(:cop_config) { { 'AllowPredicates' => true } }
it 'accepts predicate-like reader' do
expect_no_offenses(<<~RUBY)
class Foo
def foo?
@foo
end
end
RUBY
end
end
context 'with allowed methods' do
let(:cop_config) { { 'AllowedMethods' => ['to_foo', 'bar='] } }
it 'accepts allowed reader' do
expect_no_offenses(<<~RUBY)
class Foo
def to_foo
@foo
end
end
RUBY
end
it 'accepts allowed writer' do
expect_no_offenses(<<~RUBY)
class Foo
def bar=(bar)
@bar = bar
end
end
RUBY
end
context 'with AllowPredicates: false' do
let(:cop_config) { { 'AllowPredicates' => false, 'AllowedMethods' => ['foo?'] } }
it 'accepts allowed predicate' do
expect_no_offenses(<<~RUBY)
class Foo
def foo?
@foo
end
end
RUBY
end
end
end
context 'with DSL denied' do
let(:cop_config) { { 'AllowDSLWriters' => false } }
it 'registers an offense on DSL-style writer' do
expect_offense(<<~RUBY)
class Foo
def foo(val)
^^^ Use `attr_writer` to define trivial writer methods.
@foo = val
end
end
RUBY
expect_no_corrections
end
end
context 'ignore class methods' do
let(:cop_config) { { 'IgnoreClassMethods' => true } }
it 'accepts class reader' do
expect_no_offenses(<<~RUBY)
class Foo
def self.foo
@foo
end
end
RUBY
end
it 'accepts class writer' do
expect_no_offenses(<<~RUBY)
class Foo
def self.foo(val)
@foo = val
end
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/one_line_conditional_spec.rb | spec/rubocop/cop/style/one_line_conditional_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::OneLineConditional, :config do
let(:config) { RuboCop::Config.new(config_data) }
let(:config_data) { cop_config_data }
let(:cop_config_data) do
{
'Style/OneLineConditional' => {
'AlwaysCorrectToMultiline' => always_correct_to_multiline
}
}
end
context 'when AlwaysCorrectToMultiline is false' do
let(:always_correct_to_multiline) { false }
it 'registers and corrects an offense with ternary operator for if/then/else/end' do
expect_offense(<<~RUBY)
if cond then run else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
cond ? run : dont
RUBY
end
it 'does not register an offense for if/then/else/end with empty else' do
expect_no_offenses('if cond then run else end')
end
it 'registers and corrects an offense with ternary operator for if/then/else/end when ' \
'`then` without body' do
expect_offense(<<~RUBY)
if cond then else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
cond ? nil : dont
RUBY
end
it 'does not register an offense for if/then/end' do
expect_no_offenses('if cond then run end')
end
it 'does not register an offense when using if/then/else/end with multiple expressions in the `then` body' do
expect_no_offenses(<<~RUBY)
if cond then x; y else z end
RUBY
end
it 'registers and corrects an offense with ternary operator for unless/then/else/end' do
expect_offense(<<~RUBY)
unless cond then run else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `unless/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
cond ? dont : run
RUBY
end
it 'registers and corrects an offense with ternary operator for nested if/then/else/end' do
expect_offense(<<~RUBY)
if cond then foo else if cond2; bar else baz end; end
^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
cond ? foo : (if cond2; bar else baz end)
RUBY
end
it 'registers and corrects an offense when the else branch of a ternary operator has multiple expressions' do
expect_offense(<<~RUBY)
if cond; foo; else bar; baz; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond
foo
else
bar; baz
end
RUBY
end
it 'does not register an offense for unless/then/else/end with empty else' do
expect_no_offenses('unless cond then run else end')
end
it 'does not register an offense for unless/then/end' do
expect_no_offenses('unless cond then run end')
end
%w[| ^ & <=> == === =~ > >= < <= << >> + - * / % ** ~ ! != !~ && ||].each do |operator|
it 'registers and corrects an offense with ternary operator and adding parentheses ' \
'when if/then/else/end is preceded by an operator' do
expect_offense(<<~RUBY, operator: operator)
a %{operator} if cond then run else dont end
_{operator} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
a #{operator} (cond ? run : dont)
RUBY
end
end
shared_examples 'if/then/else/end with constructs changing precedence' do |expr|
it 'registers and corrects an offense with ternary operator and adding parentheses inside ' \
"for if/then/else/end with `#{expr}` constructs inside inner branches" do
expect_offense(<<~RUBY, expr: expr)
if %{expr} then %{expr} else %{expr} end
^^^^{expr}^^^^^^^{expr}^^^^^^^{expr}^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
(#{expr}) ? (#{expr}) : (#{expr})
RUBY
end
end
it_behaves_like 'if/then/else/end with constructs changing precedence', 'puts 1'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'defined? :A'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'yield a'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'super b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'not a'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a and b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a or b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a = b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a ? b : c'
it 'registers and corrects an offense with ternary operator and adding parentheses for ' \
'if/then/else/end that contains method calls with unparenthesized arguments' do
expect_offense(<<~RUBY)
if check 1 then run 2 else dont_run 3 end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
(check 1) ? (run 2) : (dont_run 3)
RUBY
end
it 'registers and corrects an offense with ternary operator without adding parentheses for ' \
'if/then/else/end that contains method calls with parenthesized arguments' do
expect_offense(<<~RUBY)
if a(0) then puts(1) else yield(2) end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
a(0) ? puts(1) : yield(2)
RUBY
end
it 'registers and corrects an offense with ternary operator without adding parentheses for ' \
'if/then/else/end that contains unparenthesized operator method calls' do
expect_offense(<<~RUBY)
if 0 + 0 then 1 + 1 else 2 + 2 end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
0 + 0 ? 1 + 1 : 2 + 2
RUBY
end
shared_examples 'if/then/else/end with keyword' do |keyword, options|
it 'registers and corrects an offense with ternary operator when one of the branches of ' \
"if/then/else/end contains `#{keyword}` keyword", *options do
expect_offense(<<~RUBY, keyword: keyword)
if true then %{keyword} else 7 end
^^^^^^^^^^^^^^{keyword}^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
true ? #{keyword} : 7
RUBY
end
end
context 'Ruby <= 3.2', :ruby32, unsupported_on: :prism do
it_behaves_like 'if/then/else/end with keyword', 'retry'
end
it_behaves_like 'if/then/else/end with keyword', 'break', [:ruby32, { unsupported_on: :prism }]
it_behaves_like 'if/then/else/end with keyword', 'self'
it_behaves_like 'if/then/else/end with keyword', 'raise'
it 'registers and corrects an offense with ternary operator when one of the branches of ' \
'if/then/else/end contains `next` keyword' do
expect_offense(<<~RUBY)
map { |line| if line.match(/^\s*#/) || line.strip.empty? then next else line end }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor the ternary operator (`?:`) over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
map { |line| (line.match(/^\s*#/) || line.strip.empty?) ? next : line }
RUBY
end
it 'registers and corrects an offense with multi-line construct for if-then-elsif-then-end' do
expect_offense(<<~RUBY)
if cond1 then run elsif cond2 then maybe end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond1
run
elsif cond2
maybe
end
RUBY
end
it 'registers and corrects an offense with multi-line construct for ' \
'if-then-elsif-then-else-end' do
expect_offense(<<~RUBY)
if cond1 then run elsif cond2 then maybe else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond1
run
elsif cond2
maybe
else
dont
end
RUBY
end
it 'registers and corrects an offense with multi-line construct for ' \
'if-then-elsif-then-elsif-then-else-end' do
expect_offense(<<~RUBY)
if cond1 then run elsif cond2 then maybe elsif cond3 then perhaps else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond1
run
elsif cond2
maybe
elsif cond3
perhaps
else
dont
end
RUBY
end
end
context 'when AlwaysCorrectToMultiline is true' do
let(:always_correct_to_multiline) { true }
it 'registers and corrects an offense with multi-line construct for if/then/else/end' do
expect_offense(<<~RUBY)
if cond then run else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond
run
else
dont
end
RUBY
end
it 'does not register an offense for if/then/else/end with empty else' do
expect_no_offenses('if cond then run else end')
end
it 'registers and corrects an offense with multi-line construct for if/then/else/end when ' \
'`then` without body' do
expect_offense(<<~RUBY)
if cond then else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond
nil
else
dont
end
RUBY
end
it 'does not register an offense for if/then/end' do
expect_no_offenses('if cond then run end')
end
it 'registers and corrects an offense with multi-line construct for unless/then/else/end' do
expect_offense(<<~RUBY)
unless cond then run else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `unless` over single-line `unless/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
unless cond
run
else
dont
end
RUBY
end
it 'registers and corrects an offense with ternary operator for nested if/then/else/end' do
expect_offense(<<~RUBY)
if cond then foo else if cond2; bar else baz end; end
^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond
foo
else
if cond2; bar else baz end
end
RUBY
end
it 'does not register an offense for unless/then/else/end with empty else' do
expect_no_offenses('unless cond then run else end')
end
it 'does not register an offense for unless/then/end' do
expect_no_offenses('unless cond then run end')
end
%w[| ^ & <=> == === =~ > >= < <= << >> + - * / % ** ~ ! != !~ && ||].each do |operator|
it 'registers and corrects an offense with multi-line construct without adding parentheses ' \
'when if/then/else/end is preceded by an operator' do
expect_offense(<<~RUBY, operator: operator)
a %{operator} if cond then run else dont end
_{operator} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
a #{operator} if cond
#{' ' * operator.length} run
#{' ' * operator.length} else
#{' ' * operator.length} dont
#{' ' * operator.length} end
RUBY
end
end
shared_examples 'if/then/else/end with constructs changing precedence' do |expr|
it 'registers and corrects an offense with multi-line construct without adding ' \
"parentheses for if/then/else/end with `#{expr}` constructs inside inner branches" do
expect_offense(<<~RUBY, expr: expr)
if %{expr} then %{expr} else %{expr} end
^^^^{expr}^^^^^^^{expr}^^^^^^^{expr}^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if #{expr}
#{expr}
else
#{expr}
end
RUBY
end
end
it_behaves_like 'if/then/else/end with constructs changing precedence', 'puts 1'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'defined? :A'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'yield a'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'super b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'not a'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a and b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a or b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a = b'
it_behaves_like 'if/then/else/end with constructs changing precedence', 'a ? b : c'
it 'registers and corrects an offense with multi-line construct without adding parentheses ' \
'for if/then/else/end that contains method calls with unparenthesized arguments' do
expect_offense(<<~RUBY)
if check 1 then run 2 else dont_run 3 end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if check 1
run 2
else
dont_run 3
end
RUBY
end
it 'registers and corrects an offense with multi-line construct without adding parentheses for ' \
'if/then/else/end that contains method calls with parenthesized arguments' do
expect_offense(<<~RUBY)
if a(0) then puts(1) else yield(2) end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if a(0)
puts(1)
else
yield(2)
end
RUBY
end
it 'registers and corrects an offense with multi-line construct without adding parentheses for ' \
'if/then/else/end that contains unparenthesized operator method calls' do
expect_offense(<<~RUBY)
if 0 + 0 then 1 + 1 else 2 + 2 end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if 0 + 0
1 + 1
else
2 + 2
end
RUBY
end
shared_examples 'if/then/else/end with keyword' do |keyword, options|
it 'registers and corrects an offense with multi-line construct when one of the branches ' \
"of if/then/else/end contains `#{keyword}` keyword", *options do
expect_offense(<<~RUBY, keyword: keyword)
if true then %{keyword} else 7 end
^^^^^^^^^^^^^^{keyword}^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if true
#{keyword}
else
7
end
RUBY
end
end
context 'Ruby <= 3.2', :ruby32, unsupported_on: :prism do
it_behaves_like 'if/then/else/end with keyword', 'retry'
end
it_behaves_like 'if/then/else/end with keyword', 'break', [:ruby32, { unsupported_on: :prism }]
it_behaves_like 'if/then/else/end with keyword', 'self'
it_behaves_like 'if/then/else/end with keyword', 'raise'
it 'registers and corrects an offense with multi-line construct when one of the branches of ' \
'if/then/else/end contains `next` keyword' do
expect_offense(<<~RUBY)
map { |line| if line.match(/^\s*#/) || line.strip.empty? then next else line end }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
map { |line| if line.match(/^\s*#/) || line.strip.empty?
next
else
line
end }
RUBY
end
it 'registers and corrects an offense with multi-line construct for ' \
'if-then-elsif-then-else-end' do
expect_offense(<<~RUBY)
if cond1 then run elsif cond2 then maybe else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond1
run
elsif cond2
maybe
else
dont
end
RUBY
end
it 'registers and corrects an offense with multi-line construct for ' \
'if-then-elsif-then-elsif-then-else-end' do
expect_offense(<<~RUBY)
if cond1 then run elsif cond2 then maybe elsif cond3 then perhaps else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond1
run
elsif cond2
maybe
elsif cond3
perhaps
else
dont
end
RUBY
end
context 'when IndentationWidth differs from default' do
let(:config_data) { cop_config_data.merge('Layout/IndentationWidth' => { 'Width' => 4 }) }
it 'registers and corrects an offense with multi-line construct for if/then/else/end' do
expect_offense(<<~RUBY)
if cond then run else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor multi-line `if` over single-line `if/then/else/end` constructs.
RUBY
expect_correction(<<~RUBY)
if cond
run
else
dont
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/commented_keyword_spec.rb | spec/rubocop/cop/style/commented_keyword_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CommentedKeyword, :config do
it 'registers an offense and corrects when commenting on the same line as `end`' do
expect_offense(<<~RUBY)
if x
y
end # comment
^^^^^^^^^ Do not place comments on the same line as the `end` keyword.
RUBY
expect_correction(<<~RUBY)
if x
y
end
RUBY
end
it 'registers an offense and corrects when commenting on the same line as `begin`' do
expect_offense(<<~RUBY)
begin # comment
^^^^^^^^^ Do not place comments on the same line as the `begin` keyword.
y
end
RUBY
expect_correction(<<~RUBY)
# comment
begin
y
end
RUBY
end
it 'registers an offense and corrects when commenting on the same line as `class`' do
expect_offense(<<~RUBY)
class X # comment
^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
y
end
RUBY
expect_correction(<<~RUBY)
# comment
class X
y
end
RUBY
end
it 'registers an offense and corrects when commenting on the same line as `module`' do
expect_offense(<<~RUBY)
module X # comment
^^^^^^^^^ Do not place comments on the same line as the `module` keyword.
y
end
RUBY
expect_correction(<<~RUBY)
# comment
module X
y
end
RUBY
end
it 'registers an offense and corrects when commenting on the same line as `def`' do
expect_offense(<<~RUBY)
def x # comment
^^^^^^^^^ Do not place comments on the same line as the `def` keyword.
y
end
RUBY
expect_correction(<<~RUBY)
# comment
def x
y
end
RUBY
end
it 'registers an offense and corrects when commenting on indented keywords' do
expect_offense(<<~RUBY)
module X
class Y # comment
^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
z
end
end
RUBY
expect_correction(<<~RUBY)
module X
# comment
class Y
z
end
end
RUBY
end
it 'registers an offense and corrects when commenting after keyword with spaces' do
expect_offense(<<~RUBY)
def x(a, b) # comment
^^^^^^^^^ Do not place comments on the same line as the `def` keyword.
y
end
RUBY
expect_correction(<<~RUBY)
# comment
def x(a, b)
y
end
RUBY
end
it 'registers an offense and corrects for one-line cases' do
expect_offense(<<~RUBY)
def x; end # comment
^^^^^^^^^ Do not place comments on the same line as the `def` keyword.
RUBY
expect_correction(<<~RUBY)
# comment
def x; end
RUBY
end
it 'does not register an offense if there are no comments after keywords' do
expect_no_offenses(<<~RUBY)
if x
y
end
RUBY
expect_no_offenses(<<~RUBY)
class X
y
end
RUBY
expect_no_offenses(<<~RUBY)
begin
x
end
RUBY
expect_no_offenses(<<~RUBY)
def x
y
end
RUBY
expect_no_offenses(<<~RUBY)
module X
y
end
RUBY
expect_no_offenses(<<~RUBY)
# module Y # trap comment
RUBY
expect_no_offenses(<<~RUBY)
'end' # comment
RUBY
expect_no_offenses(<<~RUBY)
<<-HEREDOC
def # not a comment
HEREDOC
RUBY
end
it 'does not register an offense for certain comments' do
expect_no_offenses(<<~RUBY)
class X # :nodoc:
y
end
RUBY
expect_no_offenses(<<~RUBY)
class X
def y # :yields:
yield
end
end
RUBY
expect_no_offenses(<<~RUBY)
def x # rubocop:disable Metrics/MethodLength
y
end
RUBY
expect_no_offenses(<<~RUBY)
def x # rubocop: disable Metrics/MethodLength
y
end
RUBY
expect_no_offenses(<<~RUBY)
def x # rubocop :todo Metrics/MethodLength
y
end
RUBY
expect_no_offenses(<<~RUBY)
def x # rubocop: todo Metrics/MethodLength
y
end
RUBY
end
it 'does not register an offense if AST contains # symbol' do
expect_no_offenses(<<~RUBY)
def x(y = "#value")
y
end
RUBY
expect_no_offenses(<<~RUBY)
def x(y: "#value")
y
end
RUBY
end
it 'accepts keyword letter sequences that are not keywords' do
expect_no_offenses(<<~RUBY)
options = {
end_buttons: true, # comment
}
RUBY
expect_no_offenses(<<~RUBY)
defined?(SomeModule).should be_nil # comment
RUBY
expect_no_offenses(<<~RUBY)
foo = beginning_statement # comment
RUBY
end
it 'checks a long comment in less than one second' do
Timeout.timeout(1) { expect_no_offenses(<<~RUBY) }
begin
# 13c7722bd7b3c830bea3dfbd89d447979b902335c5e517ffdba6ee091d01a1151a6c6d9609f6733a4a12116dd8bb88a0d20d62691ef3dc648393d492f6506e48e6946508783b94463d118113ae98a540a1dcb376b38751f1af8e95ddc70184b2b4d2f8844bf02de8a956b445d9c9fe886dd15c8a2b2e1c7bd2f3cc67b065f5383dca814898b5ead264adea9a88ed5accb31bd5654e2628e5958fe84bc2c79c12a9897d9b4820a81aac5999bc64c7edbbe592a52bf7c583efb9c26de9a11b42166e6fdbc527541278ff3861f0bd0c4a1c5b21d5e1d116b07def9ef8bb8b8b569b364d44edac389e936c8911541896308a9cb8e45e3406750edd35f6f8e804109042808a255f0f8660218e07c4374786ec5c32c9dab56bc0f7354852cf2acf6846bb6323ee7b488f68fb823b51dd819dc630d06569933839fc26acc4f8004387ff15e44090907dad8b5eef3ed8d0cbd3d03d6dfcf85494f67c61e34f055ef8af86c0244a8a6428168cf92e5fe7cd8215165dac197d944fdce3c71f61d0e83d98ea916bc0b8285c64b8590db7907af0bc302995b3669da2e05c13a8a4ce2bfaf431a43d8c0d719d049f012923e027128ab45e0a72d00e92096d4b5414599068ed665d1baf52fb283aeee06d0f67b35d2e4b766d0f0557d6150170fa9a16fe42af914ff696ab701034fde7bd9d944f0c3c3ccc18020ba902d15365bbf0547aea1b364f7e4153e1f45ebf2737672bf109c0d64e9e58780fe26938b2ec33f2520bb6f7c3815ae8f0ae4a73805f9257f4ff2b467bb15b7867d292705e973577f6d65acbcd8ee2461c8287925dacbf9ff785f41be0806e4927f6eca36a16a54bcfe8b70d327ce7e8b73d692cc709b2a5bd8a785eba39aad42d77f0d3d519cd42503c346826beca9bede8f40dfceca84bdc41842853f20546a56841e4db3063a3cfda7d415896fee52713c21475e05c5339caf63fe7d8fde968ca52e6746dc1716b537af7385cab47ea47a83621488587fe36a4c6d9e6ff0a0e96011393daeaa09ac329f3f7926e1a7837642843ef6af6ceab2d1e2d784942c6f4d520a48eb34db0c4097de5bb530ab9282e61f364ee0866176587ed7c52fc401523123873a4c6844b9ff87193465530da4133bdd1a766ab90da03b38066509b51eb2d115e77dd7808afd8ca352e79ded5c6b62bad51149826bf52b532bb5d688e6ff9c846a1e3d54831fdaf20982a901028f6e921c86628dfd71d4da0b88c99a3f46e69c89714b1f0f39168e0f36b260647cbf4d608ae20518c4268d07c251f9f94a473eb92046eae892b9bd06027d4aa4b70e0252703aab8bffa409ac0ca3742bcf7f18f172a79b7b43c7511f3a4e4084ec173be024ec54e130d74de4dde71efdeb5c9507bf652d89b247d2612b78767684497d34636b4a29a2f0cbdd5f10fefd130917d44c8661cb09869a3fc85a390eb43ff9752cd919da24f437f159a43660fa0ba72a100792b2d742aa2bd24c2561a8170c4af67f1314563e75816b8648c9a6c8801dc7913763bba0b3dccc16e7f7365fb181cddd2cfb1e2c12848782e362c255ec209c4b0bf84908354056ac1609492479d3e56fd1956ab8fa523d100a43b1eab397665155acb714da7342eea81855504189e957d61a9ec7194d6a20e62dd5beaa07360443f34de8ed07fd3a387a411e1e6efeeec202ce3635ebbd87641c8ad1ab2e5862712ca230c0cb5aef8ec8ec6d63bedb8a1cc6e5657de15258e5d81c97a4c736d19b81c14b2a1ec3c0d36b5f670877b99288adf5822b851727dea50469f832783c7a23710003f05bbb24e2a175fc23022180b6d4492ec210a5ef4328de969536619161956815d7cbafb9dc29df6c4b3ea733c41db465e5b47c94ed31f922c2cc07d78d208092f452069c54a80248b8f5ef10f8f72a9a575c38fa2d2ab2b150b85fd34913920780750193c4e3680c4569cbc08b08ba94bb50307b63977469e5794049b5fc28125d5cc53fa3f12b77799e2021ccaff08eada38fca5223ef7dfdb4e037b5986b55f406e00cbb401062ae439adf5b244bbc9b08e6bdd2982562422c853ccfd880ae30b4694aec839ffd0e560473064c96855afd38e5d20dedd391a61
end
RUBY
end
context 'when RBS::Inline annotation is used' do
it 'does not register an offense for RBS::Inline generics annotation' do
expect_no_offenses(<<~RUBY)
class X < Y #[String]
end
class A < B::C #[String]
end
class A < B::C::D #[String]
end
class A::B < C #[String]
end
class A::B::C < D #[String]
end
RUBY
end
it 'registers an offense and corrects for RBS::Inline non generics annotation' do
expect_offense(<<~RUBY)
class X #[String]
^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class X < Y #[String
^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class X < Y #String]
^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class X < Y # String]
^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class X < Y #String ]
^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class A < B::C #String]
^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class A < B::C::D #String]
^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class A::B < C #String]
^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class A::B::C < D #String]
^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
RUBY
expect_correction(<<~RUBY)
#[String]
class X
end
#[String
class X < Y
end
#String]
class X < Y
end
# String]
class X < Y
end
#String ]
class X < Y
end
#String]
class A < B::C
end
#String]
class A < B::C::D
end
#String]
class A::B < C
end
#String]
class A::B::C < D
end
RUBY
end
it 'does not register an offense for RBS::Inline annotation for method definition' do
expect_no_offenses(<<~RUBY)
def x #: String
end
class Y
def y #: String
end
end
RUBY
end
it 'registers an offense and corrects for RBS::Inline annotation for non method definition' do
expect_offense(<<~RUBY)
class X #: String
^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
module Y #: String
^^^^^^^^^ Do not place comments on the same line as the `module` keyword.
end
begin #: String
^^^^^^^^^ Do not place comments on the same line as the `begin` keyword.
end
RUBY
expect_correction(<<~RUBY)
#: String
class X
end
#: String
module Y
end
#: String
begin
end
RUBY
end
it 'does not register an offense for RBS::Inline annotation `#:` for `end` keyword of method' do
expect_no_offenses(<<~RUBY)
def x
end #: String
RUBY
end
it 'does not register an offense for RBS::Inline annotation `#:` for `end` keyword of block' do
expect_no_offenses(<<~RUBY)
def x
doubled_nums = [1, 2, 3].map do |num|
num * 2
end #: Array[Integer]
end
RUBY
end
it 'does not register an offense for RBS::Inline annotation `#:` for `end` keyword of class' do
expect_no_offenses(<<~RUBY)
class X
end #: String
RUBY
end
it 'does not register an offense for RBS::Inline annotation `#:` for `end` keyword of module' do
expect_no_offenses(<<~RUBY)
module X
end #: String
RUBY
end
it 'does not register an offense for RBS::Inline annotation `#:` for `end` keyword of begin' do
expect_no_offenses(<<~RUBY)
begin
end #: String
RUBY
end
end
context 'when Steep annotation is used' do
it 'does not register an offense for `steep:ignore` annotation on the same line as `def`' do
expect_no_offenses(<<~RUBY)
def x # steep:ignore
end
def x # steep:ignore MethodBodyTypeMismatch
end
RUBY
end
it 'does not register an offense for `steep:ignore` annotation on the same line as `end`' do
expect_no_offenses(<<~RUBY)
def x
end # steep:ignore
def x
end # steep:ignore MethodBodyTypeMismatch
RUBY
end
it 'does not register an offense for `steep:ignore` annotation on the same line as `begin`' do
expect_no_offenses(<<~RUBY)
begin # steep:ignore
end
begin # steep:ignore NoMethod
end
RUBY
end
it 'does not register an offense for `steep:ignore` annotation on the same line as `class`' do
expect_no_offenses(<<~RUBY)
class X # steep:ignore
end
class X # steep:ignore UnknownConstant
end
RUBY
end
it 'does not register an offense for `steep:ignore` annotation on the same line as `module`' do
expect_no_offenses(<<~RUBY)
module X # steep:ignore
end
module X # steep:ignore UnknownConstant
end
RUBY
end
it 'registers an offense and corrects for non `steep:ignore` annotation on the same line as `def' do
expect_offense(<<~RUBY)
def x # steep
^^^^^^^ Do not place comments on the same line as the `def` keyword.
end
def x #steep:ignore
^^^^^^^^^^^^^ Do not place comments on the same line as the `def` keyword.
end
def x # steep:ignoreMethodBodyTypeMismatch
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not place comments on the same line as the `def` keyword.
end
RUBY
expect_correction(<<~RUBY)
# steep
def x
end
#steep:ignore
def x
end
# steep:ignoreMethodBodyTypeMismatch
def x
end
RUBY
end
it 'registers an offense and corrects for non `steep:ignore` annotation on the same line as `end' do
expect_offense(<<~RUBY)
def x
end # steep
^^^^^^^ Do not place comments on the same line as the `end` keyword.
def x
end #steep:ignore
^^^^^^^^^^^^^ Do not place comments on the same line as the `end` keyword.
def x
end # steep:ignoreMethodBodyTypeMismatch
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not place comments on the same line as the `end` keyword.
RUBY
expect_correction(<<~RUBY)
def x
end
def x
end
def x
end
RUBY
end
it 'registers an offense and corrects for non `steep:ignore` annotation on the same line as `begin' do
expect_offense(<<~RUBY)
begin # steep
^^^^^^^ Do not place comments on the same line as the `begin` keyword.
end
begin #steep:ignore
^^^^^^^^^^^^^ Do not place comments on the same line as the `begin` keyword.
end
begin # steep:ignoreUnknownConstant
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not place comments on the same line as the `begin` keyword.
end
RUBY
expect_correction(<<~RUBY)
# steep
begin
end
#steep:ignore
begin
end
# steep:ignoreUnknownConstant
begin
end
RUBY
end
it 'registers an offense and corrects for non `steep:ignore` annotation on the same line as `class' do
expect_offense(<<~RUBY)
class X # steep
^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class X #steep:ignore
^^^^^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
class X # steep:ignoreUnknownConstant
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not place comments on the same line as the `class` keyword.
end
RUBY
expect_correction(<<~RUBY)
# steep
class X
end
#steep:ignore
class X
end
# steep:ignoreUnknownConstant
class X
end
RUBY
end
it 'registers an offense and corrects for non `steep:ignore` annotation on the same line as `module' do
expect_offense(<<~RUBY)
module X # steep
^^^^^^^ Do not place comments on the same line as the `module` keyword.
end
module X #steep:ignore
^^^^^^^^^^^^^ Do not place comments on the same line as the `module` keyword.
end
module X # steep:ignoreUnknownConstant
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not place comments on the same line as the `module` keyword.
end
RUBY
expect_correction(<<~RUBY)
# steep
module X
end
#steep:ignore
module X
end
# steep:ignoreUnknownConstant
module X
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/file_empty_spec.rb | spec/rubocop/cop/style/file_empty_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FileEmpty, :config do
context 'target ruby version >= 2.4', :ruby24 do
it 'registers an offense for `File.zero?`' do
expect_offense(<<~RUBY)
File.zero?('path/to/file')
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `!File.zero?`' do
expect_offense(<<~RUBY)
!File.zero?('path/to/file')
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
!File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.zero?` with line break' do
expect_offense(<<~RUBY)
File.
^^^^^ Use `File.empty?('path/to/file')` instead.
zero?('path/to/file')
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `FileTest.zero?`' do
expect_offense(<<~RUBY)
FileTest.zero?('path/to/file')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `FileTest.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
FileTest.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.size == 0`' do
expect_offense(<<~RUBY)
File.size('path/to/file') == 0
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `!File.size == 0`' do
expect_offense(<<~RUBY)
!File.size('path/to/file') == 0
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
!File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.size >= 0`' do
expect_offense(<<~RUBY)
File.size('path/to/file') >= 0
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
!File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `!File.size >= 0`' do
expect_offense(<<~RUBY)
!File.size('path/to/file') >= 0
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.size.zero?`' do
expect_offense(<<~RUBY)
File.size('path/to/file').zero?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.read.empty?`' do
expect_offense(<<~RUBY)
File.read('path/to/file').empty?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.binread.empty?`' do
expect_offense(<<~RUBY)
File.binread('path/to/file').empty?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.read == ""`' do
expect_offense(<<~RUBY)
File.read('path/to/file') == ''
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.binread == ""`' do
expect_offense(<<~RUBY)
File.binread('path/to/file') == ''
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.read != ""`' do
expect_offense(<<~RUBY)
File.read('path/to/file') != ''
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
!File.empty?('path/to/file')
RUBY
end
it 'registers an offense for `File.binread != ""`' do
expect_offense(<<~RUBY)
File.binread('path/to/file') != ''
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.empty?('path/to/file')` instead.
RUBY
expect_correction(<<~RUBY)
!File.empty?('path/to/file')
RUBY
end
it 'does not register an offense for `File.empty?`' do
expect_no_offenses('File.empty?("path/to/file")')
end
it 'does not register an offense for non-offending methods' do
expect_no_offenses('File.exist?("path/to/file")')
end
end
context 'target ruby version < 2.4', :ruby23, unsupported_on: :prism do
it 'does not register an offense for `File.zero?`' do
expect_no_offenses("File.zero?('path/to/file')")
end
it 'does not register an offense for `FileTest.zero?`' do
expect_no_offenses("FileTest.zero?('path/to/file')")
end
it 'does not register an offense for `File.size == 0`' do
expect_no_offenses("File.size('path/to/file') == 0")
end
it 'does not register an offense for `File.size.zero?`' do
expect_no_offenses("File.size('path/to/file').zero?")
end
it 'does not register an offense for `File.read.empty?`' do
expect_no_offenses("File.read('path/to/file').empty?")
end
it 'does not register an offense for `File.binread.empty?`' do
expect_no_offenses("File.binread('path/to/file').empty?")
end
it 'does not register an offense for `File.read == ""`' do
expect_no_offenses("File.read('path/to/file') == ''")
end
it 'does not register an offense for `File.binread == ""`' do
expect_no_offenses("File.binread('path/to/file') == ''")
end
it 'does not register an offense for `File.empty?`' do
expect_no_offenses('File.empty?("path/to/file")')
end
it 'does not register an offense for non-offending methods' do
expect_no_offenses('File.exist?("path/to/file")')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/end_block_spec.rb | spec/rubocop/cop/style/end_block_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EndBlock, :config do
it 'reports an offense and corrects END block' do
expect_offense(<<~RUBY)
END { test }
^^^ Avoid the use of `END` blocks. Use `Kernel#at_exit` instead.
RUBY
expect_correction(<<~RUBY)
at_exit { test }
RUBY
end
it 'does not report offenses for other blocks' do
expect_no_offenses(<<~RUBY)
end_block { test }
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_regexp_constructor_spec.rb | spec/rubocop/cop/style/redundant_regexp_constructor_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantRegexpConstructor, :config do
it 'registers an offense when wrapping `/regexp/` with `Regexp.new`' do
expect_offense(<<~RUBY)
Regexp.new(/regexp/)
^^^^^^^^^^^^^^^^^^^^ Remove the redundant `Regexp.new`.
RUBY
expect_correction(<<~RUBY)
/regexp/
RUBY
end
it 'registers an offense when wrapping `/regexp/` with `::Regexp.new`' do
expect_offense(<<~RUBY)
::Regexp.new(/regexp/)
^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `Regexp.new`.
RUBY
expect_correction(<<~RUBY)
/regexp/
RUBY
end
it 'registers an offense when wrapping `/regexp/i` with `Regexp.new`' do
expect_offense(<<~RUBY)
Regexp.new(/regexp/i)
^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `Regexp.new`.
RUBY
expect_correction(<<~RUBY)
/regexp/i
RUBY
end
it 'registers an offense when wrapping `/\A#{regexp}\z/io` with `Regexp.new`' do
expect_offense(<<~'RUBY')
Regexp.new(/\A#{regexp}\z/io)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `Regexp.new`.
RUBY
expect_correction(<<~'RUBY')
/\A#{regexp}\z/io
RUBY
end
it 'registers an offense when wrapping `/regexp/` with `Regexp.compile`' do
expect_offense(<<~RUBY)
Regexp.compile(/regexp/)
^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `Regexp.compile`.
RUBY
expect_correction(<<~RUBY)
/regexp/
RUBY
end
it 'does not register an offense when wrapping a string literal with `Regexp.new`' do
expect_no_offenses(<<~RUBY)
Regexp.new('regexp')
RUBY
end
it 'does not register an offense when wrapping a string literal with `Regexp.new` with regopt argument' do
expect_no_offenses(<<~RUBY)
Regexp.new('regexp', Regexp::IGNORECASE)
RUBY
end
it 'does not register an offense when wrapping a string literal with `Regexp.new` with piped regopt argument' do
expect_no_offenses(<<~RUBY)
Regexp.new('regexp', Regexp::IGNORECASE | Regexp::IGNORECASE)
RUBY
end
it 'does not register an offense when wrapping a string literal with `Regexp.compile`' do
expect_no_offenses(<<~RUBY)
Regexp.compile('regexp')
RUBY
end
it 'does not register an offense when using a regexp literal' do
expect_no_offenses(<<~RUBY)
/regexp/
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/class_methods_definitions_spec.rb | spec/rubocop/cop/style/class_methods_definitions_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ClassMethodsDefinitions, :config do
context 'when EnforcedStyle is def_self' do
let(:cop_config) { { 'EnforcedStyle' => 'def_self' } }
it 'registers an offense and corrects when defining class methods with `class << self`' do
expect_offense(<<~RUBY)
class A
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
attr_reader :two
def three
end
end
end
RUBY
expect_correction(<<~RUBY)
class A
class << self
attr_reader :two
end
def self.three
end
end
RUBY
end
it 'registers an offense and corrects when defining class methods with `class << self` and ' \
'there is no blank line between method definition and attribute accessor' do
expect_offense(<<~RUBY)
class A
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
def three
end
attr_reader :two
end
end
RUBY
expect_correction(<<~RUBY)
class A
class << self
attr_reader :two
end
def self.three
end
end
RUBY
end
it 'correctly handles methods with annotation comments' do
expect_offense(<<~RUBY)
class A
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
attr_reader :one
# Multiline
# comment.
def two
end
end
end
RUBY
expect_correction(<<~RUBY)
class A
class << self
attr_reader :one
end
# Multiline
# comment.
def self.two
end
end
RUBY
end
it 'correctly handles class << self containing multiple methods' do
expect_offense(<<~RUBY)
class A
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
def one
:one
end
def two
:two
end
end
end
RUBY
expect_correction(<<~RUBY)
class A
def self.one
:one
end
def self.two
:two
end
end
RUBY
end
it 'removes empty class << self when correcting' do
expect_offense(<<~RUBY)
class A
def self.one
end
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
def two
end
def three
end
end
end
RUBY
expect_correction(<<~RUBY)
class A
def self.one
end
def self.two
end
def self.three
end
end
RUBY
end
it 'correctly handles def self.x within class << self' do
expect_offense(<<~RUBY)
class A
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
def self.one
end
def two
end
end
end
RUBY
expect_correction(<<~RUBY)
class A
class << self
def self.one
end
end
def self.two
end
end
RUBY
end
it 'registers and corrects an offense when defining class methods with `class << self` with comment only body' do
expect_offense(<<~RUBY)
class Foo
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
def do_something
# TODO
end
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
def self.do_something
# TODO
end
end
RUBY
end
it 'registers and corrects an offense when defining class methods with `class << self` with inline comment' do
expect_offense(<<~RUBY)
class Foo
class << self
^^^^^^^^^^^^^ Do not define public methods within class << self.
def do_something # TODO
end
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
def self.do_something # TODO
end
end
RUBY
end
it 'does not register an offense when `class << self` contains non public methods' do
expect_no_offenses(<<~RUBY)
class A
class << self
def one
end
private
def two
end
end
end
RUBY
end
it 'does not register an offense when class << self does not contain methods' do
expect_no_offenses(<<~RUBY)
class A
class << self
attr_reader :one
end
end
RUBY
end
it 'does not register an offense when defining class methods with `def self.method`' do
expect_no_offenses(<<~RUBY)
class A
def self.one
end
end
RUBY
end
it 'does not register an offense when defining singleton methods using `self << object`' do
expect_no_offenses(<<~RUBY)
class A
class << not_self
def one
end
end
end
RUBY
end
it 'does not register an offense when class << self contains only class methods' do
expect_no_offenses(<<~RUBY)
class A
class << self
def self.one
end
end
end
RUBY
end
end
context 'when EnforcedStyle is self_class' do
let(:cop_config) { { 'EnforcedStyle' => 'self_class' } }
it 'registers an offense when defining class methods with `def self.method`' do
expect_offense(<<~RUBY)
class A
def self.one
^^^^^^^^^^^^ Use `class << self` to define a class method.
end
end
RUBY
end
it 'does not register an offense when defining class methods with `class << self`' do
expect_no_offenses(<<~RUBY)
class A
class << self
def one
end
end
end
RUBY
end
it 'does not register an offense when defining singleton methods not on self' do
expect_no_offenses(<<~RUBY)
object = Object.new
def object.method
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/parallel_assignment_spec.rb | spec/rubocop/cop/style/parallel_assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ParallelAssignment, :config do
let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 2 }) }
it 'registers an offense when the right side has multiple arrays' do
expect_offense(<<~RUBY)
a, b, c = [1, 2], [3, 4], [5, 6]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = [1, 2]
b = [3, 4]
c = [5, 6]
RUBY
end
it 'registers an offense when the right side has multiple hashes' do
expect_offense(<<~RUBY)
a, b, c = {a: 1}, {b: 2}, {c: 3}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = {a: 1}
b = {b: 2}
c = {c: 3}
RUBY
end
it 'registers an offense when the right side has constants' do
expect_offense(<<~RUBY)
a, b, c = CONSTANT1, CONSTANT2, CONSTANT3
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = CONSTANT1
b = CONSTANT2
c = CONSTANT3
RUBY
end
it 'registers an offense when the right side has mixed expressions' do
expect_offense(<<~RUBY)
a, b, c = [1, 2], {a: 1}, CONSTANT3
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = [1, 2]
b = {a: 1}
c = CONSTANT3
RUBY
end
it 'registers an offense when the right side has methods with/without blocks' do
expect_offense(<<~RUBY)
a, b = foo { |a| puts a }, bar()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = foo { |a| puts a }
b = bar()
RUBY
end
it 'registers an offense when assignments must be reordered to preserve meaning' do
expect_offense(<<~RUBY)
a, b = 1, a
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
b = a
a = 1
RUBY
end
it 'registers an offense when assigning to same variables in same order' do
expect_offense(<<~RUBY)
a, b = a, b
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = a
b = b
RUBY
end
it 'registers an offense when right hand side has maps with blocks' do
expect_offense(<<~RUBY)
a, b = foo.map { |e| e.id }, bar.map { |e| e.id }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = foo.map { |e| e.id }
b = bar.map { |e| e.id }
RUBY
end
it 'registers an offense when left hand side ends with an implicit variable' do
expect_offense(<<~RUBY)
array = [1, 2, 3]
a, b, c, = 8, 9, array
^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
array = [1, 2, 3]
a = 8
b = 9
c = array
RUBY
end
it 'registers an offense when right hand side has namespaced constants' do
expect_offense(<<~RUBY)
a, b = Float::INFINITY, Float::INFINITY
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = Float::INFINITY
b = Float::INFINITY
RUBY
end
it 'registers an offense when assigning to namespaced constants' do
expect_offense(<<~RUBY)
Float::INFINITY, Float::INFINITY = 1, 2
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
Float::INFINITY = 1
Float::INFINITY = 2
RUBY
end
it 'registers an offense with indices' do
expect_offense(<<~RUBY)
a[0], a[1] = a[1], a[2]
^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a[0] = a[1]
a[1] = a[2]
RUBY
end
it 'registers an offense with attributes when assignments must be ' \
'reordered to preserve meaning' do
expect_offense(<<~RUBY)
obj.attr1, obj.attr2 = obj.attr3, obj.attr1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
obj.attr2 = obj.attr1
obj.attr1 = obj.attr3
RUBY
end
it 'registers an offense with indices and attributes when assignments ' \
'must be reordered to preserve meaning' do
expect_offense(<<~RUBY)
obj.attr1, ary[0] = ary[1], obj.attr1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
ary[0] = obj.attr1
obj.attr1 = ary[1]
RUBY
end
it 'registers an offense with indices of different variables' do
expect_offense(<<~RUBY)
a[0], a[1] = a[1], b[0]
^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a[0] = a[1]
a[1] = b[0]
RUBY
end
it 'registers an offense when a lambda with parallel assignment is used on the RHS' do
expect_offense(<<~RUBY)
a, b = x, -> { a, b = x, y }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = x
b = -> { a, b = x, y }
RUBY
end
shared_examples('allowed') do |source|
it "allows assignment of: #{source.gsub(/\s*\n\s*/, '; ')}" do
expect_no_offenses(source)
end
end
it_behaves_like('allowed', 'a = 1')
it_behaves_like('allowed', 'a = a')
it_behaves_like('allowed', 'a, = a')
it_behaves_like('allowed', 'a, = 1')
it_behaves_like('allowed', "a = *'foo'")
it_behaves_like('allowed', "a, = *'foo'")
it_behaves_like('allowed', 'a, = 1, 2, 3')
it_behaves_like('allowed', 'a, = *foo')
it_behaves_like('allowed', 'a, *b = [1, 2, 3]')
it_behaves_like('allowed', '*a, b = [1, 2, 3]')
it_behaves_like('allowed', '*, b = [1, 2, 3]')
it_behaves_like('allowed', 'a, *, b = [1, 2, 3]')
it_behaves_like('allowed', 'a, b = b, a')
it_behaves_like('allowed', 'a, b, c = b, c, a')
it_behaves_like('allowed', 'a, b = (a + b), (a - b)')
it_behaves_like('allowed', 'a, b = foo.map { |e| e.id }')
it_behaves_like('allowed', 'a, b = foo()')
it_behaves_like('allowed', 'a, b = *foo')
it_behaves_like('allowed', 'a, b, c = 1, 2, *node')
it_behaves_like('allowed', 'a, b, c = *node, 1, 2')
it_behaves_like('allowed', 'begin_token, end_token = CONSTANT')
it_behaves_like('allowed', 'CONSTANT, = 1, 2')
it_behaves_like('allowed', <<~RUBY)
a = 1
b = 2
RUBY
it_behaves_like('allowed', <<~RUBY)
foo = [1, 2, 3]
a, b, c = foo
RUBY
it_behaves_like('allowed', <<~RUBY)
array = [1, 2, 3]
a, = array
RUBY
it_behaves_like('allowed', 'a, b = Float::INFINITY')
it_behaves_like('allowed', 'a[0], a[1] = a[1], a[0]')
it_behaves_like('allowed', 'obj.attr1, obj.attr2 = obj.attr2, obj.attr1')
it_behaves_like('allowed', 'obj.attr1, ary[0] = ary[0], obj.attr1')
it_behaves_like('allowed', 'ary[0], ary[1], ary[2] = ary[1], ary[2], ary[0]')
it_behaves_like('allowed', 'self.a, self.b = self.b, self.a')
it_behaves_like('allowed', 'self.a, self.b = b, a')
it 'corrects when the number of left hand variables matches the number of right hand variables' do
expect_offense(<<~RUBY)
a, b, c = 1, 2, 3
^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = 1
b = 2
c = 3
RUBY
end
it 'corrects when the right variable is an array' do
expect_offense(<<~RUBY)
a, b, c = ["1", "2", :c]
^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = "1"
b = "2"
c = :c
RUBY
end
it 'corrects when the right variable is a word array' do
expect_offense(<<~RUBY)
a, b, c = %w(1 2 3)
^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = '1'
b = '2'
c = '3'
RUBY
end
it 'corrects when the right variable is a symbol array' do
expect_offense(<<~RUBY)
a, b, c = %i(a b c)
^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = :a
b = :b
c = :c
RUBY
end
it 'corrects when assigning to method returns' do
expect_offense(<<~RUBY)
a, b = foo(), bar()
^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = foo()
b = bar()
RUBY
end
it 'corrects when assigning from multiple methods with blocks' do
expect_offense(<<~RUBY)
a, b = foo() { |c| puts c }, bar() { |d| puts d }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = foo() { |c| puts c }
b = bar() { |d| puts d }
RUBY
end
it 'corrects when using constants' do
expect_offense(<<~RUBY)
CONSTANT1, CONSTANT2 = CONSTANT3, CONSTANT4
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
CONSTANT1 = CONSTANT3
CONSTANT2 = CONSTANT4
RUBY
end
it 'corrects when using parallel assignment in singleton method' do
expect_offense(<<~RUBY)
def self.foo
foo, bar = 1, 2
^^^^^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
def self.foo
foo = 1
bar = 2
end
RUBY
end
it 'corrects when the expression is missing spaces' do
expect_offense(<<~RUBY)
a,b,c=1,2,3
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = 1
b = 2
c = 3
RUBY
end
it 'corrects when using single indentation' do
expect_offense(<<~RUBY)
def foo
a, b, c = 1, 2, 3
^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
def foo
a = 1
b = 2
c = 3
end
RUBY
end
it 'corrects when using nested indentation' do
expect_offense(<<~RUBY)
def foo
if true
a, b, c = 1, 2, 3
^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
end
end
RUBY
expect_correction(<<~RUBY)
def foo
if true
a = 1
b = 2
c = 3
end
end
RUBY
end
it 'corrects when the expression uses a modifier if statement' do
expect_offense(<<~RUBY)
a, b = 1, 2 if foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
if foo
a = 1
b = 2
end
RUBY
end
it 'corrects when the expression uses a modifier if statement inside a method' do
expect_offense(<<~RUBY)
def foo
a, b = 1, 2 if foo
^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
def foo
if foo
a = 1
b = 2
end
end
RUBY
end
it 'corrects parallel assignment in if statements' do
expect_offense(<<~RUBY)
if foo
a, b = 1, 2
^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
if foo
a = 1
b = 2
end
RUBY
end
it 'corrects when the expression uses a modifier unless statement' do
expect_offense(<<~RUBY)
a, b = 1, 2 unless foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
unless foo
a = 1
b = 2
end
RUBY
end
it 'corrects parallel assignment in unless statements' do
expect_offense(<<~RUBY)
unless foo
a, b = 1, 2
^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
unless foo
a = 1
b = 2
end
RUBY
end
it 'corrects when the expression uses a modifier while statement' do
expect_offense(<<~RUBY)
a, b = 1, 2 while foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
while foo
a = 1
b = 2
end
RUBY
end
it 'corrects parallel assignment in while statements' do
expect_offense(<<~RUBY)
while foo
a, b = 1, 2
^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
while foo
a = 1
b = 2
end
RUBY
end
it 'corrects when the expression uses a modifier until statement' do
expect_offense(<<~RUBY)
a, b = 1, 2 until foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
until foo
a = 1
b = 2
end
RUBY
end
it 'corrects parallel assignment in until statements' do
expect_offense(<<~RUBY)
until foo
a, b = 1, 2
^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
until foo
a = 1
b = 2
end
RUBY
end
it 'corrects when the expression uses a modifier rescue statement', :ruby26 do
expect_offense(<<~RUBY)
a, b = 1, 2 rescue foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
begin
a = 1
b = 2
rescue
foo
end
RUBY
end
it 'corrects when the expression uses a modifier rescue statement', :ruby27 do
expect_offense(<<~RUBY)
a, b = 1, 2 rescue foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
begin
a = 1
b = 2
rescue
foo
end
RUBY
end
it 'corrects parallel assignment inside rescue statements within method definitions' do
expect_offense(<<~RUBY)
def bar
a, b = 1, 2
^^^^^^^^^^^ Do not use parallel assignment.
rescue
'foo'
end
RUBY
expect_correction(<<~RUBY)
def bar
a = 1
b = 2
rescue
'foo'
end
RUBY
end
it 'corrects parallel assignment in rescue statements within begin ... rescue' do
expect_offense(<<~RUBY)
begin
a, b = 1, 2
^^^^^^^^^^^ Do not use parallel assignment.
rescue
'foo'
end
RUBY
expect_correction(<<~RUBY)
begin
a = 1
b = 2
rescue
'foo'
end
RUBY
end
it 'corrects when the expression uses a modifier rescue statement as the only thing inside of a method', :ruby26 do
expect_offense(<<~RUBY)
def foo
a, b = 1, 2 rescue foo
^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
def foo
a = 1
b = 2
rescue
foo
end
RUBY
end
it 'corrects when the expression uses a modifier rescue statement as the only thing inside of a method', :ruby27 do
expect_offense(<<~RUBY)
def foo
a, b = 1, 2 rescue foo
^^^^^^^^^^^ Do not use parallel assignment.
end
RUBY
expect_correction(<<~RUBY)
def foo
a = 1
b = 2
rescue
foo
end
RUBY
end
it 'corrects when the expression uses a modifier rescue statement inside of a method', :ruby26 do
expect_offense(<<~RUBY)
def foo
a, b = %w(1 2) rescue foo
^^^^^^^^^^^^^^ Do not use parallel assignment.
something_else
end
RUBY
expect_correction(<<~RUBY)
def foo
begin
a = '1'
b = '2'
rescue
foo
end
something_else
end
RUBY
end
it 'corrects when the expression uses a modifier rescue statement inside of a method', :ruby27 do
expect_offense(<<~RUBY)
def foo
a, b = %w(1 2) rescue foo
^^^^^^^^^^^^^^ Do not use parallel assignment.
something_else
end
RUBY
expect_correction(<<~RUBY)
def foo
begin
a = '1'
b = '2'
rescue
foo
end
something_else
end
RUBY
end
it 'corrects when assignments must be reordered to avoid changing meaning' do
expect_offense(<<~RUBY)
a, b, c, d = 1, a + 1, b + 1, a + b + c
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
d = a + b + c
c = b + 1
b = a + 1
a = 1
RUBY
end
it 'corrects when assignments include __FILE__' do
expect_offense(<<~RUBY)
a, b = c, __FILE__
^^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = c
b = __FILE__
RUBY
end
it 'allows more left variables than right variables' do
expect_no_offenses(<<~RUBY)
a, b, c, d = 1, 2
RUBY
end
it 'allows more right variables than left variables' do
expect_no_offenses(<<~RUBY)
a, b = 1, 2, 3
RUBY
end
it 'allows expanding an assigned var' do
expect_no_offenses(<<~RUBY)
foo = [1, 2, 3]
a, b, c = foo
RUBY
end
describe 'using custom indentation width' do
let(:config) do
RuboCop::Config.new('Style/ParallelAssignment' => {
'Enabled' => true
},
'Layout/IndentationWidth' => {
'Enabled' => true,
'Width' => 3
})
end
it 'works with standard correction' do
expect_offense(<<~RUBY)
a, b, c = 1, 2, 3
^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
a = 1
b = 2
c = 3
RUBY
end
it 'works with guard clauses' do
expect_offense(<<~RUBY)
a, b = 1, 2 if foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
if foo
a = 1
b = 2
end
RUBY
end
it 'works with rescue', :ruby26 do
expect_offense(<<~RUBY)
a, b = 1, 2 rescue foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
begin
a = 1
b = 2
rescue
foo
end
RUBY
end
it 'works with rescue', :ruby27 do
expect_offense(<<~RUBY)
a, b = 1, 2 rescue foo
^^^^^^^^^^^ Do not use parallel assignment.
RUBY
expect_correction(<<~RUBY)
begin
a = 1
b = 2
rescue
foo
end
RUBY
end
it 'works with nesting' do
expect_offense(<<~RUBY)
def foo
if true
a, b, c = 1, 2, 3
^^^^^^^^^^^^^^^^^ Do not use parallel assignment.
end
end
RUBY
expect_correction(<<~RUBY)
def foo
if true
a = 1
b = 2
c = 3
end
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/arguments_forwarding_spec.rb | spec/rubocop/cop/style/arguments_forwarding_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ArgumentsForwarding, :config do
let(:cop_config) do
{
'RedundantRestArgumentNames' => redundant_rest_argument_names,
'RedundantKeywordRestArgumentNames' => redundant_keyword_rest_argument_names,
'RedundantBlockArgumentNames' => redundant_block_argument_names
}
end
let(:redundant_rest_argument_names) { %w[args arguments] }
let(:redundant_keyword_rest_argument_names) { %w[kwargs options opts] }
let(:redundant_block_argument_names) { %w[blk block proc] }
context 'TargetRubyVersion <= 2.6', :ruby26, unsupported_on: :prism do
it 'does not register an offense when using restarg with block arg' do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
bar(*args, &block)
end
RUBY
end
end
context 'TargetRubyVersion >= 2.7', :ruby27 do
it 'registers an offense when using restarg and block arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'registers an offense when using restarg, kwargs and block arg' do
expect_offense(<<~RUBY)
def foo(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'registers an offense when using restarg, kwargs and block arg with another method call' do
expect_offense(<<~RUBY)
def foo(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
baz(1, 2, 3)
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar(...)
baz(1, 2, 3)
end
RUBY
end
it 'registers an offense when using restarg, kwargs and block arg twice' do
expect_offense(<<~RUBY)
def foo(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
baz(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar(...)
baz(...)
end
RUBY
end
it 'registers an offense when passing restarg and block arg in defs', unsupported_on: :prism do
expect_offense(<<~RUBY)
def self.foo(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def self.foo(...)
bar(...)
end
RUBY
end
it 'registers an offense when the parentheses of arguments are omitted', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo *args, &block
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar *args, &block
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
# A method definition that uses forwarding arguments without parentheses
# is a syntax error. e.g. `def do_something ...`
# Therefore it enforces parentheses with autocorrection.
expect_correction(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'registers an offense when forwarding to a method in block', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
do_something do
bar(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
do_something do
bar(...)
end
end
RUBY
end
it 'registers an offense when delegating', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
obj.bar(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
end
it 'registers an offense when using restarg and block arg for `.()` call', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar.(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar.(...)
end
RUBY
end
it 'does not register an offense when using block arg', :ruby30, unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(&block)
bar(&block)
end
RUBY
end
it 'registers an offense when using default positional arg, keyword arg, and block arg', :ruby31, unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(arg = {}, **kwargs, &block)
^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(arg, **kwargs, &block)
^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(arg = {}, ...)
bar(arg, ...)
end
RUBY
end
it 'registers an offense when using block arg', :ruby31 do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block arguments forwarding (`&`).
bar(&block)
^^^^^^ Use anonymous block arguments forwarding (`&`).
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
bar(&)
end
RUBY
end
it 'does not register an offense when naming block arg `&`', :ruby31 do
expect_no_offenses(<<~RUBY)
def foo(&)
bar(&)
end
RUBY
end
it 'does not register an offense when using block arg in nested method definitions', :ruby32 do
expect_no_offenses(<<~RUBY)
def foo(x)
class << x
def bar(y, &)
baz.qux(&)
end
end
end
RUBY
end
context 'when `RedundantBlockArgumentNames: [meaningless_block_name]`' do
let(:redundant_block_argument_names) { ['meaningless_block_name'] }
it 'registers an offense when using restarg and block arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(*args, &meaningless_block_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args, &meaningless_block_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'does not register an offense when using restarg and unconfigured block arg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
bar(*args, &block)
end
RUBY
end
it 'registers an offense when using restarg and block arg', :ruby32 do
expect_offense(<<~RUBY)
def foo(*args, &meaningless_block_name)
^^^^^ Use anonymous positional arguments forwarding (`*`).
^^^^^^^^^^^^^^^^^^^^^^^ Use anonymous block arguments forwarding (`&`).
bar(*args, &meaningless_block_name)
^^^^^ Use anonymous positional arguments forwarding (`*`).
^^^^^^^^^^^^^^^^^^^^^^^ Use anonymous block arguments forwarding (`&`).
end
RUBY
expect_correction(<<~RUBY)
def foo(*, &)
bar(*, &)
end
RUBY
end
it 'registers an offense when using restarg and unconfigured block arg', :ruby32 do
expect_offense(<<~RUBY)
def foo(*args, &block)
^^^^^ Use anonymous positional arguments forwarding (`*`).
bar(*args, &block)
^^^^^ Use anonymous positional arguments forwarding (`*`).
end
RUBY
expect_correction(<<~RUBY)
def foo(*, &block)
bar(*, &block)
end
RUBY
end
end
it 'does not register an offense when using arguments forwarding' do
expect_no_offenses(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'does not register an offense when different arguments are used', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
bar(*args)
end
RUBY
end
it 'does not register an offense when different argument names are used' do
expect_no_offenses(<<~RUBY)
def foo(arg)
bar(argument)
end
RUBY
end
it 'does not register an offense when different splat argument names are used', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
bar(*arguments, &block)
end
RUBY
end
it 'does not register an offense when different kwrest argument names are used', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(**kwargs, &block)
bar(**kwarguments, &block)
end
RUBY
end
it 'does not register an offense when the restarg is overwritten', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, **kwargs, &block)
args = new_args
bar(*args, **kwargs, &block)
end
RUBY
end
it 'does not register an offense when the kwarg is overwritten', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, **kwargs, &block)
kwargs = new_kwargs
bar(*args, **kwargs, &block)
end
RUBY
end
it 'does not register an offense when the block arg is overwritten', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, **kwargs, &block)
block = new_block
bar(*args, **kwargs, &block)
end
RUBY
end
it 'does not register an offense when using the restarg outside forwarding method arguments', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, **kwargs, &block)
args.do_something
bar(*args, **kwargs, &block)
end
RUBY
end
it 'does not register an offense when assigning the restarg outside forwarding method arguments', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
var = args
foo(*args, &block)
end
RUBY
end
it 'does not register an offense when referencing the restarg outside forwarding method arguments', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
args
foo(*args, &block)
end
RUBY
end
it 'does not register an offense when not always passing the block as well as restarg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
bar(*args, &block)
baz(*args)
end
RUBY
end
it 'does not register an offense when not always passing the block as well as kwrestarg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(**kwargs, &block)
bar(**kwargs, &block)
baz(**kwargs)
end
RUBY
end
it 'does not register an offense when not always forwarding all', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, **kwargs, &block)
bar(*args, **kwargs, &block)
bar(*args, &block)
bar(**kwargs, &block)
end
RUBY
end
it 'does not register an offense when always forwarding the block but not other args', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
bar(*args, &block)
bar(&block)
end
RUBY
end
it 'does not register an offense when body of method definition is empty' do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
end
RUBY
end
it 'does not register an offense with arg destructuring', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo((bar, baz), **kwargs)
forwarded(bar, baz, **kwargs)
end
RUBY
end
it 'does not register an offense with an additional kwarg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(first:, **kwargs, &block)
forwarded(**kwargs, &block)
end
RUBY
end
context 'AllowOnlyRestArgument: true' do
let(:cop_config) { { 'AllowOnlyRestArgument' => true } }
it 'does not register an offense when using only rest arg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args)
bar(*args)
end
RUBY
end
it 'does not register an offense when using only kwrest arg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(**kwargs)
bar(**kwargs)
end
RUBY
end
it 'registers an offense when using only rest arg', :ruby32 do
expect_offense(<<~RUBY)
def foo(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
bar(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
end
RUBY
expect_correction(<<~RUBY)
def foo(*)
bar(*)
end
RUBY
end
it 'registers an offense when using only kwrest arg', :ruby32 do
expect_offense(<<~RUBY)
def foo(**kwargs)
^^^^^^^^ Use anonymous keyword arguments forwarding (`**`).
bar(**kwargs)
^^^^^^^^ Use anonymous keyword arguments forwarding (`**`).
end
RUBY
expect_correction(<<~RUBY)
def foo(**)
bar(**)
end
RUBY
end
end
context 'AllowOnlyRestArgument: false' do
let(:cop_config) { { 'AllowOnlyRestArgument' => false } }
it 'registers an offense when using only rest arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(*args)
^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args)
^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'registers an offense when using only kwrest arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(**kwargs)
^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(**kwargs)
^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'does not register an offense with default positional arguments', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(arg=1, *args)
bar(*args)
end
RUBY
end
it 'does not register an offense with default keyword arguments', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, arg: 1)
bar(*args)
end
RUBY
end
it 'registers an offense when using only rest arg', :ruby32 do
expect_offense(<<~RUBY)
def foo(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
bar(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
end
RUBY
expect_correction(<<~RUBY)
def foo(*)
bar(*)
end
RUBY
end
it 'registers an offense when using only rest arg in `yield`', :ruby32 do
expect_offense(<<~RUBY)
def foo(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
yield(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
end
RUBY
expect_correction(<<~RUBY)
def foo(*)
yield(*)
end
RUBY
end
it 'registers an offense when using only rest arg in brackets', :ruby32 do
expect_offense(<<~RUBY)
def foo(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
bar[*args]
^^^^^ Use anonymous positional arguments forwarding (`*`).
end
RUBY
expect_correction(<<~RUBY)
def foo(*)
bar[*]
end
RUBY
end
it 'registers an offense when using only kwrest arg', :ruby32 do
expect_offense(<<~RUBY)
def foo(**kwargs)
^^^^^^^^ Use anonymous keyword arguments forwarding (`**`).
bar(**kwargs)
^^^^^^^^ Use anonymous keyword arguments forwarding (`**`).
end
RUBY
expect_correction(<<~RUBY)
def foo(**)
bar(**)
end
RUBY
end
it 'registers an offense with default positional arguments', :ruby32 do
expect_offense(<<~RUBY)
def foo(arg=1, *args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
bar(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
end
RUBY
expect_correction(<<~RUBY)
def foo(arg=1, *)
bar(*)
end
RUBY
end
it 'registers an offense with default keyword arguments', :ruby32 do
expect_offense(<<~RUBY)
def foo(*args, arg: 1)
^^^^^ Use anonymous positional arguments forwarding (`*`).
bar(*args)
^^^^^ Use anonymous positional arguments forwarding (`*`).
end
RUBY
expect_correction(<<~RUBY)
def foo(*, arg: 1)
bar(*)
end
RUBY
end
end
it 'does not register an offense for restarg when passing block to separate call', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, &block)
bar(*args).baz(&block)
end
RUBY
end
it 'does not register an offense for restarg and kwrestarg when passing block to separate call', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, **kwargs, &block)
bar(*args, **kwargs).baz(&block)
end
RUBY
end
it 'does not register an offense for restarg/kwrestarg/block passed to separate methods', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(*args, **kwargs, &block)
bar(first(*args), second(**kwargs), third(&block))
end
RUBY
end
it 'does not register an offense if an additional positional parameter is present', unsupported_on: :prism do
# Technically, forward-all supports leading additional arguments in Ruby >= 2.7.3, but for
# simplicity we do not correct for any Ruby < 3.0
# https://github.com/rubocop/rubocop/issues/12087#issuecomment-1662972732
expect_no_offenses(<<~RUBY)
def method_missing(m, *args, **kwargs, &block)
if @template.respond_to?(m)
@template.send(m, *args, **kwargs, &block)
else
super
end
end
RUBY
end
it 'registers an offense if an additional positional parameter is present', :ruby30 do
expect_offense(<<~RUBY)
def method_missing(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
if @template.respond_to?(m)
@template.send(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
else
super
end
end
RUBY
expect_correction(<<~RUBY)
def method_missing(m, ...)
if @template.respond_to?(m)
@template.send(m, ...)
else
super
end
end
RUBY
end
it 'registers an offense if an additional positional parameter is present in method forwarding with safe navigation', :ruby30 do
expect_offense(<<~RUBY)
def method_missing(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
obj.foo(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def method_missing(m, ...)
obj.foo(m, ...)
end
RUBY
end
it 'registers an offense if an additional positional parameter is present in `super`', :ruby30 do
expect_offense(<<~RUBY)
def method_missing(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
super(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def method_missing(m, ...)
super(m, ...)
end
RUBY
end
it 'does not register an offense if kwargs are forwarded with a positional parameter', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(m, **kwargs, &block)
bar(m, **kwargs, &block)
end
RUBY
end
it 'does not register an offense if args are forwarded with a positional parameter last', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(m, *args, &block)
bar(*args, m, &block)
end
RUBY
end
it 'does not register an offense if args/kwargs are forwarded with a positional parameter', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(m, *args, **kwargs, &block)
bar(m, *args, **kwargs, &block)
end
RUBY
end
it 'registers an offense if args/kwargs are forwarded with a positional parameter', :ruby30 do
expect_offense(<<~RUBY)
def foo(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(m, ...)
bar(m, ...)
end
RUBY
end
it 'does not register an offense when forwarding args/kwargs with an additional arg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def self.get(*args, **kwargs, &block)
CanvasHttp.request(Net::HTTP::Get, *args, **kwargs, &block)
end
RUBY
end
it 'registers an offense when forwarding args/kwargs with an additional arg', :ruby30 do
expect_offense(<<~RUBY)
def self.get(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
CanvasHttp.request(Net::HTTP::Get, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def self.get(...)
CanvasHttp.request(Net::HTTP::Get, ...)
end
RUBY
end
it 'does not register an offense when forwarding args with an additional arg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def post(*args, &block)
future_on(executor, *args, &block)
end
RUBY
end
it 'registers an offense when args are forwarded at several call sites' do
expect_offense(<<~RUBY)
def foo(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
baz(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
if something?
baz(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
baz(...)
if something?
baz(...)
end
end
RUBY
end
end
context 'TargetRubyVersion >= 3.0', :ruby30 do
it 'does not register an offense if args are forwarded with a positional parameter last', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(m, *args, &block)
bar(*args, m, &block)
end
RUBY
end
it 'does not register an offense with an additional required kwarg that is not forwarded', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(first:, **kwargs, &block)
forwarded(**kwargs, &block)
end
RUBY
end
it 'does not register an offense with an additional required kwarg that is forwarded', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(first:, **kwargs, &block)
forwarded(first: first, **kwargs, &block)
end
RUBY
end
it 'does not register an offense with an additional optional kwarg that is not forwarded', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(first: nil, **kwargs, &block)
forwarded(**kwargs, &block)
end
RUBY
end
it 'does not register an offense with an additional optional kwarg that is forwarded', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(first: nil, **kwargs, &block)
forwarded(first: first, **kwargs, &block)
end
RUBY
end
it 'does not register an offense if args/kwargs are forwarded with a positional parameter last', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(m, *args, **kwargs, &block)
bar(*args, m, **kwargs, &block)
end
RUBY
end
it 'registers an offense if args/kwargs are forwarded with a positional parameter' do
expect_offense(<<~RUBY)
def foo(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(m, ...)
bar(m, ...)
end
RUBY
end
it 'registers an offense when args are forwarded at several call sites' do
expect_offense(<<~RUBY)
def foo(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
baz(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
if something?
baz(m, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
end
RUBY
expect_correction(<<~RUBY)
def foo(m, ...)
baz(m, ...)
if something?
baz(m, ...)
end
end
RUBY
end
it 'does not register an offense if args/kwargs are forwarded with additional pre-kwarg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(m, *args, **kwargs, &block)
bar(m, *args, extra: :kwarg, **kwargs, &block)
end
RUBY
end
it 'does not register an offense if args/kwargs are forwarded with additional post-kwarg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(m, *args, **kwargs, &block)
bar(m, *args, **kwargs, extra: :kwarg, &block)
end
RUBY
end
it 'registers an offense when forwarding args after dropping an additional arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(x, *args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
bar(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(x, ...)
bar(...)
end
RUBY
end
it 'registers no offense when forwarding args with a leading default arg', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(x, y = 42, *args, &block)
bar(x, y, *args, &block)
end
RUBY
end
it 'registers an offense when forwarding args with an additional arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def post(*args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
future_on(executor, *args, &block)
^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def post(...)
future_on(executor, ...)
end
RUBY
end
it 'registers an offense when forwarding args/kwargs with an additional arg' do
expect_offense(<<~RUBY)
def self.get(*args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
CanvasHttp.request(Net::HTTP::Get, *args, **kwargs, &block)
^^^^^^^^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def self.get(...)
CanvasHttp.request(Net::HTTP::Get, ...)
end
RUBY
end
it 'registers an offense when forwarding kwargs/block arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(**kwargs, &block)
^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
baz(**kwargs, &block)
^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
baz(...)
end
RUBY
end
it 'registers an offense when forwarding kwargs/block arg and an additional arg', unsupported_on: :prism do
expect_offense(<<~RUBY)
def foo(x, **kwargs, &block)
^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
baz(x, **kwargs, &block)
^^^^^^^^^^^^^^^^ Use shorthand syntax `...` for arguments forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(x, ...)
baz(x, ...)
end
RUBY
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/map_into_array_spec.rb | spec/rubocop/cop/style/map_into_array_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MapIntoArray, :config do
it 'registers an offense and corrects when using `each` with `<<` to build an array' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
RUBY
end
it 'registers an offense and corrects when using `each` with `push` to build an array' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest.push(e * 2) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
RUBY
end
it 'registers an offense and corrects when using `each` with `push` with hash argument without braces to build an array' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest.push(e: 2) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| { e: 2 } }
RUBY
end
it 'registers an offense and corrects when using `each` with `push` with hash argument with braces to build an array' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest.push({ e: 2 }) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| { e: 2 } }
RUBY
end
it 'registers an offense and corrects when using `each` with `append` to build an array' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest.append(e * 2) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
RUBY
end
it 'registers an offense and corrects when using `each` with `append` with hash argument without braces to build an array' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest.append(e: 2) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| { e: 2 } }
RUBY
end
it 'registers an offense and corrects when using `each` with `append` with hash argument with braces to build an array' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest.append({ e: 2 }) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| { e: 2 } }
RUBY
end
it 'registers an offense and corrects when a non-related operation precedes an `each` call' do
expect_offense(<<~RUBY)
dest = []
do_something
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
do_something
dest = src.map { |e| e * 2 }
RUBY
end
it 'registers an offense and corrects when a non-related operation follows an `each` call' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
do_something
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
do_something
RUBY
end
it 'registers an offense and corrects when using an if statement' do
expect_offense(<<~RUBY)
dest = []
src.each do |e|
^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
dest << if cond?
e
else
e * 2
end
end
RUBY
expect_correction(<<~RUBY)
dest = src.map do |e|
if cond?
e
else
e * 2
end
end
RUBY
end
it 'registers an offense and corrects when using a case statement' do
expect_offense(<<~RUBY)
dest = []
src.each do |e|
^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
dest << case foo
when 1
e
else
e * 2
end
end
RUBY
expect_correction(<<~RUBY)
dest = src.map do |e|
case foo
when 1
e
else
e * 2
end
end
RUBY
end
it 'registers an offense and corrects when using a begin block' do
expect_offense(<<~RUBY)
dest = []
src.each do |e|
^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
dest << begin
foo
e * 2
end
end
RUBY
expect_correction(<<~RUBY)
dest = src.map do |e|
begin
foo
e * 2
end
end
RUBY
end
it 'registers an offense and corrects when using an array literal' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest << [1, e] }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| [1, e] }
RUBY
end
it 'registers an offense and corrects when using a literal' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest << true }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| true }
RUBY
end
it 'registers an offense and corrects when using a numblock' do
expect_offense(<<~RUBY)
dest = []
src.each { dest << _1 * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { _1 * 2 }
RUBY
end
it 'registers an offense and corrects when using a itblock', :ruby34 do
expect_offense(<<~RUBY)
dest = []
src.each { dest << it * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { it * 2 }
RUBY
end
it 'registers an offense and corrects when the destination initialized multiple times' do
expect_offense(<<~RUBY)
dest = []
do_something(dest)
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = []
do_something(dest)
dest = src.map { |e| e * 2 }
RUBY
end
it 'registers an offense and corrects removing a destination reference follows an `each` call' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
dest
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
RUBY
end
it 'registers an offense and corrects when nested autocorrections required' do
expect_offense(<<~RUBY)
dest = []
src.each do |e|
^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
dest << (
dest2 = []
src.each do |e|
^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
dest2 << e
end
dest2
)
end
RUBY
expect_correction(<<~RUBY)
dest = src.map do |e|
(
dest2 = src.map do |e|
e
end
)
end
RUBY
end
it 'registers an offense and corrects when the destination comes from `tap` on an empty array' do
expect_offense(<<~RUBY)
[].tap do |dest|
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
end
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
RUBY
end
it 'does not register an offense when the destination comes from `tap` on an empty array that has been mutated' do
expect_no_offenses(<<~RUBY)
[].tap do |dest|
do_something(dest)
src.each { |e| dest << e * 2 }
end
RUBY
end
it 'does not register an offense when the destination comes from `tap` on a non-empty array' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].tap do |dest|
src.each { |e| dest << e * 2 }
end
RUBY
end
it 'does not register an offense when the destination comes from `tap` on a non-array' do
expect_no_offenses(<<~RUBY)
{}.tap do |dest|
src.each { |e| dest << e * 2 }
end
RUBY
end
it 'does not register an offense when the destination is not a local variable' do
expect_no_offenses(<<~RUBY)
@dest = []
src.each { |e| @dest << e }
RUBY
end
it 'does not register an offense when `each` is called with non-block arguments' do
expect_no_offenses(<<~RUBY)
dest = []
StringIO.new('foo:bar').each(':') { |e| dest << e }
RUBY
end
it 'does not register an offense when using `each` without receiver with `<<` to build an array' do
expect_no_offenses(<<~RUBY)
dest = []
each { |e| dest << e * 2 }
RUBY
end
it 'does not register an offense when using `each` with `self` receiver with `<<` to build an array' do
expect_no_offenses(<<~RUBY)
dest = []
self.each { |e| dest << e * 2 }
RUBY
end
it 'does not register an offense when the parent node of an `each` call is not a begin node' do
expect_no_offenses(<<~RUBY)
[
dest = [],
src.each { |e| dest << e * 2 },
]
RUBY
end
it 'does not register an offense when the destination initialization is not a sibling of an `each` call' do
expect_no_offenses(<<~RUBY)
dest = []
if cond
src.each { |e| dest << e * 2 }
end
RUBY
end
it 'does not register an offense when the destination is used before an `each` call' do
expect_no_offenses(<<~RUBY)
dest = []
dest << 0
src.each { |e| dest << e * 2 }
RUBY
end
it 'does not register an offense when the destination is used in the receiver expression' do
expect_no_offenses(<<~RUBY)
dest = []
(dest << 1).each { |e| dest << e * 2 }
RUBY
end
it 'does not register an offense when the destination is shadowed by a block argument' do
expect_no_offenses(<<~RUBY)
dest = []
src.each { |dest| dest << 1 }
RUBY
end
it 'does not register an offense when the destination is used in the transformation' do
expect_no_offenses(<<~RUBY)
dest = []
src.each { |e| dest << dest.size }
RUBY
end
it 'does not register an offense when pushing splat' do
expect_no_offenses(<<~RUBY)
dest = []
src.each { |e| dest.push(*e) }
RUBY
end
it 'does not register an offense when pushing anonymously-forwarded block', :ruby31 do
expect_no_offenses(<<~RUBY)
def foo(&)
dest = []
src.each { |e| dest.push(&) }
end
RUBY
end
it 'does not register an offense when pushing anonymously-forwarded restarg', :ruby32 do
expect_no_offenses(<<~RUBY)
def foo(*)
dest = []
src.each { |e| dest.push(*) }
end
RUBY
end
it 'does not register an offense when pushing anonymously-forwarded kwrestarg', :ruby32, unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
def foo(**)
dest = []
src.each { |e| dest.push(**) }
end
RUBY
end
it 'does not register an offense when pushing anonymously-forwarded args' do
expect_no_offenses(<<~RUBY)
def foo(...)
dest = []
src.each { |e| dest.push(...) }
end
RUBY
end
context 'destination initializer' do
shared_examples 'corrects' do |initializer:|
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
dest = #{initializer}
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
RUBY
end
end
context '[]' do
it_behaves_like 'corrects', initializer: '[]'
end
context 'Array.new' do
it_behaves_like 'corrects', initializer: 'Array.new'
end
context 'Array[]' do
it_behaves_like 'corrects', initializer: 'Array[]'
end
context 'Array([])' do
it_behaves_like 'corrects', initializer: 'Array([])'
end
context 'Array.new([])' do
it_behaves_like 'corrects', initializer: 'Array.new([])'
end
end
context 'new method name for replacement' do
context 'when `Style/CollectionMethods` is configured for `map`' do
let(:other_cops) do
{
'Style/CollectionMethods' => {
'PreferredMethods' => {
'map' => 'collect'
}
}
}
end
it 'registers an offense and corrects using the method specified in `PreferredMethods`' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `collect` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.collect { |e| e * 2 }
RUBY
end
end
context 'when `Style/CollectionMethods` is configured except for `map`' do
let(:other_cops) do
{
'Style/CollectionMethods' => {
'PreferredMethods' => {
'reject' => 'filter'
}
}
}
end
it 'registers an offense and corrects using `map` method' do
expect_offense(<<~RUBY)
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(<<~RUBY)
dest = src.map { |e| e * 2 }
RUBY
end
end
end
context 'autocorrection skipping' do
shared_examples 'corrects' do |template:|
it 'registers an offense and corrects' do
expect_offense(format(template, <<~RUBY))
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_correction(format(template, <<~RUBY))
dest = src.map { |e| e * 2 }
RUBY
end
end
shared_examples 'skip correcting' do |template:|
it 'registers an offense but does not autocorrect it' do
expect_offense(format(template, <<~RUBY))
dest = []
src.each { |e| dest << e * 2 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `map` instead of `each` to map elements into an array.
RUBY
expect_no_corrections
end
end
context 'at the top level' do
it_behaves_like 'corrects', template: '%s'
end
context 'in parentheses' do
context 'not at the end' do
context 'parent is used' do
it_behaves_like 'corrects', template: 'a = (%s; do_someting)'
end
context 'parent is not used' do
it_behaves_like 'corrects', template: '(%s; do_someting)'
end
end
context 'at the end' do
context 'parent is used' do
it_behaves_like 'skip correcting', template: 'a = (%s)'
end
context 'parent is not used' do
it_behaves_like 'corrects', template: '(%s)'
end
end
end
context 'in a begin block' do
context 'not at the end' do
context 'parent is used' do
it_behaves_like 'corrects', template: 'a = begin; %s; do_something end'
end
context 'parent is not used' do
it_behaves_like 'corrects', template: 'begin; %s; do_something end'
end
end
context 'at the end' do
context 'parent is used' do
it_behaves_like 'skip correcting', template: 'a = begin; %s end'
end
context 'parent is not used' do
it_behaves_like 'corrects', template: 'begin; %s end'
end
end
context 'in an ensure' do
it_behaves_like 'corrects', template: 'begin; ensure; %s end'
end
end
context 'in a block' do
context 'in a void context' do
it_behaves_like 'corrects', template: 'each { %s }'
end
context 'in a non-void context' do
it_behaves_like 'skip correcting', template: 'block { %s }'
end
end
context 'in a numblock' do
context 'in a void context' do
it_behaves_like 'corrects', template: 'each { _1; %s }'
end
context 'in a non-void context' do
it_behaves_like 'skip correcting', template: 'block { _1; %s }'
end
end
context 'in a method' do
context 'not at the end' do
it_behaves_like 'corrects', template: 'def foo; %s; do_something end'
end
context 'at the end' do
it_behaves_like 'skip correcting', template: 'def foo; %s end'
end
context 'in a constructor' do
it_behaves_like 'corrects', template: 'def initialize; %s; end'
end
context 'in an assignment method' do
it_behaves_like 'corrects', template: 'def foo=(value); %s; end'
end
end
context 'in a for loop' do
it_behaves_like 'corrects', template: 'for i in foo; %s; end'
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/empty_method_spec.rb | spec/rubocop/cop/style/empty_method_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyMethod, :config do
context 'when configured with compact style' do
let(:cop_config) { { 'EnforcedStyle' => 'compact' } }
context 'with an empty instance method definition' do
it 'registers an offense for empty method' do
expect_offense(<<~RUBY)
def foo
^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def foo; end
RUBY
end
it 'registers an offense for method with arguments' do
expect_offense(<<~RUBY)
def foo(bar, baz)
^^^^^^^^^^^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def foo(bar, baz); end
RUBY
end
it 'registers an offense for method with arguments without parens' do
expect_offense(<<~RUBY)
def foo bar, baz
^^^^^^^^^^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def foo bar, baz; end
RUBY
end
it 'registers an offense for method with blank line' do
expect_offense(<<~RUBY)
def foo
^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def foo; end
RUBY
end
it 'registers an offense for method with closing paren on following line' do
expect_offense(<<~RUBY)
def foo(arg
^^^^^^^^^^^ Put empty method definitions on a single line.
); end
RUBY
expect_correction(<<~RUBY)
def foo(arg); end
RUBY
end
it 'allows single line method' do
expect_no_offenses('def foo; end')
end
end
context 'with a non-empty instance method definition' do
it 'allows multi line method' do
expect_no_offenses(<<~RUBY)
def foo
bar
end
RUBY
end
it 'allows single line method' do
expect_no_offenses('def foo; bar; end')
end
it 'allows multi line method with comment' do
expect_no_offenses(<<~RUBY)
def foo
# bar
end
RUBY
end
end
context 'with an empty class method definition' do
it 'registers an offense for empty method' do
expect_offense(<<~RUBY)
def self.foo
^^^^^^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def self.foo; end
RUBY
end
it 'registers an offense for empty method with arguments' do
expect_offense(<<~RUBY)
def self.foo(bar, baz)
^^^^^^^^^^^^^^^^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def self.foo(bar, baz); end
RUBY
end
it 'registers an offense for method with blank line' do
expect_offense(<<~RUBY)
def self.foo
^^^^^^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def self.foo; end
RUBY
end
it 'allows single line method' do
expect_no_offenses('def self.foo; end')
end
end
context 'with a non-empty class method definition' do
it 'allows multi line method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar
end
RUBY
end
it 'allows single line method' do
expect_no_offenses('def self.foo; bar; end')
end
it 'allows multi line method with comment' do
expect_no_offenses(<<~RUBY)
def self.foo
# bar
end
RUBY
end
end
context 'relation with Layout/LineLength' do
let(:other_cops) do
{
'Layout/LineLength' => {
'Enabled' => line_length_enabled,
'Max' => 20
}
}
end
let(:line_length_enabled) { true }
context 'when that cop is disabled' do
let(:line_length_enabled) { false }
it 'corrects to long lines' do
expect_offense(<<~RUBY)
def foo(abc: '10000', def: '20000', ghi: '30000')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_correction(<<~RUBY)
def foo(abc: '10000', def: '20000', ghi: '30000'); end
RUBY
end
end
context 'when the correction would exceed the configured maximum' do
it 'reports an offense but does not correct' do
expect_offense(<<~RUBY)
def foo(abc: '10000', def: '20000', ghi: '30000')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Put empty method definitions on a single line.
end
RUBY
expect_no_corrections
end
end
end
end
context 'when configured with expanded style' do
let(:cop_config) { { 'EnforcedStyle' => 'expanded' } }
context 'with an empty instance method definition' do
it 'allows multi line method' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
it 'allows multi line method with blank line' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
it 'registers an offense for single line method' do
expect_offense(<<~RUBY)
def foo; end
^^^^^^^^^^^^ Put the `end` of empty method definitions on the next line.
RUBY
expect_correction(<<~RUBY)
def foo
end
RUBY
end
end
context 'with a non-empty instance method definition' do
it 'allows multi line method' do
expect_no_offenses(<<~RUBY)
def foo
bar
end
RUBY
end
it 'allows single line method' do
expect_no_offenses('def foo; bar; end')
end
it 'allows multi line method with a comment' do
expect_no_offenses(<<~RUBY)
def foo
# bar
end
RUBY
end
end
context 'with an empty class method definition' do
it 'allows empty multi line method' do
expect_no_offenses(<<~RUBY)
def self.foo
end
RUBY
end
it 'allows multi line method with a blank line' do
expect_no_offenses(<<~RUBY)
def self.foo
end
RUBY
end
it 'registers an offense for single line method' do
expect_offense(<<~RUBY)
def self.foo; end
^^^^^^^^^^^^^^^^^ Put the `end` of empty method definitions on the next line.
RUBY
expect_correction(<<~RUBY)
def self.foo
end
RUBY
end
end
context 'with a non-empty class method definition' do
it 'allows multi line method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar
end
RUBY
end
it 'allows single line method' do
expect_no_offenses('def self.foo; bar; end')
end
it 'allows multi line method with comment' do
expect_no_offenses(<<~RUBY)
def self.foo
# bar
end
RUBY
end
end
context 'when method is nested in class scope' do
it 'registers an offense for single line method' do
expect_offense(<<~RUBY)
class Foo
def bar; end
^^^^^^^^^^^^ Put the `end` of empty method definitions on the next line.
end
RUBY
expect_correction(<<~RUBY)
class Foo
def bar
end
end
RUBY
end
end
context 'relation with Layout/LineLength' do
let(:other_cops) do
{
'Layout/LineLength' => {
'Enabled' => true,
'Max' => 20
}
}
end
it 'still corrects even if the method is longer than the configured Max' do
expect_offense(<<~RUBY)
def foo(abc: '10000', def: '20000', ghi: '30000'); end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Put the `end` of empty method definitions on the next line.
RUBY
expect_correction(<<~RUBY)
def foo(abc: '10000', def: '20000', ghi: '30000')
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/unless_logical_operators_spec.rb | spec/rubocop/cop/style/unless_logical_operators_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::UnlessLogicalOperators, :config do
context 'EnforcedStyle is `forbid_mixed_logical_operators`' do
let(:cop_config) { { 'EnforcedStyle' => 'forbid_mixed_logical_operators' } }
it 'registers an offense when using `&&` and `||`' do
expect_offense(<<~RUBY)
return unless a && b || c
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
expect_offense(<<~RUBY)
return unless a || b && c
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
end
it 'registers an offense when using `&&` and `and`' do
expect_offense(<<~RUBY)
return unless a && b and c
^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
expect_offense(<<~RUBY)
return unless a and b && c
^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
end
it 'registers an offense when using `&&` and `or`' do
expect_offense(<<~RUBY)
return unless a && b or c
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
expect_offense(<<~RUBY)
return unless a or b && c
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
end
it 'registers an offense when using `||` and `or`' do
expect_offense(<<~RUBY)
return unless a || b or c
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
expect_offense(<<~RUBY)
return unless a or b || c
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
end
it 'registers an offense when using `||` and `and`' do
expect_offense(<<~RUBY)
return unless a || b and c
^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
expect_offense(<<~RUBY)
return unless a and b || c
^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
end
it 'registers an offense when using parentheses' do
expect_offense(<<~RUBY)
return unless a || (b && c) || d
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use mixed logical operators in an `unless`.
RUBY
end
it 'does not register an offense when using only `&&`s' do
expect_no_offenses(<<~RUBY)
return unless a && b && c
RUBY
end
it 'does not register an offense when using only `||`s' do
expect_no_offenses(<<~RUBY)
return unless a || b || c
RUBY
end
it 'does not register an offense when using only `and`s' do
expect_no_offenses(<<~RUBY)
return unless a and b and c
RUBY
end
it 'does not register an offense when using only `or`s' do
expect_no_offenses(<<~RUBY)
return unless a or b or c
RUBY
end
it 'does not register an offense when using if' do
expect_no_offenses(<<~RUBY)
return if a || b && c || d
RUBY
end
it 'does not register an offense when not used in unless' do
expect_no_offenses(<<~RUBY)
def condition?
a or b && c || d
end
RUBY
end
it 'does not register an offense when not using logical operator' do
expect_no_offenses(<<~RUBY)
return unless a?
RUBY
end
it 'does not register an offense when using `||` operator and invoked method name includes "or" in the conditional branch' do
expect_no_offenses(<<~RUBY)
unless condition
includes_or_in_the_name
foo || bar
end
RUBY
end
it 'does not register an offense when using `&&` operator and invoked method name includes "and" in the conditional branch' do
expect_no_offenses(<<~RUBY)
unless condition
includes_and_in_the_name
foo && bar
end
RUBY
end
end
context 'EnforcedStyle is `forbid_logical_operators`' do
let(:cop_config) { { 'EnforcedStyle' => 'forbid_logical_operators' } }
it 'registers an offense when using only `&&`' do
expect_offense(<<~RUBY)
return unless a && b
^^^^^^^^^^^^^^^^^^^^ Do not use any logical operator in an `unless`.
RUBY
end
it 'registers an offense when using only `||`' do
expect_offense(<<~RUBY)
return unless a || b
^^^^^^^^^^^^^^^^^^^^ Do not use any logical operator in an `unless`.
RUBY
end
it 'registers an offense when using only `and`' do
expect_offense(<<~RUBY)
return unless a and b
^^^^^^^^^^^^^^^^^^^^^ Do not use any logical operator in an `unless`.
RUBY
end
it 'registers an offense when using only `or`' do
expect_offense(<<~RUBY)
return unless a or b
^^^^^^^^^^^^^^^^^^^^ Do not use any logical operator in an `unless`.
RUBY
end
it 'registers an offense when using `&&` followed by ||' do
expect_offense(<<~RUBY)
return unless a && b || c
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use any logical operator in an `unless`.
RUBY
end
it 'does not register an offense when using if' do
expect_no_offenses(<<~RUBY)
return if a || b
RUBY
end
it 'does not register an offense when not used in unless' do
expect_no_offenses(<<~RUBY)
def condition?
a || b
end
RUBY
end
it 'does not register an offense when not using logical operator' do
expect_no_offenses(<<~RUBY)
return unless a?
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/access_modifier_declarations_spec.rb | spec/rubocop/cop/style/access_modifier_declarations_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::AccessModifierDeclarations, :config do
shared_examples 'always accepted' do |access_modifier|
it "accepts when #{access_modifier} is a hash literal value" do
expect_no_offenses(<<~RUBY)
class Foo
foo
bar(key: #{access_modifier})
end
RUBY
end
context 'allow access modifiers on symbols' do
let(:cop_config) { { 'AllowModifiersOnSymbols' => true } }
it "accepts when argument to #{access_modifier} is a symbol" do
expect_no_offenses(<<~RUBY)
class Foo
foo
#{access_modifier} :bar
end
RUBY
end
it "accepts when argument to #{access_modifier} is multiple symbols" do
expect_no_offenses(<<~RUBY)
class Foo
foo
#{access_modifier} :bar, :baz
end
RUBY
end
it "accepts when argument to #{access_modifier} is splat with a `%i` array literal" do
expect_no_offenses(<<~RUBY)
class Foo
foo
#{access_modifier} *%i[bar baz]
end
RUBY
end
it "accepts when argument to #{access_modifier} is splat with a constant" do
expect_no_offenses(<<~RUBY)
class Foo
foo
#{access_modifier} *METHOD_NAMES
end
RUBY
end
it "accepts when argument to #{access_modifier} is a splat with a method call" do
expect_no_offenses(<<~RUBY)
class Foo
foo
#{access_modifier} *bar
end
RUBY
end
end
context 'do not allow access modifiers on symbols' do
let(:cop_config) { { 'AllowModifiersOnSymbols' => false } }
it "does not register an offense when argument to #{access_modifier} is a symbol and there is no surrounding scope" do
expect_no_offenses(<<~RUBY)
#{access_modifier} :foo
RUBY
end
it "registers an offense when argument to #{access_modifier} is a symbol" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Foo
foo
%{access_modifier} :bar
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_no_corrections
end
context "when argument to #{access_modifier} is multiple symbols" do
it 'registers an offense and does not autocorrect when methods are not defined' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Foo
foo
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_no_corrections
end
it 'registers an offense and autocorrects when methods are all defined in class' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
module Foo
def bar; end
def baz; end
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
module Foo
#{access_modifier}
def bar; end
def baz; end
end
RUBY
end
it 'registers an offense and autocorrects when methods are all defined in class and there is a comment' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
module Foo
def bar; end
def baz; end
# comment
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
module Foo
#{access_modifier}
# comment
def bar; end
def baz; end
end
RUBY
end
it 'registers an offense and autocorrects when methods are all defined in class and there is already a bare access modifier' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
module Foo
def bar; end
def baz; end
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
%{access_modifier}
def quux; end
end
RUBY
expect_correction(<<~RUBY)
module Foo
#{access_modifier}
def bar; end
def baz; end
def quux; end
end
RUBY
end
it 'registers an offense but does not correct when not all methods are defined in class' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
module Foo
def bar; end
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_no_corrections
end
it 'registers an offense and autocorrects when methods are all defined in self class' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class << self
def bar; end
def baz; end
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class << self
#{access_modifier}
def bar; end
def baz; end
end
RUBY
end
it 'registers an offense and autocorrects when methods are all defined in self class and there is a comment' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class << self
def bar; end
def baz; end
# comment
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class << self
#{access_modifier}
# comment
def bar; end
def baz; end
end
RUBY
end
it 'registers an offense and autocorrects when methods are all defined in self class and there is already a bare access modifier' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class << self
def bar; end
def baz; end
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
%{access_modifier}
def quux; end
end
RUBY
expect_correction(<<~RUBY)
class << self
#{access_modifier}
def bar; end
def baz; end
def quux; end
end
RUBY
end
it 'registers an offense but does not correct when not all methods are defined in self class' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class << self
def bar; end
%{access_modifier} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_no_corrections
end
end
it "registers an offense when argument to #{access_modifier} is splat with a `%i` array literal" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Foo
foo
%{access_modifier} *%i[bar baz]
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_no_corrections
end
it "registers an offense when argument to #{access_modifier} is splat with a constant" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Foo
foo
%{access_modifier} *METHOD_NAMES
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_no_corrections
end
end
context 'allow access modifiers on attrs' do
let(:cop_config) { { 'AllowModifiersOnAttrs' => true } }
it "accepts when argument to #{access_modifier} is an attr_*" do
expect_no_offenses(<<~RUBY)
class Foo
#{access_modifier} attr_reader :foo
#{access_modifier} attr_writer :bar
#{access_modifier} attr_accessor :baz
#{access_modifier} attr :qux
end
RUBY
end
it 'accepts multiple arguments on attrs' do
expect_no_offenses(<<~RUBY)
class Foo
#{access_modifier} attr_reader :reader1, :reader2
#{access_modifier} attr_writer :writer1, :writer2
#{access_modifier} attr_accessor :accessor1, :accessor2
#{access_modifier} attr :attr1, :attr2
end
RUBY
end
end
context 'do not allow access modifiers on attrs' do
let(:cop_config) { { 'AllowModifiersOnAttrs' => false } }
%i[attr_reader attr_writer attr_accessor attr].each do |attr_method|
context "for #{access_modifier} #{attr_method}" do
it 'registers an offense for a single symbol' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Foo
foo
%{access_modifier} #{attr_method} :bar
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Foo
foo
#{access_modifier}
#{attr_method} :bar
end
RUBY
end
it 'registers an offense for multiple symbols' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Foo
foo
%{access_modifier} #{attr_method} :bar, :baz
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Foo
foo
#{access_modifier}
#{attr_method} :bar, :baz
end
RUBY
end
end
end
end
context 'allow access modifiers on alias_method' do
let(:cop_config) { { 'AllowModifiersOnAliasMethod' => true } }
it "accepts when argument to #{access_modifier} is an alias_method" do
expect_no_offenses(<<~RUBY)
class Foo
#{access_modifier} alias_method :bar, :foo
end
RUBY
end
end
context 'do not allow access modifiers on alias_method' do
let(:cop_config) { { 'AllowModifiersOnAliasMethod' => false } }
it "registers an offense when argument to #{access_modifier} is an alias_method" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Foo
#{access_modifier} alias_method :bar, :foo
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Foo
#{access_modifier}
alias_method :bar, :foo
end
RUBY
end
end
end
context 'when `group` is configured' do
let(:cop_config) { { 'EnforcedStyle' => 'group' } }
%w[private protected public module_function].each do |access_modifier|
it "offends when #{access_modifier} is inlined with a method" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
%{access_modifier} def foo; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier}
def foo; end
end
RUBY
end
it "offends when #{access_modifier} is inlined with a method on the top level" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
%{access_modifier} def foo; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
RUBY
expect_correction(<<~RUBY)
#{access_modifier}
def foo; end
RUBY
end
it "does not offend when #{access_modifier} is not inlined" do
expect_no_offenses(<<~RUBY)
class Test
#{access_modifier}
end
RUBY
end
it "accepts when using only #{access_modifier}" do
expect_no_offenses(<<~RUBY)
#{access_modifier}
RUBY
end
it "does not offend when #{access_modifier} is not inlined and has a comment" do
expect_no_offenses(<<~RUBY)
class Test
#{access_modifier} # hey
end
RUBY
end
it "registers an offense for correct + multiple opposite styles of #{access_modifier} usage" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class TestOne
#{access_modifier}
end
class TestTwo
#{access_modifier} def foo; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
class TestThree
#{access_modifier} def foo; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class TestOne
#{access_modifier}
end
class TestTwo
#{access_modifier}
def foo; end
end
class TestThree
#{access_modifier}
def foo; end
end
RUBY
end
context 'when method is modified by inline modifier' do
it 'registers and autocorrects an offense' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
#{access_modifier} def foo; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier}
def foo; end
end
RUBY
end
end
it "does not register an offense when using #{access_modifier} in a block" do
expect_no_offenses(<<~RUBY)
module MyModule
singleton_methods.each { |method| #{access_modifier}(method) }
end
RUBY
end
it "does not register an offense when using #{access_modifier} in a numblock" do
expect_no_offenses(<<~RUBY)
module MyModule
singleton_methods.each { #{access_modifier}(_1) }
end
RUBY
end
context 'when method is modified by inline modifier with disallowed symbol' do
let(:cop_config) do
{ 'AllowModifiersOnSymbols' => false }
end
it 'registers and autocorrects an offense' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
def foo; end
#{access_modifier} :foo
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier}
def foo; end
end
RUBY
end
end
context 'when non-existent method is modified by inline modifier with disallowed symbol' do
let(:cop_config) do
{ 'AllowModifiersOnSymbols' => false }
end
it 'registers an offense but does not autocorrect it' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
#{access_modifier} :foo
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_no_corrections
end
end
%w[attr attr_reader attr_writer attr_accessor].each do |attr_method|
context "when method is modified by inline modifier with disallowed #{attr_method}" do
let(:cop_config) do
{ 'AllowModifiersOnAttrs' => false }
end
it 'registers and autocorrects an offense' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
#{access_modifier} #{attr_method} :foo
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier}
#{attr_method} :foo
end
RUBY
end
end
end
context 'when method is modified by inline modifier where group modifier already exists' do
it 'registers and autocorrects an offense' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
#{access_modifier} def foo; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
#{access_modifier}
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier}
def foo; end
end
RUBY
end
end
context 'when method has comments' do
it 'registers and autocorrects an offense' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
# comment
#{access_modifier} def foo
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
# comment
end
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier}
# comment
def foo
# comment
end
end
RUBY
end
end
context "with #{access_modifier} within `if` node" do
it "does not offend when #{access_modifier} does not have right sibling node" do
expect_no_offenses(<<~RUBY)
class Test
#{access_modifier} :inspect if METHODS.include?(:inspect)
end
RUBY
end
it 'registers and autocorrects offense if conditional modifier is followed by a normal one' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
#{access_modifier} get_method_name if get_method_name =~ /a/
#{access_modifier} def bar; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier} get_method_name if get_method_name =~ /a/
#{access_modifier}
def bar; end
end
RUBY
end
it 'registers and autocorrects offense if conditional modifiers wrap a normal one' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
#{access_modifier} get_method_name_1 if get_method_name_1 =~ /a/
#{access_modifier} def bar; end
^{access_modifier} `#{access_modifier}` should not be inlined in method definitions.
#{access_modifier} get_method_name_2 if get_method_name_2 =~ /b/
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier} get_method_name_1 if get_method_name_1 =~ /a/
#{access_modifier} get_method_name_2 if get_method_name_2 =~ /b/
#{access_modifier}
def bar; end
end
RUBY
end
end
it_behaves_like 'always accepted', access_modifier
end
it 'offends when multiple groupable access modifiers are defined' do
expect_offense(<<~RUBY)
class Test
private def foo; end
private def bar; end
^^^^^^^ `private` should not be inlined in method definitions.
def baz; end
QUX = ['qux']
end
RUBY
expect_correction(<<~RUBY)
class Test
def baz; end
QUX = ['qux']
private
def foo; end
def bar; end
end
RUBY
end
end
context 'when `inline` is configured' do
let(:cop_config) { { 'EnforcedStyle' => 'inline' } }
%w[private protected public module_function].each do |access_modifier|
it "offends when #{access_modifier} is not inlined" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
%{access_modifier}
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
def foo; end
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier} def foo; end
end
RUBY
end
it "offends when #{access_modifier} is not inlined and has a comment" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
%{access_modifier} # hey
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
def foo; end
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier} def foo; end
end
RUBY
end
it "does not offend when #{access_modifier} is inlined with a method" do
expect_no_offenses(<<~RUBY)
class Test
#{access_modifier} def foo; end
end
RUBY
end
it "does not offend when #{access_modifier} is inlined with a symbol" do
expect_no_offenses(<<~RUBY)
class Test
#{access_modifier} :foo
def foo; end
end
RUBY
end
it "registers an offense for correct + multiple opposite styles of #{access_modifier} usage" do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class TestOne
#{access_modifier} def foo; end
end
class TestTwo
#{access_modifier}
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
def foo; end
end
RUBY
expect_correction(<<~RUBY)
class TestOne
#{access_modifier} def foo; end
end
class TestTwo
#{access_modifier} def foo; end
end
RUBY
end
it "does not register an offense for #{access_modifier} without method definitions" do
expect_no_offenses(<<~RUBY)
#{access_modifier}
RUBY
end
context 'when methods are modified by group modifier' do
it 'registers and autocorrects an offense' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
#{access_modifier}
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
def foo; end
def bar; end
end
RUBY
expect_correction(<<~RUBY)
class Test
#{access_modifier} def foo; end
#{access_modifier} def bar; end
end
RUBY
end
it 'registers an offense when using a grouped access modifier declaration' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
class Test
def something_else; end
def a_method_that_is_public; end
#{access_modifier}
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
def my_other_private_method; end
def bar; end
end
RUBY
expect_correction(<<~RUBY)
class Test
def something_else; end
def a_method_that_is_public; end
#{access_modifier} def my_other_private_method; end
#{access_modifier} def bar; end
end
RUBY
end
end
context 'with `begin` parent node' do
it 'registers an offense when modifier and method definition are on different lines' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
%{access_modifier};
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
def foo
end
def bar
end
RUBY
expect_correction(<<~RUBY)
#{access_modifier} def foo
end
#{access_modifier} def bar
end
RUBY
end
it 'registers an offense when modifier and method definition are on the same line' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
%{access_modifier}; def foo; end
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
RUBY
expect_correction(<<~RUBY)
#{access_modifier} def foo; end
RUBY
end
it 'registers an offense when modifier and method definitions are on the same line' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
%{access_modifier}; def foo; end; def bar; end
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
RUBY
expect_correction(<<~RUBY)
#{access_modifier} def foo; end; #{access_modifier} def bar; end
RUBY
end
it 'registers an offense when modifier and method definitions and some other node are on the same line' do
expect_offense(<<~RUBY, access_modifier: access_modifier)
%{access_modifier}; def foo; end; some_method; def bar; end
^{access_modifier} `#{access_modifier}` should be inlined in method definitions.
RUBY
expect_correction(<<~RUBY)
#{access_modifier} def foo; end; some_method; #{access_modifier} def bar; end
RUBY
end
end
it_behaves_like 'always accepted', access_modifier
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/missing_respond_to_missing_spec.rb | spec/rubocop/cop/style/missing_respond_to_missing_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MissingRespondToMissing, :config do
it 'registers an offense when respond_to_missing? is not implemented' do
expect_offense(<<~RUBY)
class Test
def method_missing
^^^^^^^^^^^^^^^^^^ When using `method_missing`, define `respond_to_missing?`.
end
end
RUBY
end
it 'registers an offense when method_missing is implemented as a class methods' do
expect_offense(<<~RUBY)
class Test
def self.method_missing
^^^^^^^^^^^^^^^^^^^^^^^ When using `method_missing`, define `respond_to_missing?`.
end
end
RUBY
end
it 'allows method_missing and respond_to_missing? implemented as instance methods' do
expect_no_offenses(<<~RUBY)
class Test
def respond_to_missing?
end
def method_missing
end
end
RUBY
end
it 'allows method_missing and respond_to_missing? implemented as class methods' do
expect_no_offenses(<<~RUBY)
class Test
def self.respond_to_missing?
end
def self.method_missing
end
end
RUBY
end
it 'allows method_missing and respond_to_missing? when defined with inline access modifier' do
expect_no_offenses(<<~RUBY)
class Test
private def respond_to_missing?
end
private def method_missing
end
end
RUBY
end
it 'allows method_missing and respond_to_missing? when defined with inline access modifier and ' \
'method_missing is not qualified by inline access modifier' do
expect_no_offenses(<<~RUBY)
class Test
private def respond_to_missing?
end
def method_missing
end
end
RUBY
end
it 'registers an offense respond_to_missing? is implemented as ' \
'an instance method and method_missing is implemented as a class method' do
expect_offense(<<~RUBY)
class Test
def self.method_missing
^^^^^^^^^^^^^^^^^^^^^^^ When using `method_missing`, define `respond_to_missing?`.
end
def respond_to_missing?
end
end
RUBY
end
it 'registers an offense respond_to_missing? is implemented as ' \
'a class method and method_missing is implemented as an instance method' do
expect_offense(<<~RUBY)
class Test
def self.respond_to_missing?
end
def method_missing
^^^^^^^^^^^^^^^^^^ When using `method_missing`, define `respond_to_missing?`.
end
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb | spec/rubocop/cop/style/multiline_ternary_operator_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineTernaryOperator, :config do
it 'registers an offense and corrects when the if branch and the else branch are ' \
'on a separate line from the condition' do
expect_offense(<<~RUBY)
a = cond ?
^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
b : c
RUBY
expect_correction(<<~RUBY)
a = if cond
b
else
c
end
RUBY
end
it 'registers an offense and corrects when the false branch is on a separate line and assigning a return value' do
expect_offense(<<~RUBY)
a = cond ? b :
^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
c
RUBY
expect_correction(<<~RUBY)
a = if cond
b
else
c
end
RUBY
end
it 'registers an offense and corrects when the false branch is on a separate line' do
expect_offense(<<~RUBY)
cond ? b :
^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
c
RUBY
expect_correction(<<~RUBY)
if cond
b
else
c
end
RUBY
end
it 'registers an offense and corrects when nesting multiline ternary operators' do
expect_offense(<<~RUBY)
cond_a? ? foo :
^^^^^^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
cond_b? ? bar :
^^^^^^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
cond_c? ? baz : qux
RUBY
expect_correction(<<~RUBY)
if cond_a?
foo
else
if cond_b?
bar
else
cond_c? ? baz : qux
end
end
RUBY
end
it 'registers an offense and corrects when everything is on a separate line' do
expect_offense(<<~RUBY)
a = cond ?
^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
b :
c
RUBY
expect_correction(<<~RUBY)
a = if cond
b
else
c
end
RUBY
end
it 'registers an offense and corrects when condition is multiline' do
expect_offense(<<~RUBY)
a =
b ==
^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
c ? d : e
RUBY
expect_correction(<<~RUBY)
a =
if b ==
c
d
else
e
end
RUBY
end
it 'registers an offense and corrects when condition is multiline and using hash key assignment' do
expect_offense(<<~RUBY)
a[:a] =
b ==
^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
c ? d : e
RUBY
expect_correction(<<~RUBY)
a[:a] =
if b ==
c
d
else
e
end
RUBY
end
it 'registers an offense and corrects when condition is multiline and using assignment method' do
expect_offense(<<~RUBY)
a.foo =
b ==
^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
c ? d : e
RUBY
expect_correction(<<~RUBY)
a.foo =
if b ==
c
d
else
e
end
RUBY
end
it 'does not register an offense when using a method call as a ternary operator condition with a line break ' \
'between receiver and method' do
# NOTE: Redundant line break is corrected by `Layout/RedundantLineBreak`.
expect_no_offenses(<<~RUBY)
do_something(arg
.foo ? bar : baz)
RUBY
end
it 'registers an offense and corrects when returning a multiline ternary operator expression with `return`' do
expect_offense(<<~RUBY)
return cond ?
^^^^^^ Avoid multi-line ternary operators, use single-line instead.
foo :
bar
RUBY
expect_correction(<<~RUBY)
return cond ? foo : bar
RUBY
end
context 'Ruby <= 3.2', :ruby32, unsupported_on: :prism do
it 'registers an offense and corrects when returning a multiline ternary operator expression with `break`' do
expect_offense(<<~RUBY)
break cond ?
^^^^^^ Avoid multi-line ternary operators, use single-line instead.
foo :
bar
RUBY
expect_correction(<<~RUBY)
break cond ? foo : bar
RUBY
end
it 'registers an offense and corrects when returning a multiline ternary operator expression with `next`' do
expect_offense(<<~RUBY)
next cond ?
^^^^^^ Avoid multi-line ternary operators, use single-line instead.
foo :
bar
RUBY
expect_correction(<<~RUBY)
next cond ? foo : bar
RUBY
end
end
it 'registers an offense and corrects when returning a multiline ternary operator expression with method call' do
expect_offense(<<~RUBY)
do_something cond ?
^^^^^^ Avoid multi-line ternary operators, use single-line instead.
foo :
bar
RUBY
expect_correction(<<~RUBY)
do_something cond ? foo : bar
RUBY
end
it 'registers an offense and corrects when returning a multiline ternary operator expression with safe navigation method call' do
expect_offense(<<~RUBY)
obj&.do_something cond ?
^^^^^^ Avoid multi-line ternary operators, use single-line instead.
foo :
bar
RUBY
expect_correction(<<~RUBY)
obj&.do_something cond ? foo : bar
RUBY
end
it 'accepts a single line ternary operator expression' do
expect_no_offenses('a = cond ? b : c')
end
it 'registers an offense and corrects when the if branch and the else branch are ' \
'on a separate line from the condition and not contains a comment' do
expect_offense(<<~RUBY)
# comment a
a = cond ?
^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
b : c # comment b
# comment c
RUBY
expect_correction(<<~RUBY)
# comment a
a = if cond
b
else
c
end # comment b
# comment c
RUBY
end
it 'registers an offense and corrects when if branch and the else branch are ' \
'on a separate line from the condition and contains a comment' do
expect_offense(<<~RUBY)
a = cond ? # comment a
^^^^^^^^^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
# comment b
b : c
a = cond ?
^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
b : # comment
c
a = cond ? b : # comment
^^^^^^^^^^^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
c
RUBY
expect_correction(<<~RUBY)
# comment a
# comment b
a = if cond
b
else
c
end
# comment
a = if cond
b
else
c
end
# comment
a = if cond
b
else
c
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/swap_values_spec.rb | spec/rubocop/cop/style/swap_values_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SwapValues, :config do
shared_examples 'verbosely swapping' do |type, x, y, correction|
it "registers an offense and corrects when verbosely swapping #{type} variables" do
expect_offense(<<~RUBY, x: x)
tmp = %{x}
^^^^^^^{x} Replace this and assignments at lines 2 and 3 with `#{correction}`.
#{x} = #{y}
#{y} = tmp
RUBY
expect_correction(<<~RUBY)
#{correction}
RUBY
end
end
it_behaves_like('verbosely swapping', 'local', 'x', 'y', 'x, y = y, x')
it_behaves_like('verbosely swapping', 'global', '$x', '$y', '$x, $y = $y, $x')
it_behaves_like('verbosely swapping', 'instance', '@x', '@y', '@x, @y = @y, @x')
it_behaves_like('verbosely swapping', 'class', '@@x', '@@y', '@@x, @@y = @@y, @@x')
it_behaves_like('verbosely swapping', 'constant', 'X', 'Y', 'X, Y = Y, X')
it_behaves_like('verbosely swapping', 'constant with namespaces',
'::X', 'Foo::Y', '::X, Foo::Y = Foo::Y, ::X')
it_behaves_like('verbosely swapping', 'mixed', '@x', '$y', '@x, $y = $y, @x')
it 'handles comments when correcting' do
expect_offense(<<~RUBY)
tmp = x # comment 1
^^^^^^^ Replace this and assignments at lines 3 and 4 with `x, y = y, x`.
# comment 2
x = y
y = tmp # comment 3
RUBY
expect_correction(<<~RUBY)
x, y = y, x
RUBY
end
it 'does not register an offense when idiomatically swapping variables' do
expect_no_offenses(<<~RUBY)
x, y = y, x
RUBY
end
it 'does not register an offense when almost swapping variables' do
expect_no_offenses(<<~RUBY)
tmp = x
x = y
y = not_a_tmp
RUBY
end
it 'does not register an offense when assigning receiver object at `def`' do
expect_no_offenses(<<~RUBY)
def (foo = Object.new).do_something
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_sort_spec.rb | spec/rubocop/cop/style/redundant_sort_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantSort, :config do
it 'registers an offense when first is called with sort' do
expect_offense(<<~RUBY)
[1, 2, 3].sort.first
^^^^^^^^^^ Use `min` instead of `sort...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min
RUBY
end
it 'registers an offense when `first` is called with safe navigation `sort`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.sort.first
^^^^^^^^^^ Use `min` instead of `sort...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.min
RUBY
end
it 'registers an offense when `first` is safe navigation called with safe navigation `sort`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.sort&.first
^^^^^^^^^^^ Use `min` instead of `sort...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.min
RUBY
end
it 'registers an offense when last is called with sort' do
expect_offense(<<~RUBY)
[1, 2].sort.last
^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY
expect_correction(<<~RUBY)
[1, 2].max
RUBY
end
it 'registers an offense when `last` is called with safe navigation `sort`' do
expect_offense(<<~RUBY)
[1, 2]&.sort.last
^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY
expect_correction(<<~RUBY)
[1, 2]&.max
RUBY
end
it 'registers an offense when `last` is safe navigation called with safe navigation `sort`' do
expect_offense(<<~RUBY)
[1, 2]&.sort&.last
^^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY
expect_correction(<<~RUBY)
[1, 2]&.max
RUBY
end
it 'registers an offense when last is called on sort with comparator' do
expect_offense(<<~RUBY)
foo.sort { |a, b| b <=> a }.last
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY
expect_correction(<<~RUBY)
foo.max { |a, b| b <=> a }
RUBY
end
it 'registers an offense when `last` is called on safe navigation `sort` with comparator' do
expect_offense(<<~RUBY)
foo&.sort { |a, b| b <=> a }.last
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY
expect_correction(<<~RUBY)
foo&.max { |a, b| b <=> a }
RUBY
end
it 'registers an offense when `last` is safe navigation called on safe navigation `sort` with comparator' do
expect_offense(<<~RUBY)
foo&.sort { |a, b| b <=> a }&.last
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY
expect_correction(<<~RUBY)
foo&.max { |a, b| b <=> a }
RUBY
end
it 'registers an offense when first is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by { |x| x.length }.first
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min_by { |x| x.length }
RUBY
end
it 'registers an offense when `first` is called on safe navigation `sort_by`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.sort_by { |x| x.length }.first
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.min_by { |x| x.length }
RUBY
end
it 'registers an offense when `first` is safe navigation called on safe navigation `sort_by`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.sort_by { |x| x.length }&.first
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.min_by { |x| x.length }
RUBY
end
it 'registers an offense when last is called on sort_by' do
expect_offense(<<~RUBY)
foo.sort_by { |x| x.something }.last
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `max_by` instead of `sort_by...last`.
RUBY
expect_correction(<<~RUBY)
foo.max_by { |x| x.something }
RUBY
end
it 'registers an offense when first is called on sort_by with line breaks' do
expect_offense(<<~RUBY)
[1, 2, 3]
.sort_by { |x| x.length }
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
.first
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]
.min_by { |x| x.length }
#{' '}
RUBY
end
it 'registers an offense when first is called on sort_by with line breaks and `||` operator' do
expect_offense(<<~RUBY)
[1, 2, 3]
.sort_by { |x| x.length }
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
.first || []
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]
.min_by { |x| x.length } ||
[]
RUBY
end
it 'registers an offense when first is called on sort_by with line breaks and `&&` operator' do
expect_offense(<<~RUBY)
[1, 2, 3]
.sort_by { |x| x.length }
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
.first && []
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]
.min_by { |x| x.length } &&
[]
RUBY
end
it 'registers an offense when first is called on sort_by with line breaks and `or` operator' do
expect_offense(<<~RUBY)
[1, 2, 3]
.sort_by { |x| x.length }
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
.first or []
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]
.min_by { |x| x.length } or
[]
RUBY
end
it 'registers an offense when first is called on sort_by with line breaks and `and` operator' do
expect_offense(<<~RUBY)
[1, 2, 3]
.sort_by { |x| x.length }
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
.first and []
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]
.min_by { |x| x.length } and
[]
RUBY
end
it 'registers an offense when first is called on sort_by no block' do
expect_offense(<<~RUBY)
[1, 2].sort_by(&:something).first
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2].min_by(&:something)
RUBY
end
it 'registers an offense when last is called on sort_by no block' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by(&:length).last
^^^^^^^^^^^^^^^^^^^^^^ Use `max_by` instead of `sort_by...last`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].max_by(&:length)
RUBY
end
it 'registers an offense when at(-1) is called with sort' do
expect_offense(<<~RUBY)
[1, 2].sort.at(-1)
^^^^^^^^^^^ Use `max` instead of `sort...at(-1)`.
RUBY
expect_correction(<<~RUBY)
[1, 2].max
RUBY
end
it 'registers an offense when `at(-1)` is with safe navigation `sort`' do
expect_offense(<<~RUBY)
[1, 2]&.sort.at(-1)
^^^^^^^^^^^ Use `max` instead of `sort...at(-1)`.
RUBY
expect_correction(<<~RUBY)
[1, 2]&.max
RUBY
end
it 'registers an offense when `at(-1)` is safe navigation called with safe navigation `sort`' do
expect_offense(<<~RUBY)
[1, 2]&.sort&.at(-1)
^^^^^^^^^^^^ Use `max` instead of `sort...at(-1)`.
RUBY
expect_correction(<<~RUBY)
[1, 2]&.max
RUBY
end
it 'registers an offense when slice(0) is called on sort' do
expect_offense(<<~RUBY)
[1, 2, 3].sort.slice(0)
^^^^^^^^^^^^^ Use `min` instead of `sort...slice(0)`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min
RUBY
end
it 'registers an offense when [0] is called on sort' do
expect_offense(<<~RUBY)
[1, 2, 3].sort[0]
^^^^^^^ Use `min` instead of `sort...[0]`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min
RUBY
end
it 'registers an offense when [](0) is called on sort' do
expect_offense(<<~RUBY)
[1, 2, 3].sort.[](0)
^^^^^^^^^^ Use `min` instead of `sort...[](0)`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min
RUBY
end
it 'registers an offense when [](-1) is called on sort_by' do
expect_offense(<<~RUBY)
foo.sort_by { |x| x.foo }.[](-1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `max_by` instead of `sort_by...[](-1)`.
RUBY
expect_correction(<<~RUBY)
foo.max_by { |x| x.foo }
RUBY
end
it 'registers an offense when at(0) is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by(&:foo).at(0)
^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...at(0)`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min_by(&:foo)
RUBY
end
it 'registers an offense when slice(0) is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2].sort_by(&:foo).slice(0)
^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...slice(0)`.
RUBY
expect_correction(<<~RUBY)
[1, 2].min_by(&:foo)
RUBY
end
it 'registers an offense when slice(-1) is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by(&:foo).slice(-1)
^^^^^^^^^^^^^^^^^^^^^^^^ Use `max_by` instead of `sort_by...slice(-1)`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].max_by(&:foo)
RUBY
end
it 'registers an offense when [-1] is called on sort' do
expect_offense(<<~RUBY)
[1, 2, 3].sort[-1]
^^^^^^^^ Use `max` instead of `sort...[-1]`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].max
RUBY
end
it 'registers an offense when [0] is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2].sort_by(&:foo)[0]
^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...[0]`.
RUBY
expect_correction(<<~RUBY)
[1, 2].min_by(&:foo)
RUBY
end
it 'registers an offense when [-1] is called on sort_by' do
expect_offense(<<~RUBY)
foo.sort_by { |x| x.foo }[-1]
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `max_by` instead of `sort_by...[-1]`.
RUBY
expect_correction(<<~RUBY)
foo.max_by { |x| x.foo }
RUBY
end
# Arguments get too complicated to handle easily, e.g.
# '[1, 2, 3].sort.last(2)' is not equivalent to '[1, 2, 3].max(2)',
# so we don't register an offense.
it 'does not register an offense when first has an argument' do
expect_no_offenses('[1, 2, 3].sort.first(1)')
end
# Some gems like mongo provides sort method with an argument
it 'does not register an offense when sort has an argument' do
expect_no_offenses('mongo_client["users"].find.sort(_id: 1).first')
end
it 'does not register an offense for sort!.first' do
expect_no_offenses('[1, 2, 3].sort!.first')
end
it 'does not register an offense for sort_by!(&:something).last' do
expect_no_offenses('[1, 2, 3].sort_by!(&:something).last')
end
it 'does not register an offense when sort_by is used without first' do
expect_no_offenses('[1, 2, 3].sort_by { |x| -x }')
end
it 'does not register an offense when first is used without sort_by' do
expect_no_offenses('[1, 2, 3].first')
end
it 'does not register an offense when first is used before sort' do
expect_no_offenses('[[1, 2], [3, 4]].first.sort')
end
# `[2, 1, 3].sort_by(&:size).first` is not equivalent to `[2, 1, 3].first`, but this
# cop would "correct" it to `[2, 1, 3].min_by`.
it 'does not register an offense when sort_by is not given a block' do
expect_no_offenses('[2, 1, 3].sort_by.first')
end
it 'registers an offense with `sort_by { a || b }`' do
expect_offense(<<~RUBY)
x.sort_by { |y| y.foo || bar }.last
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `max_by` instead of `sort_by...last`.
RUBY
expect_correction(<<~RUBY)
x.max_by { |y| y.foo || bar }
RUBY
end
context 'when not taking first or last element' do
it 'does not register an offense when [1] is called on sort' do
expect_no_offenses('[1, 2, 3].sort[1]')
end
it 'does not register an offense when at(-2) is called on sort_by' do
expect_no_offenses('[1, 2, 3].sort_by(&:foo).at(-2)')
end
it 'does not register an offense when [-1] is called on sort with an argument' do
expect_no_offenses('mongo_client["users"].find.sort(_id: 1)[-1]')
end
end
context '>= Ruby 2.7', :ruby27 do
context 'when using numbered parameter' do
it 'registers an offense and corrects when last is called on sort with comparator' do
expect_offense(<<~RUBY)
foo.sort { _2 <=> _1 }.last
^^^^^^^^^^^^^^^^^^^^^^^ Use `max` instead of `sort...last`.
RUBY
expect_correction(<<~RUBY)
foo.max { _2 <=> _1 }
RUBY
end
it 'registers an offense and corrects when first is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by { _1.length }.first
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...first`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min_by { _1.length }
RUBY
end
it 'registers an offense and corrects when at(0) is called on sort_by' do
expect_offense(<<~RUBY)
[1, 2, 3].sort_by { _1.foo }.at(0)
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...at(0)`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].min_by { _1.foo }
RUBY
end
it 'registers an offense and corrects when `at(0)` is called on safe navigation `sort_by`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.sort_by { _1.foo }.at(0)
^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...at(0)`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.min_by { _1.foo }
RUBY
end
it 'registers an offense and corrects when `at(0)` is safe navigation called on safe navigation `sort_by`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.sort_by { _1.foo }&.at(0)
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `min_by` instead of `sort_by...at(0)`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.min_by { _1.foo }
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/multiline_block_chain_spec.rb | spec/rubocop/cop/style/multiline_block_chain_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineBlockChain, :config do
context 'with multi-line block chaining' do
it 'registers an offense for a simple case' do
expect_offense(<<~RUBY)
a do
b
end.c do
^^^^^ Avoid multi-line chains of blocks.
d
end
RUBY
end
it 'registers an offense for a simple case with safe navigation operator' do
expect_offense(<<~RUBY)
a do
b
end&.c do
^^^^^^ Avoid multi-line chains of blocks.
d
end
RUBY
end
it 'registers an offense for a slightly more complicated case' do
expect_offense(<<~RUBY)
a do
b
end.c1.c2 do
^^^^^^^^^ Avoid multi-line chains of blocks.
d
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for a slightly more complicated case' do
expect_offense(<<~RUBY)
a do
_1
end.c1.c2 do
^^^^^^^^^ Avoid multi-line chains of blocks.
_1
end
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for a slightly more complicated case' do
expect_offense(<<~RUBY)
a do
it
end.c1.c2 do
^^^^^^^^^ Avoid multi-line chains of blocks.
it
end
RUBY
end
end
it 'registers two offenses for a chain of three blocks' do
expect_offense(<<~RUBY)
a do
b
end.c do
^^^^^ Avoid multi-line chains of blocks.
d
end.e do
^^^^^ Avoid multi-line chains of blocks.
f
end
RUBY
end
it 'registers an offense for a chain where the second block is single-line' do
expect_offense(<<~RUBY)
Thread.list.find_all { |t|
t.alive?
}.map { |thread| thread.object_id }
^^^^^ Avoid multi-line chains of blocks.
RUBY
end
it 'accepts a chain where the first block is single-line' do
expect_no_offenses(<<~RUBY)
Thread.list.find_all { |t| t.alive? }.map { |t|
t.object_id
}
RUBY
end
end
it 'accepts a chain of blocks spanning one line' do
expect_no_offenses(<<~RUBY)
a { b }.c { d }
w do x end.y do z end
RUBY
end
it 'accepts a multi-line block chained with calls on one line' do
expect_no_offenses(<<~RUBY)
a do
b
end.c.d
RUBY
end
it 'accepts a chain of calls followed by a multi-line block' do
expect_no_offenses(<<~RUBY)
a1.a2.a3 do
b
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/if_with_boolean_literal_branches_spec.rb | spec/rubocop/cop/style/if_with_boolean_literal_branches_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::IfWithBooleanLiteralBranches, :config do
context 'when condition is a comparison method' do
RuboCop::AST::Node::COMPARISON_OPERATORS.each do |comparison_operator|
it 'registers and corrects an offense when using `if foo == bar` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo #{comparison_operator} bar
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo #{comparison_operator} bar
RUBY
end
it 'registers and corrects an offense when using `unless foo == bar` with boolean literal branches' do
expect_offense(<<~RUBY)
unless foo #{comparison_operator} bar
^^^^^^ Remove redundant `unless` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
foo #{comparison_operator} bar
RUBY
end
it 'registers and corrects an offense when using ternary operator with boolean literal branches' do
expect_offense(<<~RUBY, comparison_operator: comparison_operator)
foo #{comparison_operator} bar ? true : false
_{comparison_operator} ^^^^^^^^^^^^^^^ Remove redundant ternary operator with boolean literal branches.
RUBY
expect_correction(<<~RUBY)
foo #{comparison_operator} bar
RUBY
end
it 'registers and corrects an offense when using `if foo == bar` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
if foo #{comparison_operator} bar
^^ Remove redundant `if` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
!(foo #{comparison_operator} bar)
RUBY
end
it 'registers and corrects an offense when using `unless foo == bar` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
unless foo #{comparison_operator} bar
^^^^^^ Remove redundant `unless` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
!(foo #{comparison_operator} bar)
RUBY
end
it 'registers and corrects an offense when using opposite ternary operator with boolean literal branches' do
expect_offense(<<~RUBY, comparison_operator: comparison_operator)
foo #{comparison_operator} bar ? false : true
_{comparison_operator} ^^^^^^^^^^^^^^^ Remove redundant ternary operator with boolean literal branches.
RUBY
expect_correction(<<~RUBY)
!(foo #{comparison_operator} bar)
RUBY
end
it 'registers and corrects an offense when using `if` with boolean literal branches directly under `def`' do
expect_offense(<<~RUBY, comparison_operator: comparison_operator)
def foo
if bar > baz
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
end
RUBY
expect_correction(<<~RUBY)
def foo
bar > baz
end
RUBY
end
it 'does not register an offense when using a branch that is not boolean literal' do
expect_no_offenses(<<~RUBY)
if foo #{comparison_operator} bar
do_something
else
false
end
RUBY
end
end
end
context 'when condition is a predicate method' do
it 'registers and corrects an offense when using `if foo.do_something?` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo.do_something?
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo.do_something?
RUBY
end
it 'registers and corrects an offense when using `unless foo.do_something?` with boolean literal branches' do
expect_offense(<<~RUBY)
unless foo.do_something?
^^^^^^ Remove redundant `unless` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
foo.do_something?
RUBY
end
it 'registers and corrects an offense when using `if foo.do_something?` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
if foo.do_something?
^^ Remove redundant `if` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
!foo.do_something?
RUBY
end
it 'registers and corrects an offense when using `unless foo.do_something?` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
unless foo.do_something?
^^^^^^ Remove redundant `unless` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
!foo.do_something?
RUBY
end
it 'registers and corrects an offense when using `elsif foo.do_something?` with boolean literal branches' do
expect_offense(<<~RUBY)
if condition
bar
false
elsif foo.do_something?
^^^^^ Use `else` instead of redundant `elsif` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
if condition
bar
false
else
foo.do_something?
end
RUBY
end
it 'registers and corrects an offense when using `elsif foo.do_something?` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
if condition
bar
false
elsif foo.do_something?
^^^^^ Use `else` instead of redundant `elsif` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
if condition
bar
false
else
!foo.do_something?
end
RUBY
end
end
context 'when double negative is used in condition' do
it 'registers and corrects an offense when using `if !!condition` with boolean literal branches' do
expect_offense(<<~RUBY)
if !!condition
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
!!condition
RUBY
end
it 'registers and corrects an offense when using `if !!condition` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
if !!condition
^^ Remove redundant `if` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
!!!condition
RUBY
end
end
context 'when condition is a method that does not known whether to return boolean value' do
it 'does not register an offense when using `if condition` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if condition
true
else
false
end
RUBY
end
it 'does not register an offense when using `unless condition` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
unless condition
false
else
true
end
RUBY
end
it 'does not register an offense when using `if condition` with opposite boolean literal branches' do
expect_no_offenses(<<~RUBY)
if condition
false
else
true
end
RUBY
end
it 'does not register an offense when using `unless condition` with opposite boolean literal branches' do
expect_no_offenses(<<~RUBY)
unless condition
true
else
false
end
RUBY
end
end
context 'when condition is a logical operator and operands do not known whether to return boolean value' do
it 'does not register an offense when using `if foo && bar` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo && bar
true
else
false
end
RUBY
end
it 'does not register an offense when using `if foo || bar` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo || bar
true
else
false
end
RUBY
end
it 'does not register an offense when using `unless foo && bar` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
unless foo && bar
false
else
true
end
RUBY
end
it 'does not register an offense when using `unless foo || bar` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
unless foo || bar
false
else
true
end
RUBY
end
it 'does not register an offense when using `if foo && bar` with opposite boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo && bar
false
else
true
end
RUBY
end
it 'does not register an offense when using `if foo || bar` with opposite boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo || bar
false
else
true
end
RUBY
end
it 'does not register an offense when using `unless foo && bar` with opposite boolean literal branches' do
expect_no_offenses(<<~RUBY)
unless foo && bar
true
else
false
end
RUBY
end
it 'does not register an offense when using `unless foo || bar` with opposite boolean literal branches' do
expect_no_offenses(<<~RUBY)
unless foo || bar
true
else
false
end
RUBY
end
end
context 'when complex condition' do
it 'registers and corrects an offense when using `if foo? && bar && baz?` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo? && bar && baz?
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo? && bar && baz?
RUBY
end
it 'does not register an offense when using `if foo? || bar || baz?` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo? || bar || baz?
true
else
false
end
RUBY
end
it 'registers and corrects an offense when using `if foo? || bar && baz?` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo? || bar && baz?
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo? || bar && baz?
RUBY
end
it 'registers and corrects an offense when using `if foo? || (bar && baz)?` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo? || (bar && baz?)
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo? || (bar && baz?)
RUBY
end
it 'registers and corrects an offense when using `if (foo? || bar) && baz?` with boolean literal branches' do
expect_offense(<<~RUBY)
if (foo? || bar) && baz?
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
(foo? || bar) && baz?
RUBY
end
it 'does not register an offense when using `if foo? && bar || baz?` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo? && bar || baz?
true
else
false
end
RUBY
end
it 'does not register an offense when using `if foo? && (bar || baz)?` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo? && (bar || baz?)
true
else
false
end
RUBY
end
it 'does not register an offense when using `if (foo? && bar) || baz?` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if (foo? && bar) || baz?
true
else
false
end
RUBY
end
end
context 'when condition is a logical operator and all operands are predicate methods' do
it 'registers and corrects an offense when using `if foo? && bar?` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo? && bar?
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo? && bar?
RUBY
end
it 'registers and corrects an offense when using `if foo? && bar?` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
if foo? && bar?
^^ Remove redundant `if` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
!(foo? && bar?)
RUBY
end
it 'registers and corrects an offense when using `unless foo? || bar?` with boolean literal branches' do
expect_offense(<<~RUBY)
unless foo? || bar?
^^^^^^ Remove redundant `unless` with boolean literal branches.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
foo? || bar?
RUBY
end
it 'registers and corrects an offense when using `unless foo? || bar?` with opposite boolean literal branches' do
expect_offense(<<~RUBY)
unless foo? || bar?
^^^^^^ Remove redundant `unless` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
!(foo? || bar?)
RUBY
end
it 'registers and corrects an offense when using `if foo? && bar? && baz?` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo? && bar? && baz?
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo? && bar? && baz?
RUBY
end
it 'registers and corrects an offense when using `if foo? && bar? || baz?` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo? && bar? || baz?
^^ Remove redundant `if` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
foo? && bar? || baz?
RUBY
end
end
context 'when using `elsif` with boolean literal branches' do
it 'registers and corrects an offense when using single `elsif` with boolean literal branches' do
expect_offense(<<~RUBY)
if foo
true
elsif bar > baz
^^^^^ Use `else` instead of redundant `elsif` with boolean literal branches.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
if foo
true
else
bar > baz
end
RUBY
end
it 'does not register an offense when using multiple `elsif` with boolean literal branches' do
expect_no_offenses(<<~RUBY)
if foo
true
elsif bar > baz
true
elsif qux > quux
true
else
false
end
RUBY
end
end
it 'does not crash when using `()` as a condition' do
expect_no_offenses(<<~RUBY)
if ()
else
end
RUBY
end
context 'when `AllowedMethods: nonzero?`' do
let(:cop_config) { { 'AllowedMethods' => ['nonzero?'] } }
it 'does not register an offense when using `nonzero?`' do
expect_no_offenses(<<~RUBY)
num.nonzero? ? true : false
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trailing_comma_in_block_args_spec.rb | spec/rubocop/cop/style/trailing_comma_in_block_args_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrailingCommaInBlockArgs, :config do
context 'curly brace block format' do
it 'registers an offense when a trailing comma is not needed' do
expect_offense(<<~RUBY)
test { |a, b,| a + b }
^ Useless trailing comma present in block arguments.
RUBY
expect_correction(<<~RUBY)
test { |a, b| a + b }
RUBY
end
it 'does not register an offense when a trailing comma is required' do
expect_no_offenses(<<~RUBY)
test { |a,| a }
RUBY
end
it 'does not register an offense when no arguments are present' do
expect_no_offenses(<<~RUBY)
test { a }
RUBY
end
it 'does not register an offense when more than one argument is ' \
'present with no trailing comma' do
expect_no_offenses(<<~RUBY)
test { |a, b| a + b }
RUBY
end
it 'does not register an offense for default arguments' do
expect_no_offenses(<<~RUBY)
test { |a, b, c = nil| a + b + c }
RUBY
end
it 'does not register an offense for keyword arguments' do
expect_no_offenses(<<~RUBY)
test { |a, b, c: 1| a + b + c }
RUBY
end
it 'ignores commas in default argument strings' do
expect_no_offenses(<<~RUBY)
add { |foo, bar = ','| foo + bar }
RUBY
end
it 'preserves semicolons in block/local variables' do
expect_no_offenses(<<~RUBY)
add { |foo, bar,; baz| foo + bar }
RUBY
end
end
context 'do/end block format' do
it 'registers an offense when a trailing comma is not needed' do
expect_offense(<<~RUBY)
test do |a, b,|
^ Useless trailing comma present in block arguments.
a + b
end
RUBY
expect_correction(<<~RUBY)
test do |a, b|
a + b
end
RUBY
end
it 'does not register an offense when a trailing comma is required' do
expect_no_offenses(<<~RUBY)
test do |a,|
a
end
RUBY
end
it 'does not register an offense when no arguments are present' do
expect_no_offenses(<<~RUBY)
test do
a
end
RUBY
end
it 'does not register an offense for an empty block' do
expect_no_offenses(<<~RUBY)
test do ||
end
RUBY
end
it 'does not register an offense when more than one argument is ' \
'present with no trailing comma' do
expect_no_offenses(<<~RUBY)
test do |a, b|
a + b
end
RUBY
end
it 'does not register an offense for default arguments' do
expect_no_offenses(<<~RUBY)
test do |a, b, c = nil|
a + b + c
end
RUBY
end
it 'does not register an offense for keyword arguments' do
expect_no_offenses(<<~RUBY)
test do |a, b, c: 1|
a + b + c
end
RUBY
end
it 'ignores commas in default argument strings' do
expect_no_offenses(<<~RUBY)
add do |foo, bar = ','|
foo + bar
end
RUBY
end
it 'preserves semicolons in block/local variables' do
expect_no_offenses(<<~RUBY)
add do |foo, bar,; baz|
foo + bar
end
RUBY
end
end
context 'when `->` has multiple arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
-> (foo, bar) { do_something(foo, bar) }
RUBY
end
end
context 'when `lambda` has multiple arguments' do
it 'does not register an offense when more than one argument is ' \
'present with no trailing comma' do
expect_no_offenses(<<~RUBY)
lambda { |foo, bar| do_something(foo, bar) }
RUBY
end
it "registers an offense and corrects when a trailing comma isn't needed" do
expect_offense(<<~RUBY)
lambda { |foo, bar,| do_something(foo, bar) }
^ Useless trailing comma present in block arguments.
RUBY
expect_correction(<<~RUBY)
lambda { |foo, bar| do_something(foo, bar) }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/attr_spec.rb | spec/rubocop/cop/style/attr_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Attr, :config do
it 'registers an offense attr' do
expect_offense(<<~RUBY)
class SomeClass
attr :name
^^^^ Do not use `attr`. Use `attr_reader` instead.
end
RUBY
end
it 'registers an offense for attr within class_eval' do
expect_offense(<<~RUBY)
SomeClass.class_eval do
attr :name
^^^^ Do not use `attr`. Use `attr_reader` instead.
end
RUBY
end
it 'registers an offense for attr within module_eval' do
expect_offense(<<~RUBY)
SomeClass.module_eval do
attr :name
^^^^ Do not use `attr`. Use `attr_reader` instead.
end
RUBY
end
it 'registers an offense when using `attr` and method definitions' do
expect_offense(<<~RUBY)
class SomeClass
attr :name
^^^^ Do not use `attr`. Use `attr_reader` instead.
def foo
end
end
RUBY
end
it 'accepts attr when it does not take arguments' do
expect_no_offenses('func(attr)')
end
it 'accepts attr when it has a receiver' do
expect_no_offenses('x.attr arg')
end
it 'does not register offense for custom `attr` method' do
expect_no_offenses(<<~RUBY)
class SomeClass
def attr(*args)
p args
end
def a
attr(1)
end
end
RUBY
end
context 'autocorrects' do
it 'attr to attr_reader' do
expect_offense(<<~RUBY)
attr :name
^^^^ Do not use `attr`. Use `attr_reader` instead.
RUBY
expect_correction(<<~RUBY)
attr_reader :name
RUBY
end
it 'attr, false to attr_reader' do
expect_offense(<<~RUBY)
attr :name, false
^^^^ Do not use `attr`. Use `attr_reader` instead.
RUBY
expect_correction(<<~RUBY)
attr_reader :name
RUBY
end
it 'attr :name, true to attr_accessor :name' do
expect_offense(<<~RUBY)
attr :name, true
^^^^ Do not use `attr`. Use `attr_accessor` instead.
RUBY
expect_correction(<<~RUBY)
attr_accessor :name
RUBY
end
it 'attr with multiple names to attr_reader' do
expect_offense(<<~RUBY)
attr :foo, :bar
^^^^ Do not use `attr`. Use `attr_reader` instead.
RUBY
expect_correction(<<~RUBY)
attr_reader :foo, :bar
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/negated_unless_spec.rb | spec/rubocop/cop/style/negated_unless_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NegatedUnless do
subject(:cop) do
config = RuboCop::Config.new(
'Style/NegatedUnless' => {
'SupportedStyles' => %w[both prefix postfix],
'EnforcedStyle' => 'both'
}
)
described_class.new(config)
end
describe 'with “both” style' do
it 'registers an offense for unless with exclamation point condition' do
expect_offense(<<~RUBY)
unless !a_condition
^^^^^^^^^^^^^^^^^^^ Favor `if` over `unless` for negative conditions.
some_method
end
some_method unless !a_condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `if` over `unless` for negative conditions.
RUBY
expect_correction(<<~RUBY)
if a_condition
some_method
end
some_method if a_condition
RUBY
end
it 'registers an offense for unless with "not" condition' do
expect_offense(<<~RUBY)
unless not a_condition
^^^^^^^^^^^^^^^^^^^^^^ Favor `if` over `unless` for negative conditions.
some_method
end
some_method unless not a_condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `if` over `unless` for negative conditions.
RUBY
expect_correction(<<~RUBY)
if a_condition
some_method
end
some_method if a_condition
RUBY
end
it 'accepts an unless/else with negative condition' do
expect_no_offenses(<<~RUBY)
unless !a_condition
some_method
else
something_else
end
RUBY
end
it 'accepts an unless where only part of the condition is negated' do
expect_no_offenses(<<~RUBY)
unless !condition && another_condition
some_method
end
unless not condition or another_condition
some_method
end
some_method unless not condition or another_condition
RUBY
end
it 'accepts an unless where the condition is doubly negated' do
expect_no_offenses(<<~RUBY)
unless !!condition
some_method
end
some_method unless !!condition
RUBY
end
it 'autocorrects by replacing parenthesized unless not with if' do
expect_offense(<<~RUBY)
something unless (!x.even?)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `if` over `unless` for negative conditions.
RUBY
expect_correction(<<~RUBY)
something if (x.even?)
RUBY
end
end
describe 'with “prefix” style' do
subject(:cop) do
config = RuboCop::Config.new(
'Style/NegatedUnless' => {
'SupportedStyles' => %w[both prefix postfix],
'EnforcedStyle' => 'prefix'
}
)
described_class.new(config)
end
it 'registers an offense for prefix' do
expect_offense(<<~RUBY)
unless !foo
^^^^^^^^^^^ Favor `if` over `unless` for negative conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo
end
RUBY
end
it 'does not register an offense for postfix' do
expect_no_offenses('foo unless !bar')
end
end
describe 'with “postfix” style' do
subject(:cop) do
config = RuboCop::Config.new(
'Style/NegatedUnless' => {
'SupportedStyles' => %w[both prefix postfix],
'EnforcedStyle' => 'postfix'
}
)
described_class.new(config)
end
it 'registers an offense for postfix' do
expect_offense(<<~RUBY)
foo unless !bar
^^^^^^^^^^^^^^^ Favor `if` over `unless` for negative conditions.
RUBY
expect_correction(<<~RUBY)
foo if bar
RUBY
end
it 'does not register an offense for prefix' do
expect_no_offenses(<<~RUBY)
unless !foo
end
RUBY
end
end
it 'does not blow up for ternary ops' do
expect_no_offenses('a ? b : c')
end
it 'does not blow up on a negated ternary operator' do
expect_no_offenses('!foo.empty? ? :bar : :baz')
end
it 'does not blow up for empty if condition' do
expect_no_offenses(<<~RUBY)
if ()
end
RUBY
end
it 'does not blow up for empty unless condition' do
expect_no_offenses(<<~RUBY)
unless ()
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/multiline_if_modifier_spec.rb | spec/rubocop/cop/style/multiline_if_modifier_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineIfModifier, :config do
context 'if guard clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
{
^ Favor a normal if-statement over a modifier clause in a multiline statement.
result: run
} if cond
RUBY
expect_correction(<<~RUBY)
if cond
{
result: run
}
end
RUBY
end
it 'allows a one liner' do
expect_no_offenses(<<~RUBY)
run if cond
RUBY
end
it 'allows a multiline condition' do
expect_no_offenses(<<~RUBY)
run if cond &&
cond2
RUBY
end
it 'registers an offense when indented' do
expect_offense(<<-RUBY.strip_margin('|'))
| {
| ^ Favor a normal if-statement over a modifier clause in a multiline statement.
| result: run
| } if cond
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| if cond
| {
| result: run
| }
| end
RUBY
end
it 'registers an offense when nested modifier' do
expect_offense(<<~RUBY)
[
^ Favor a normal if-statement over a modifier clause in a multiline statement.
] if inner if outer
RUBY
expect_correction(<<~RUBY)
if outer
if inner
[
]
end
end
RUBY
end
end
context 'unless guard clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
{
^ Favor a normal unless-statement over a modifier clause in a multiline statement.
result: run
} unless cond
RUBY
expect_correction(<<~RUBY)
unless cond
{
result: run
}
end
RUBY
end
it 'allows a one liner' do
expect_no_offenses(<<~RUBY)
run unless cond
RUBY
end
it 'allows a multiline condition' do
expect_no_offenses(<<~RUBY)
run unless cond &&
cond2
RUBY
end
it 'registers an offense when indented' do
expect_offense(<<-RUBY.strip_margin('|'))
| {
| ^ Favor a normal unless-statement over a modifier clause in a multiline statement.
| result: run
| } unless cond
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| unless cond
| {
| result: run
| }
| end
RUBY
end
it 'registers an offense when nested modifier' do
expect_offense(<<~RUBY)
[
^ Favor a normal unless-statement over a modifier clause in a multiline statement.
] unless inner unless outer
RUBY
expect_correction(<<~RUBY)
unless outer
unless inner
[
]
end
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/module_member_existence_check_spec.rb | spec/rubocop/cop/style/module_member_existence_check_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ModuleMemberExistenceCheck, :config do
it 'registers an offense when using `.instance_methods.include?(method)`' do
expect_offense(<<~RUBY)
x.instance_methods.include?(method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method)` instead.
RUBY
expect_correction(<<~RUBY)
x.method_defined?(method)
RUBY
end
it 'registers an offense when using `.instance_methods.include? method`' do
expect_offense(<<~RUBY)
x.instance_methods.include? method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method)` instead.
RUBY
expect_correction(<<~RUBY)
x.method_defined?(method)
RUBY
end
it 'registers an offense when using `.instance_methods.member?(method)`' do
expect_offense(<<~RUBY)
x.instance_methods.member?(method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method)` instead.
RUBY
expect_correction(<<~RUBY)
x.method_defined?(method)
RUBY
end
it 'registers an offense when using `&.instance_methods&.include?(method)`' do
expect_offense(<<~RUBY)
x&.instance_methods&.include?(method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method)` instead.
RUBY
expect_correction(<<~RUBY)
x&.method_defined?(method)
RUBY
end
it 'registers an offense when using `instance_methods.include?(method)`' do
expect_offense(<<~RUBY)
instance_methods.include?(method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method)` instead.
RUBY
expect_correction(<<~RUBY)
method_defined?(method)
RUBY
end
it 'registers an offense when using `.instance_methods(false).include?(method)`' do
expect_offense(<<~RUBY)
x.instance_methods(false).include?(method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method, false)` instead.
RUBY
expect_correction(<<~RUBY)
x.method_defined?(method, false)
RUBY
end
it 'registers an offense when using `.instance_methods(true).include?(method)`' do
expect_offense(<<~RUBY)
x.instance_methods(true).include?(method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method)` instead.
RUBY
expect_correction(<<~RUBY)
x.method_defined?(method)
RUBY
end
it 'registers an offense when using `.instance_methods(inherit).include?(method)`' do
expect_offense(<<~RUBY)
x.instance_methods(inherit).include?(method)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `method_defined?(method, inherit)` instead.
RUBY
expect_correction(<<~RUBY)
x.method_defined?(method, inherit)
RUBY
end
it 'does not register an offense when passing more than one argument to `instance_methods`' do
expect_no_offenses(<<~RUBY)
x.instance_methods(true, false).include?(method)
RUBY
end
it 'does not register an offense when passing more than one argument to `include?`' do
expect_no_offenses(<<~RUBY)
x.instance_methods.include?(foo, bar)
RUBY
end
it 'does not register an offense when passing a splat argument to `include?`' do
expect_no_offenses(<<~RUBY)
x.instance_methods.include?(*foo)
RUBY
end
it 'does not register an offense when passing a kwargs argument to `include?`' do
expect_no_offenses(<<~RUBY)
x.instance_methods.include?(**foo)
RUBY
end
it 'does not register an offense when passing a block argument to `include?`' do
expect_no_offenses(<<~RUBY)
x.instance_methods.include?(&foo)
RUBY
end
it 'does not register an offense when passing a splat argument to `instance_methods`' do
expect_no_offenses(<<~RUBY)
x.instance_methods(*foo).include?(method)
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/hash_syntax_spec.rb | spec/rubocop/cop/style/hash_syntax_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashSyntax, :config do
context 'configured to enforce ruby19 style' do
context 'with SpaceAroundOperators enabled' do
let(:config) do
RuboCop::Config.new('AllCops' => {
'TargetRubyVersion' => ruby_version
},
'Style/HashSyntax' => cop_config,
'Layout/SpaceAroundOperators' => {
'Enabled' => true
})
end
let(:cop_config) do
{
'EnforcedStyle' => 'ruby19',
'SupportedStyles' => %w[ruby19 hash_rockets],
'EnforcedShorthandSyntax' => 'always',
'SupportedShorthandSyntax' => %w[always never],
'UseHashRocketsWithSymbolValues' => false,
'PreferHashRocketsForNonAlnumEndingSymbols' => false
}.merge(cop_config_overrides)
end
let(:cop_config_overrides) { {} }
it 'registers an offense for hash rocket syntax when new is possible' do
expect_offense(<<~RUBY)
x = { :a => 0, :b => 2}
^^^^^ Use the new Ruby 1.9 hash syntax.
^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { a: 0, b: 2}
RUBY
end
it 'registers an offense for mixed syntax when new is possible' do
expect_offense(<<~RUBY)
x = { :a => 0, b: 1 }
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { a: 0, b: 1 }
RUBY
end
it 'registers an offense for hash rockets in method calls' do
expect_offense(<<~RUBY)
func(3, :a => 0)
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
func(3, a: 0)
RUBY
end
it 'accepts hash rockets when keys have different types' do
expect_no_offenses('x = { :a => 0, "b" => 1 }')
end
it 'accepts an empty hash' do
expect_no_offenses('{}')
end
context 'ruby < 2.2', :ruby21, unsupported_on: :prism do
it 'accepts hash rockets when symbol keys have string in them' do
expect_no_offenses('x = { :"string" => 0 }')
end
end
it 'registers an offense when symbol keys have strings in them', :ruby22 do
expect_offense(<<~RUBY)
x = { :"string" => 0 }
^^^^^^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { "string": 0 }
RUBY
end
it 'preserves quotes during autocorrection' do
expect_offense(<<~RUBY)
{ :'&&' => foo }
^^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
{ '&&': foo }
RUBY
end
context 'if PreferHashRocketsForNonAlnumEndingSymbols is false' do
it 'registers an offense for hash rockets when symbols end with ?' do
expect_offense(<<~RUBY)
x = { :a? => 0 }
^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { a?: 0 }
RUBY
end
it 'registers an offense for hash rockets when symbols end with !' do
expect_offense(<<~RUBY)
x = { :a! => 0 }
^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { a!: 0 }
RUBY
end
end
context 'if PreferHashRocketsForNonAlnumEndingSymbols is true' do
let(:cop_config_overrides) { { 'PreferHashRocketsForNonAlnumEndingSymbols' => true } }
it 'accepts hash rockets when symbols end with ?' do
expect_no_offenses('x = { :a? => 0 }')
end
it 'accepts hash rockets when symbols end with !' do
expect_no_offenses('x = { :a! => 0 }')
end
end
it 'accepts hash rockets when symbol keys end with =' do
expect_no_offenses('x = { :a= => 0 }')
end
it 'accepts hash rockets when symbol characters are not supported' do
expect_no_offenses('x = { :[] => 0 }')
end
it 'registers an offense when keys start with an uppercase letter' do
expect_offense(<<~RUBY)
x = { :A => 0 }
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { A: 0 }
RUBY
end
it 'accepts new syntax in a hash literal' do
expect_no_offenses('x = { a: 0, b: 1 }')
end
it 'accepts new syntax in method calls' do
expect_no_offenses('func(3, a: 0)')
end
it 'autocorrects even if it interferes with SpaceAroundOperators' do
# Clobbering caused by two cops changing in the same range is dealt with
# by the autocorrect loop, so there's no reason to avoid a change.
expect_offense(<<~RUBY)
{ :a=>1, :b=>2 }
^^^^ Use the new Ruby 1.9 hash syntax.
^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
{ a: 1, b: 2 }
RUBY
end
# Bug: https://github.com/rubocop/rubocop/issues/5019
it 'autocorrects a missing space when hash is used as argument' do
expect_offense(<<~RUBY)
foo:bar => 1
^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
foo bar: 1
RUBY
end
context 'when using a return value uses `return`' do
it 'registers an offense and corrects when not enclosed in parentheses' do
expect_offense(<<~RUBY)
return :key => value
^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
return {key: value}
RUBY
end
it 'registers an offense and corrects when enclosed in parentheses' do
expect_offense(<<~RUBY)
return {:key => value}
^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
return {key: value}
RUBY
end
end
it 'registers an offense for implicit `call` method' do
expect_offense(<<~RUBY)
method(:puts).(:key => value)
^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
method(:puts).(key: value)
RUBY
end
end
context 'with SpaceAroundOperators disabled' do
let(:config) do
RuboCop::Config.new('AllCops' => {
'TargetRubyVersion' => ruby_version
},
'Style/HashSyntax' => {
'EnforcedStyle' => 'ruby19',
'SupportedStyles' => %w[ruby19 hash_rockets],
'UseHashRocketsWithSymbolValues' => false
},
'Layout/SpaceAroundOperators' => {
'Enabled' => false
})
end
it 'autocorrects even if there is no space around =>' do
expect_offense(<<~RUBY)
{ :a=>1, :b=>2 }
^^^^ Use the new Ruby 1.9 hash syntax.
^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
{ a: 1, b: 2 }
RUBY
end
end
context 'configured to use hash rockets when symbol values are found' do
let(:config) do
RuboCop::Config.new('AllCops' => {
'TargetRubyVersion' => ruby_version
},
'Style/HashSyntax' => {
'EnforcedStyle' => 'ruby19',
'SupportedStyles' => %w[ruby19 hash_rockets],
'UseHashRocketsWithSymbolValues' => true
})
end
it 'accepts ruby19 syntax when no elements have symbol values' do
expect_no_offenses('x = { a: 1, b: 2 }')
end
it 'accepts ruby19 syntax when no elements have symbol values in method calls' do
expect_no_offenses('func(3, a: 0)')
end
it 'accepts an empty hash' do
expect_no_offenses('{}')
end
it 'registers an offense when any element uses a symbol for the value' do
expect_offense(<<~RUBY)
x = { a: 1, b: :c }
^^ Use hash rockets syntax.
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
x = { :a => 1, :b => :c }
RUBY
end
it 'registers an offense when any element has a symbol value in method calls' do
expect_offense(<<~RUBY)
func(3, b: :c)
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
func(3, :b => :c)
RUBY
end
it 'registers an offense when using hash rockets and no elements have a symbol value' do
expect_offense(<<~RUBY)
x = { :a => 1, :b => 2 }
^^^^^ Use the new Ruby 1.9 hash syntax.
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { a: 1, b: 2 }
RUBY
end
it 'registers an offense for hashes with elements on multiple lines' do
expect_offense(<<~RUBY)
x = { a: :b,
^^ Use hash rockets syntax.
c: :d }
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
x = { :a => :b,
:c => :d }
RUBY
end
it 'accepts both hash rockets and ruby19 syntax in the same code' do
expect_no_offenses(<<~RUBY)
rocket_required = { :a => :b }
ruby19_required = { c: 3 }
RUBY
end
it 'autocorrects to hash rockets when all elements have symbol value' do
expect_offense(<<~RUBY)
{ a: :b, c: :d }
^^ Use hash rockets syntax.
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
{ :a => :b, :c => :d }
RUBY
end
it 'accepts hash in ruby19 style with no symbol values' do
expect_no_offenses(<<~RUBY)
{ a: 1, b: 2 }
RUBY
end
end
it 'registers an offense for implicit `call` method' do
expect_offense(<<~RUBY)
method(:puts).(:key=>value)
^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
method(:puts).(key: value)
RUBY
end
end
context 'configured to enforce hash rockets style' do
let(:cop_config) do
{
'EnforcedStyle' => 'hash_rockets',
'SupportedStyles' => %w[ruby19 hash_rockets],
'UseHashRocketsWithSymbolValues' => false
}
end
it 'registers an offense for Ruby 1.9 style' do
expect_offense(<<~RUBY)
x = { a: 0, b: 2}
^^ Use hash rockets syntax.
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
x = { :a => 0, :b => 2}
RUBY
end
it 'registers an offense for mixed syntax' do
expect_offense(<<~RUBY)
x = { a => 0, b: 1 }
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
x = { a => 0, :b => 1 }
RUBY
end
it 'registers an offense for 1.9 style in method calls' do
expect_offense(<<~RUBY)
func(3, a: 0)
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
func(3, :a => 0)
RUBY
end
it 'accepts hash rockets in a hash literal' do
expect_no_offenses('x = { :a => 0, :b => 1 }')
end
it 'accepts hash rockets in method calls' do
expect_no_offenses('func(3, :a => 0)')
end
it 'accepts an empty hash' do
expect_no_offenses('{}')
end
context 'UseHashRocketsWithSymbolValues has no impact' do
let(:cop_config) do
{
'EnforcedStyle' => 'hash_rockets',
'SupportedStyles' => %w[ruby19 hash_rockets],
'UseHashRocketsWithSymbolValues' => true
}
end
it 'does not register an offense when there is a symbol value' do
expect_no_offenses('{ :a => :b, :c => :d }')
end
end
it 'registers an offense for implicit `call` method' do
expect_offense(<<~RUBY)
method(:puts).(a: 0)
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
method(:puts).(:a => 0)
RUBY
end
end
context 'configured to enforce ruby 1.9 style with no mixed keys' do
context 'UseHashRocketsWithSymbolValues disabled' do
let(:cop_config) do
{
'EnforcedStyle' => 'ruby19_no_mixed_keys',
'UseHashRocketsWithSymbolValues' => false
}
end
it 'accepts new syntax in a hash literal' do
expect_no_offenses('x = { a: 0, b: 1 }')
end
it 'registers an offense for hash rocket syntax when new is possible' do
expect_offense(<<~RUBY)
x = { :a => 0, :b => 2 }
^^^^^ Use the new Ruby 1.9 hash syntax.
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { a: 0, b: 2 }
RUBY
end
it 'registers an offense for mixed syntax when new is possible' do
expect_offense(<<~RUBY)
x = { :a => 0, b: 1 }
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { a: 0, b: 1 }
RUBY
end
it 'accepts new syntax in method calls' do
expect_no_offenses('func(3, a: 0)')
end
it 'registers an offense for hash rockets in method calls' do
expect_offense(<<~RUBY)
func(3, :a => 0)
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
func(3, a: 0)
RUBY
end
it 'accepts hash rockets when keys have different types' do
expect_no_offenses('x = { :a => 0, "b" => 1 }')
end
it 'accepts an empty hash' do
expect_no_offenses('{}')
end
it 'registers an offense when keys have different types and styles' do
expect_offense(<<~RUBY)
x = { a: 0, "b" => 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { :a => 0, "b" => 1 }
RUBY
end
context 'ruby < 2.2', :ruby21, unsupported_on: :prism do
it 'accepts hash rockets when keys have whitespaces in them' do
expect_no_offenses('x = { :"t o" => 0, :b => 1 }')
end
it 'registers an offense when keys have whitespaces and mix styles' do
expect_offense(<<~RUBY)
x = { :"t o" => 0, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it 'accepts hash rockets when keys have special symbols in them' do
expect_no_offenses('x = { :"\\tab" => 1, :b => 1 }')
end
it 'registers an offense when keys have special symbols and mix styles' do
expect_offense(<<~RUBY)
x = { :"\tab" => 1, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it 'accepts hash rockets when keys start with a digit' do
expect_no_offenses('x = { :"1" => 1, :b => 1 }')
end
it 'registers an offense when keys start with a digit and mix styles' do
expect_offense(<<~RUBY)
x = { :"1" => 1, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
end
it 'registers an offense when keys have whitespaces in them' do
expect_offense(<<~RUBY)
x = { :"t o" => 0 }
^^^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { "t o": 0 }
RUBY
end
it 'registers an offense when keys have special symbols in them' do
expect_offense(<<~'RUBY')
x = { :"\tab" => 1 }
^^^^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~'RUBY')
x = { "\tab": 1 }
RUBY
end
it 'registers an offense when keys start with a digit' do
expect_offense(<<~RUBY)
x = { :"1" => 1 }
^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { "1": 1 }
RUBY
end
it 'accepts new syntax when keys are interpolated string' do
expect_no_offenses('{"#{foo}": 1, "#{@foo}": 2, "#@foo": 3}')
end
end
context 'UseHashRocketsWithSymbolValues enabled' do
let(:cop_config) do
{
'EnforcedStyle' => 'ruby19_no_mixed_keys',
'UseHashRocketsWithSymbolValues' => true
}
end
it 'registers an offense when any element uses a symbol for the value' do
expect_offense(<<~RUBY)
x = { a: 1, b: :c }
^^ Use hash rockets syntax.
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
x = { :a => 1, :b => :c }
RUBY
end
it 'registers an offense when any element has a symbol value in method calls' do
expect_offense(<<~RUBY)
func(3, b: :c)
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
func(3, :b => :c)
RUBY
end
it 'autocorrects to hash rockets when all elements have symbol value' do
expect_offense(<<~RUBY)
{ a: :b, c: :d }
^^ Use hash rockets syntax.
^^ Use hash rockets syntax.
RUBY
expect_correction(<<~RUBY)
{ :a => :b, :c => :d }
RUBY
end
it 'accepts new syntax in a hash literal' do
expect_no_offenses('x = { a: 0, b: 1 }')
end
it 'registers an offense for hash rocket syntax when new is possible' do
expect_offense(<<~RUBY)
x = { :a => 0, :b => 2 }
^^^^^ Use the new Ruby 1.9 hash syntax.
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'hash_rockets')
expect_correction(<<~RUBY)
x = { a: 0, b: 2 }
RUBY
end
it 'registers an offense for mixed syntax when new is possible' do
expect_offense(<<~RUBY)
x = { :a => 0, b: 1 }
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { a: 0, b: 1 }
RUBY
end
it 'accepts new syntax in method calls' do
expect_no_offenses('func(3, a: 0)')
end
it 'registers an offense for hash rockets in method calls' do
expect_offense(<<~RUBY)
func(3, :a => 0)
^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
func(3, a: 0)
RUBY
end
it 'accepts hash rockets when keys have different types' do
expect_no_offenses('x = { :a => 0, "b" => 1 }')
end
it 'accepts an empty hash' do
expect_no_offenses('{}')
end
it 'registers an offense when keys have different types and styles' do
expect_offense(<<~RUBY)
x = { a: 0, "b" => 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { :a => 0, "b" => 1 }
RUBY
end
context 'ruby < 2.2', :ruby21, unsupported_on: :prism do
it 'accepts hash rockets when keys have whitespaces in them' do
expect_no_offenses('x = { :"t o" => 0, :b => 1 }')
end
it 'registers an offense when keys have whitespaces and mix styles' do
expect_offense(<<~RUBY)
x = { :"t o" => 0, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it 'accepts hash rockets when keys have special symbols in them' do
expect_no_offenses('x = { :"\\tab" => 1, :b => 1 }')
end
it 'registers an offense when keys have special symbols and mix styles' do
expect_offense(<<~RUBY)
x = { :"\tab" => 1, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it 'accepts hash rockets when keys start with a digit' do
expect_no_offenses('x = { :"1" => 1, :b => 1 }')
end
it 'registers an offense when keys start with a digit and mix styles' do
expect_offense(<<~RUBY)
x = { :"1" => 1, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
end
it 'registers an offense when keys have whitespaces in them' do
expect_offense(<<~RUBY)
x = { :"t o" => 0 }
^^^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { "t o": 0 }
RUBY
end
it 'registers an offense when keys have special symbols in them' do
expect_offense(<<~'RUBY')
x = { :"\tab" => 1 }
^^^^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~'RUBY')
x = { "\tab": 1 }
RUBY
end
it 'registers an offense when keys start with a digit' do
expect_offense(<<~RUBY)
x = { :"1" => 1 }
^^^^^^^ Use the new Ruby 1.9 hash syntax.
RUBY
expect_correction(<<~RUBY)
x = { "1": 1 }
RUBY
end
it 'accepts new syntax when keys are interpolated string' do
expect_no_offenses('{"#{foo}": 1, "#{@foo}": 2, "#@foo": 3}')
end
end
end
context 'configured to enforce no mixed keys' do
let(:cop_config) { { 'EnforcedStyle' => 'no_mixed_keys' } }
it 'accepts new syntax in a hash literal' do
expect_no_offenses('x = { a: 0, b: 1 }')
end
it 'accepts the hash rocket syntax when new is possible' do
expect_no_offenses('x = { :a => 0 }')
end
it 'registers an offense for mixed syntax when new is possible' do
expect_offense(<<~RUBY)
x = { :a => 0, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { :a => 0, :b => 1 }
RUBY
end
it 'accepts new syntax in method calls' do
expect_no_offenses('func(3, a: 0)')
end
it 'accepts hash rockets in method calls' do
expect_no_offenses('func(3, :a => 0)')
end
it 'accepts hash rockets when keys have different types' do
expect_no_offenses('x = { :a => 0, "b" => 1 }')
end
it 'accepts an empty hash' do
expect_no_offenses('{}')
end
it 'registers an offense when keys have different types and styles' do
expect_offense(<<~RUBY)
x = { a: 0, "b" => 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { :a => 0, "b" => 1 }
RUBY
end
it 'accepts hash rockets when keys have whitespaces in them' do
expect_no_offenses('x = { :"t o" => 0, :b => 1 }')
end
context 'Ruby >= 3.1', :ruby31 do
it 'registers hash rockets when keys have whitespaces in them and using hash value omission' do
expect_offense(<<~RUBY)
{:"t o" => 0, b:}
^^ Don't mix styles in the same hash.
RUBY
expect_correction(<<~RUBY)
{:"t o" => 0, :b => b}
RUBY
end
end
it 'registers an offense when keys have whitespaces and mix styles' do
expect_offense(<<~RUBY)
x = { :"t o" => 0, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { :"t o" => 0, :b => 1 }
RUBY
end
it 'accepts hash rockets when keys have special symbols in them' do
expect_no_offenses('x = { :"\\tab" => 1, :b => 1 }')
end
it 'registers an offense when keys have special symbols and mix styles' do
expect_offense(<<~RUBY, tab: "\t")
x = { :"%{tab}ab" => 1, b: 1 }
_{tab} ^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { :"\tab" => 1, :b => 1 }
RUBY
end
it 'accepts hash rockets when keys start with a digit' do
expect_no_offenses('x = { :"1" => 1, :b => 1 }')
end
it 'registers an offense when keys start with a digit and mix styles' do
expect_offense(<<~RUBY)
x = { :"1" => 1, b: 1 }
^^ Don't mix styles in the same hash.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
x = { :"1" => 1, :b => 1 }
RUBY
end
it 'accepts old hash rockets style' do
expect_no_offenses('{ :a => 1, :b => 2 }')
end
it 'accepts new hash style' do
expect_no_offenses('{ a: 1, b: 2 }')
end
it 'autocorrects mixed key hashes' do
expect_offense(<<~RUBY)
{ a: 1, :b => 2 }
^^^^^ Don't mix styles in the same hash.
RUBY
expect_correction(<<~RUBY)
{ a: 1, b: 2 }
RUBY
end
end
context 'configured to enforce shorthand syntax style' do
let(:cop_config) do
{
'EnforcedStyle' => enforced_style,
'SupportedStyles' => %w[ruby19 hash_rockets],
'EnforcedShorthandSyntax' => 'always'
}
end
let(:enforced_style) { 'ruby19' }
context 'Ruby >= 3.1', :ruby31 do
it 'registers and corrects an offense when hash key and hash value are the same' do
expect_offense(<<~RUBY)
{foo: foo, bar: bar}
^^^ Omit the hash value.
^^^ Omit the hash value.
RUBY
expect_correction(<<~RUBY)
{foo:, bar:}
RUBY
end
it 'registers and corrects an offense when hash key and hash value (lvar) are the same' do
expect_offense(<<~RUBY)
foo = 'a'
bar = 'b'
{foo: foo, bar: bar}
^^^ Omit the hash value.
^^^ Omit the hash value.
RUBY
expect_correction(<<~RUBY)
foo = 'a'
bar = 'b'
{foo:, bar:}
RUBY
end
it 'registers and corrects an offense when hash key and hash value are partially the same' do
expect_offense(<<~RUBY)
{foo:, bar: bar, baz: qux}
^^^ Omit the hash value.
RUBY
expect_correction(<<~RUBY)
{foo:, bar:, baz: qux}
RUBY
end
it 'registers and corrects an offense when `Hash[foo: foo]`' do
expect_offense(<<~RUBY)
Hash[foo: foo]
^^^ Omit the hash value.
RUBY
expect_correction(<<~RUBY)
Hash[foo:]
RUBY
end
it 'registers and corrects an offense when `Hash[foo: foo]` and an expression follows' do
expect_offense(<<~RUBY)
Hash[foo: foo]
^^^ Omit the hash value.
do_something
RUBY
expect_correction(<<~RUBY)
Hash[foo:]
do_something
RUBY
end
it 'registers and corrects an offense when braced hash key and value are the same and it is used in `if`...`else`' do
expect_offense(<<~RUBY)
if condition
template % {value: value}
^^^^^ Omit the hash value.
else
do_something
end
RUBY
expect_correction(<<~RUBY)
if condition
template % {value:}
else
do_something
end
RUBY
end
it 'registers and corrects an offense when hash key and hash value are the same and it in the method body' do
expect_offense(<<~RUBY)
def do_something
{
foo: foo,
^^^ Omit the hash value.
bar: bar
^^^ Omit the hash value.
}
end
RUBY
expect_correction(<<~RUBY)
def do_something
{
foo:,
bar:
}
end
RUBY
end
it 'registers and corrects an offense when hash key and hash value are the same and it in the method body' \
'and an expression follows' do
expect_offense(<<~RUBY)
def do_something
{
foo: foo,
^^^ Omit the hash value.
bar: bar
^^^ Omit the hash value.
}
end
do_something
RUBY
expect_correction(<<~RUBY)
def do_something
{
foo:,
bar:
}
end
do_something
RUBY
end
it 'does not register an offense when hash values are omitted' do
expect_no_offenses(<<~RUBY)
{foo:, bar:}
RUBY
end
it 'does not register an offense when hash key and hash value are not the same' do
expect_no_offenses(<<~RUBY)
{foo: bar, bar: foo}
RUBY
end
it 'does not register an offense when symbol hash key and hash value (lvar) are not the same' do
expect_no_offenses(<<~RUBY)
foo = 'a'
bar = 'b'
{foo: bar, bar: foo}
RUBY
end
it 'registers an offense when hash key and hash value are not the same and method with `[]` is called' do
expect_offense(<<~RUBY)
{foo: foo}.do_something[key]
^^^ Omit the hash value.
RUBY
expect_correction(<<~RUBY)
{foo:}.do_something[key]
RUBY
end
it 'does not register an offense when hash pattern matching' do
expect_no_offenses(<<~RUBY)
case pattern
in {foo: 42}
in {foo: foo}
end
RUBY
end
it 'does not register an offense when hash key and hash value are the same but the value ends `!`' do
# Prevents the following syntax error:
#
# $ ruby -cve 'def foo! = puts("hi"); {foo!:}'
# ruby 3.1.0dev (2021-12-05T10:23:42Z master 19f037e452) [x86_64-darwin19]
# -e:1: identifier foo! is not valid to get
expect_no_offenses(<<~RUBY)
{foo!: foo!}
RUBY
end
it 'does not register an offense when hash key and hash value are the same but the value ends `?`' do
# Prevents the following syntax error:
#
# $ ruby -cve 'def foo? = puts("hi"); {foo?:}'
# ruby 3.1.0dev (2021-12-05T10:23:42Z master 19f037e452) [x86_64-darwin19]
# -e:1: identifier foo? is not valid to get
expect_no_offenses(<<~RUBY)
{foo?: foo?}
RUBY
end
it 'does not register an offense when symbol hash key and string hash value are the same' do
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/double_negation_spec.rb | spec/rubocop/cop/style/double_negation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DoubleNegation, :config do
let(:cop_config) { { 'EnforcedStyle' => enforced_style } }
shared_examples 'common' do
it 'registers an offense and corrects for `!!` when not a return location' do
expect_offense(<<~RUBY)
def foo?
foo
!!test.something
^ Avoid the use of double negation (`!!`).
bar
end
RUBY
expect_correction(<<~RUBY)
def foo?
foo
!test.something.nil?
bar
end
RUBY
end
it 'registers an offense and corrects for `!!`' do
expect_offense(<<~RUBY)
!!test.something
^ Avoid the use of double negation (`!!`).
RUBY
expect_correction(<<~RUBY)
!test.something.nil?
RUBY
end
it 'does not register an offense for !' do
expect_no_offenses('!test.something')
end
it 'does not register an offense for `not not`' do
expect_no_offenses('not not test.something')
end
end
context 'when `EnforcedStyle: allowed_in_returns`' do
let(:enforced_style) { 'allowed_in_returns' }
it_behaves_like 'common'
it 'registers an offense and corrects for `!!` when not return location and using `unless`' do
expect_offense(<<~RUBY)
def foo?
unless condition_foo?
!!foo
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
unless condition_foo?
!foo.nil?
do_something
end
end
RUBY
end
it 'registers an offense and corrects for `!!` when not return location' \
'and using `if`, `elsif`, and `else`' do
expect_offense(<<~RUBY)
def foo?
if condition_foo?
!!foo
^ Avoid the use of double negation (`!!`).
do_something
elsif condition_bar?
!!bar
^ Avoid the use of double negation (`!!`).
do_something
else
!!baz
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
if condition_foo?
!foo.nil?
do_something
elsif condition_bar?
!bar.nil?
do_something
else
!baz.nil?
do_something
end
end
RUBY
end
it 'registers an offense and corrects for `!!` with hash when not return location' \
'and using `if`, `elsif`, and `else`' do
expect_offense(<<~RUBY)
def foo?
if condition_foo?
{ foo: !!foo0, bar: bar0, baz: baz0 }
^ Avoid the use of double negation (`!!`).
do_something
elsif condition_bar?
{ foo: !!foo1, bar: bar1, baz: baz1 }
^ Avoid the use of double negation (`!!`).
do_something
else
{ foo: !!foo2, bar: bar2, baz: baz2 }
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
if condition_foo?
{ foo: !foo0.nil?, bar: bar0, baz: baz0 }
do_something
elsif condition_bar?
{ foo: !foo1.nil?, bar: bar1, baz: baz1 }
do_something
else
{ foo: !foo2.nil?, bar: bar2, baz: baz2 }
do_something
end
end
RUBY
end
it 'registers an offense and corrects for `!!` with array when not return location' \
'and using `if`, `elsif`, and `else`' do
expect_offense(<<~RUBY)
def foo?
if condition_foo?
[!!foo0, bar0, baz0]
^ Avoid the use of double negation (`!!`).
do_something
elsif condition_bar?
[!!foo1, bar1, baz1]
^ Avoid the use of double negation (`!!`).
do_something
else
[!!foo2, bar2, baz2]
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
if condition_foo?
[!foo0.nil?, bar0, baz0]
do_something
elsif condition_bar?
[!foo1.nil?, bar1, baz1]
do_something
else
[!foo2.nil?, bar2, baz2]
do_something
end
end
RUBY
end
it 'registers an offense and corrects for `!!` when not return location' \
'and using `case`, `when`, and `else`' do
expect_offense(<<~RUBY)
def foo?
case condition
when foo
!!foo
^ Avoid the use of double negation (`!!`).
do_something
when bar
!!bar
^ Avoid the use of double negation (`!!`).
do_something
else
!!baz
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
case condition
when foo
!foo.nil?
do_something
when bar
!bar.nil?
do_something
else
!baz.nil?
do_something
end
end
RUBY
end
it 'registers an offense and corrects for `!!` with hash when not return location' \
'and using `case`, `when`, and `else`' do
expect_offense(<<~RUBY)
def foo?
case condition
when foo
{ foo: !!foo0, bar: bar0, baz: baz0 }
^ Avoid the use of double negation (`!!`).
do_something
when bar
{ foo: !!foo1, bar: bar1, baz: baz1 }
^ Avoid the use of double negation (`!!`).
do_something
else
{ foo: !!foo2, bar: bar2, baz: baz2 }
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
case condition
when foo
{ foo: !foo0.nil?, bar: bar0, baz: baz0 }
do_something
when bar
{ foo: !foo1.nil?, bar: bar1, baz: baz1 }
do_something
else
{ foo: !foo2.nil?, bar: bar2, baz: baz2 }
do_something
end
end
RUBY
end
it 'registers an offense and corrects for `!!` with array when not return location' \
'and using `case`, `when`, and `else`' do
expect_offense(<<~RUBY)
def foo?
case condition
when foo
[!!foo0, bar0, baz0]
^ Avoid the use of double negation (`!!`).
do_something
when bar
[!!foo1, bar1, baz1]
^ Avoid the use of double negation (`!!`).
do_something
else
[!!foo2, bar2, baz2]
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
case condition
when foo
[!foo0.nil?, bar0, baz0]
do_something
when bar
[!foo1.nil?, bar1, baz1]
do_something
else
[!foo2.nil?, bar2, baz2]
do_something
end
end
RUBY
end
it 'registers an offense and corrects for `!!` with multi-line array at return location' do
expect_offense(<<~RUBY)
def foo
[
foo1,
!!bar1,
^ Avoid the use of double negation (`!!`).
!!baz1
^ Avoid the use of double negation (`!!`).
]
end
RUBY
expect_correction(<<~RUBY)
def foo
[
foo1,
!bar1.nil?,
!baz1.nil?
]
end
RUBY
end
it 'registers an offense and corrects for `!!` with single-line array at return location' do
expect_offense(<<~RUBY)
def foo
[foo1, !!bar1, baz1]
^ Avoid the use of double negation (`!!`).
end
RUBY
expect_correction(<<~RUBY)
def foo
[foo1, !bar1.nil?, baz1]
end
RUBY
end
it 'registers an offense and corrects for `!!` with multi-line hash at return location' do
expect_offense(<<~RUBY)
def foo
{
foo: foo1,
bar: !!bar1,
^ Avoid the use of double negation (`!!`).
baz: !!baz1
^ Avoid the use of double negation (`!!`).
}
end
RUBY
expect_correction(<<~RUBY)
def foo
{
foo: foo1,
bar: !bar1.nil?,
baz: !baz1.nil?
}
end
RUBY
end
it 'registers an offense and corrects for `!!` with single-line hash at return location' do
expect_offense(<<~RUBY)
def foo
{ foo: foo1, bar: !!bar1, baz: baz1 }
^ Avoid the use of double negation (`!!`).
end
RUBY
expect_correction(<<~RUBY)
def foo
{ foo: foo1, bar: !bar1.nil?, baz: baz1 }
end
RUBY
end
it 'registers an offense and corrects for `!!` with nested hash at return location' do
expect_offense(<<~RUBY)
def foo
{
foo: foo1,
bar: { baz: !!quux }
^ Avoid the use of double negation (`!!`).
}
end
RUBY
expect_correction(<<~RUBY)
def foo
{
foo: foo1,
bar: { baz: !quux.nil? }
}
end
RUBY
end
it 'registers an offense and corrects for `!!` with nested array at return location' do
expect_offense(<<~RUBY)
def foo
[
foo1,
[baz, !!quux]
^ Avoid the use of double negation (`!!`).
]
end
RUBY
expect_correction(<<~RUBY)
def foo
[
foo1,
[baz, !quux.nil?]
]
end
RUBY
end
it 'registers an offense and corrects for `!!` with complex array at return location' do
expect_offense(<<~RUBY)
def foo
[
foo1,
{ baz: !!quux }
^ Avoid the use of double negation (`!!`).
]
end
RUBY
expect_correction(<<~RUBY)
def foo
[
foo1,
{ baz: !quux.nil? }
]
end
RUBY
end
# rubocop:disable RSpec/RepeatedExampleGroupDescription
context 'Ruby >= 2.7', :ruby27 do
# rubocop:enable RSpec/RepeatedExampleGroupDescription
it 'registers an offense and corrects for `!!` when not return location' \
'and using `case`, `in`, and `else`' do
expect_offense(<<~RUBY)
def foo?
case pattern
in foo
!!foo
^ Avoid the use of double negation (`!!`).
do_something
in bar
!!bar
^ Avoid the use of double negation (`!!`).
do_something
else
!!baz
^ Avoid the use of double negation (`!!`).
do_something
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
case pattern
in foo
!foo.nil?
do_something
in bar
!bar.nil?
do_something
else
!baz.nil?
do_something
end
end
RUBY
end
end
it 'does not register an offense for `!!` when return location' do
expect_no_offenses(<<~RUBY)
def foo?
bar
!!baz.do_something
end
RUBY
end
it 'does not register an offense for `!!` when using `return` keyword' do
expect_no_offenses(<<~RUBY)
def foo?
return !!bar.do_something if condition
baz
!!qux
end
RUBY
end
it 'does not register an offense for a line-broken `!!` expression when using `return` keyword' do
expect_no_offenses(<<~RUBY)
def foo?
return !!bar.do_something if condition
baz
!!qux &&
quux
end
RUBY
end
it 'does not register an offense for `!!` when return location by `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :foo? do
bar
!!qux
end
RUBY
end
it 'does not register an offense for `!!` when return location by `define_method` with numblock' do
expect_no_offenses(<<~RUBY)
define_method :foo? do
do_something(_1)
!!qux
end
RUBY
end
it 'does not register an offense for `!!` when return location by `define_singleton_method`' do
expect_no_offenses(<<~RUBY)
define_singleton_method :foo? do
bar
!!qux
end
RUBY
end
it 'does not register an offense for `!!` when return location and using `rescue`' do
expect_no_offenses(<<~RUBY)
def foo?
bar
!!baz.do_something
rescue
qux
end
RUBY
end
it 'does not register an offense for `!!` when return location and using `ensure`' do
expect_no_offenses(<<~RUBY)
def foo?
bar
!!baz.do_something
ensure
qux
end
RUBY
end
it 'does not register an offense for `!!` when return location and using `rescue` and `ensure`' do
expect_no_offenses(<<~RUBY)
def foo?
bar
!!baz.do_something
rescue
qux
ensure
corge
end
RUBY
end
it 'does not register an offense for `!!` when return location and using `rescue`, `else`, and `ensure`' do
expect_no_offenses(<<~RUBY)
def foo?
bar
!!baz.do_something
rescue
qux
else
quux
ensure
corge
end
RUBY
end
it 'does not register an offense for `!!` when return location and using `unless`' do
expect_no_offenses(<<~RUBY)
def foo?
unless condition_foo?
!!foo
end
end
def bar?
unless condition_bar?
do_something
!!bar
end
end
RUBY
end
it 'does not register an offense for `!!` when return location and using `if`, `elsif`, and `else`' do
expect_no_offenses(<<~RUBY)
def foo?
if condition_foo?
!!foo
elsif condition_bar?
!!bar
else
!!baz
end
end
def bar?
if condition_foo?
do_something
!!foo
elsif condition_bar?
do_something
!!bar
else
do_something
!!baz
end
end
RUBY
end
it 'does not register an offense for `!!` with hash when return location and using `if`, `elsif`, and `else`' do
expect_no_offenses(<<~RUBY)
def foo?
if condition_foo?
{ foo: !!foo0, bar: bar0, baz: baz0 }
elsif condition_bar?
{ foo: !!foo1, bar: bar1, baz: baz1 }
else
{ foo: !!foo2, bar: bar2, baz: baz2 }
end
end
def bar?
if condition_foo?
do_something
{ foo: !!foo0, bar: bar0, baz: baz0 }
elsif condition_bar?
do_something
{ foo: !!foo1, bar: bar1, baz: baz1 }
else
do_something
{ foo: !!foo2, bar: bar2, baz: baz2 }
end
end
RUBY
end
it 'does not register an offense for `!!` with array when return location and using `if`, `elsif`, and `else`' do
expect_no_offenses(<<~RUBY)
def foo?
if condition_foo?
[!!foo0, bar0, baz0]
elsif condition_bar?
[!!foo1, bar1, baz1]
else
[!!foo2, bar2, baz2]
end
end
def bar?
if condition_foo?
do_something
[!!foo0, bar0, baz0]
elsif condition_bar?
do_something
[!!foo1, bar1, baz1]
else
do_something
[!!foo2, bar2, baz2]
end
end
RUBY
end
it 'does not register an offense for `!!` when return location and using `case`, `when`, and `else`' do
expect_no_offenses(<<~RUBY)
def foo?
case condition
when foo
!!foo
when bar
!!bar
else
!!baz
end
end
def bar?
case condition
when foo
do_something
!!foo
when bar
do_something
!!bar
else
do_something
!!baz
end
end
RUBY
end
it 'does not register an offense for `!!` with hash when return location and using `case`, `when`, and `else`' do
expect_no_offenses(<<~RUBY)
def foo?
case condition
when foo
{ foo: !!foo0, bar: bar0, baz: baz0 }
when bar
{ foo: !!foo1, bar: bar1, baz: baz1 }
else
{ foo: !!foo2, bar: bar2, baz: baz2 }
end
end
def bar?
case condition
when foo
do_something
{ foo: !!foo0, bar: bar0, baz: baz0 }
when bar
do_something
{ foo: !!foo1, bar: bar1, baz: baz1 }
else
do_something
{ foo: !!foo2, bar: bar2, baz: baz2 }
end
end
RUBY
end
it 'does not register an offense for `!!` with array when return location and using `case`, `when`, and `else`' do
expect_no_offenses(<<~RUBY)
def foo?
case condition
when foo
[!!foo0, bar0, baz0]
when bar
[!!foo1, bar1, baz1]
else
[!!foo2, bar2, baz2]
end
end
def foo?
case condition
when foo
do_something
[!!foo0, bar0, baz0]
when bar
do_something
[!!foo1, bar1, baz1]
else
do_something
[!!foo2, bar2, baz2]
end
end
RUBY
end
# rubocop:disable RSpec/RepeatedExampleGroupDescription
context 'Ruby >= 2.7', :ruby27 do
# rubocop:enable RSpec/RepeatedExampleGroupDescription
it 'does not register an offense for `!!` when return location and using `case`, `in`, and `else`' do
expect_no_offenses(<<~RUBY)
def foo?
case condition
in foo
!!foo
in bar
!!bar
else
!!baz
end
end
def bar?
case condition
in foo
do_something
!!foo
in bar
do_something
!!bar
else
do_something
!!baz
end
end
RUBY
end
end
end
context 'when `EnforcedStyle: forbidden`' do
let(:enforced_style) { 'forbidden' }
it_behaves_like 'common'
it 'registers an offense and corrects for `!!` when return location' do
expect_offense(<<~RUBY)
def foo?
bar
!!baz.do_something
^ Avoid the use of double negation (`!!`).
end
RUBY
expect_correction(<<~RUBY)
def foo?
bar
!baz.do_something.nil?
end
RUBY
end
it 'registers an offense and corrects for `!!` when using `return` keyword' do
expect_offense(<<~RUBY)
def foo?
return !!bar.do_something if condition
^ Avoid the use of double negation (`!!`).
baz
!!bar
^ Avoid the use of double negation (`!!`).
end
RUBY
expect_correction(<<~RUBY)
def foo?
return !bar.do_something.nil? if condition
baz
!bar.nil?
end
RUBY
end
it 'registers an offense for `!!` when return location and using `rescue`' do
expect_offense(<<~RUBY)
def foo?
bar
!!baz.do_something
^ Avoid the use of double negation (`!!`).
rescue
qux
end
RUBY
expect_correction(<<~RUBY)
def foo?
bar
!baz.do_something.nil?
rescue
qux
end
RUBY
end
it 'registers an offense for `!!` when return location and using `ensure`' do
expect_offense(<<~RUBY)
def foo?
bar
!!baz.do_something
^ Avoid the use of double negation (`!!`).
ensure
qux
end
RUBY
expect_correction(<<~RUBY)
def foo?
bar
!baz.do_something.nil?
ensure
qux
end
RUBY
end
it 'registers an offense for `!!` when return location and using `rescue` and `ensure`' do
expect_offense(<<~RUBY)
def foo?
bar
!!baz.do_something
^ Avoid the use of double negation (`!!`).
rescue
baz
ensure
qux
end
RUBY
expect_correction(<<~RUBY)
def foo?
bar
!baz.do_something.nil?
rescue
baz
ensure
qux
end
RUBY
end
it 'registers an offense for `!!` when return location and using `rescue`, `else`, and `ensure`' do
expect_offense(<<~RUBY)
def foo?
bar
!!baz.do_something
^ Avoid the use of double negation (`!!`).
rescue
qux
else
quux
ensure
corge
end
RUBY
expect_correction(<<~RUBY)
def foo?
bar
!baz.do_something.nil?
rescue
qux
else
quux
ensure
corge
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trailing_comma_in_arguments_spec.rb | spec/rubocop/cop/style/trailing_comma_in_arguments_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrailingCommaInArguments, :config do
shared_examples 'single line lists' do |extra_info|
[%w[( )], %w[[ ]]].each do |start_bracket, end_bracket|
context "with `#{start_bracket}#{end_bracket}` brackets" do
it 'registers an offense for trailing comma in a method call' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}a, b, c, #{end_bracket}
_{start_bracket} ^ Avoid comma after the last parameter of a method call#{extra_info}.
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}a, b, c #{end_bracket}
RUBY
end
it 'registers an offense for trailing comma preceded by whitespace in a method call' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}a, b, c , #{end_bracket}
_{start_bracket} ^ Avoid comma after the last parameter of a method call#{extra_info}.
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}a, b, c #{end_bracket}
RUBY
end
it 'registers an offense for trailing comma in a method call with hash parameters at the end' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}a, b, c: 0, d: 1, #{end_bracket}
_{start_bracket} ^ Avoid comma after the last parameter of a method call#{extra_info}.
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}a, b, c: 0, d: 1 #{end_bracket}
RUBY
end
it 'accepts method call without trailing comma' do
expect_no_offenses("some_method#{start_bracket}a, b, c#{end_bracket}")
end
it 'accepts method call without trailing comma when a line break before a method call' do
expect_no_offenses(<<~RUBY)
obj
.do_something#{start_bracket}:foo, :bar#{end_bracket}
RUBY
end
it 'accepts method call without trailing comma with single element hash ' \
'parameters at the end' do
expect_no_offenses("some_method#{start_bracket}a: 1#{end_bracket}")
end
it 'accepts method call without parameters' do
expect_no_offenses('some_method')
end
it 'accepts chained single-line method calls' do
expect_no_offenses(<<~RUBY)
target
.some_method#{start_bracket}a#{end_bracket}
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense for trailing comma in a method call' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
receiver&.some_method#{start_bracket}a, b, c, #{end_bracket}
_{start_bracket} ^ Avoid comma after the last parameter of a method call#{extra_info}.
RUBY
expect_correction(<<~RUBY)
receiver&.some_method#{start_bracket}a, b, c #{end_bracket}
RUBY
end
it 'registers an offense for trailing comma in a method call with hash ' \
'parameters at the end' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
receiver&.some_method#{start_bracket}a, b, c: 0, d: 1, #{end_bracket}
_{start_bracket} ^ Avoid comma after the last parameter of a method call#{extra_info}.
RUBY
expect_correction(<<~RUBY)
receiver&.some_method#{start_bracket}a, b, c: 0, d: 1 #{end_bracket}
RUBY
end
end
end
end
it 'accepts method call without parameters' do
expect_no_offenses('some_method')
end
it 'accepts heredoc without trailing comma' do
expect_no_offenses(<<~RUBY)
route(1, <<-HELP.chomp)
...
HELP
RUBY
end
end
context 'with single line list of values' do
context 'when EnforcedStyleForMultiline is no_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'no_comma' } }
it_behaves_like 'single line lists', ''
end
context 'when EnforcedStyleForMultiline is comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'comma' } }
it_behaves_like 'single line lists', ', unless each item is on its own line'
end
context 'when EnforcedStyleForMultiline is diff_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'diff_comma' } }
it_behaves_like 'single line lists', ', unless that item immediately precedes a newline'
end
context 'when EnforcedStyleForMultiline is consistent_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } }
it_behaves_like 'single line lists', ', unless items are split onto multiple lines'
end
end
context 'with a single argument spanning multiple lines' do
context 'when EnforcedStyleForMultiline is consistent_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } }
[%w[( )], %w[[ ]]].each do |start_bracket, end_bracket|
context "with `#{start_bracket}#{end_bracket}` brackets" do
it 'accepts a single argument with no trailing comma' do
expect_no_offenses(<<~RUBY)
EmailWorker.perform_async#{start_bracket}{
subject: "hey there",
email: "foo@bar.com"
}#{end_bracket}
RUBY
end
end
end
end
end
context 'with a braced hash argument spanning multiple lines after an argument' do
context 'when EnforcedStyleForMultiline is consistent_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } }
[%w[( )], %w[[ ]]].each do |start_bracket, end_bracket|
context "with `#{start_bracket}#{end_bracket}` brackets" do
it 'accepts multiple arguments with no trailing comma' do
expect_no_offenses(<<~RUBY)
EmailWorker.perform_async#{start_bracket}arg, {
subject: "hey there",
email: "foo@bar.com"
}#{end_bracket}
RUBY
end
end
end
end
end
context 'with multiple arguments of anonymous function spanning multiple lines' do
context 'when EnforcedStyleForMultiline is consistent_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } }
it 'accepts multiple arguments with trailing comma' do
expect_no_offenses(<<~RUBY)
func.(
'foo',
'bar',
'baz',
)
RUBY
end
it 'accepts keyword arguments with trailing comma' do
expect_no_offenses(<<~RUBY)
func.(foo: 1,
bar: 2,)
RUBY
end
end
end
context 'with multi-line list of values' do
context 'when EnforcedStyleForMultiline is no_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'no_comma' } }
[%w[( )], %w[[ ]]].each do |start_bracket, end_bracket|
context "with `#{start_bracket}#{end_bracket}` brackets" do
it 'registers an offense for trailing comma in a method call with ' \
'hash parameters at the end' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,#{end_bracket}
^ Avoid comma after the last parameter of a method call.
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1#{end_bracket}
RUBY
end
it 'accepts a method call with hash parameters at the end and no trailing comma' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}a,
b,
c: 0,
d: 1
#{end_bracket}
RUBY
end
it 'accepts comma inside a heredoc parameter at the end' do
expect_no_offenses(<<~RUBY)
route#{start_bracket}help: {
'auth' => <<-HELP.chomp
,
HELP
}#{end_bracket}
RUBY
end
it 'accepts comma inside a heredoc with comments inside' do
expect_no_offenses(<<~RUBY)
route#{start_bracket}
<<-HELP
,
# some comment
HELP
#{end_bracket}
RUBY
end
it 'accepts comma inside a heredoc with method and comments inside' do
expect_no_offenses(<<~RUBY)
route#{start_bracket}
<<-HELP.chomp
,
# some comment
HELP
#{end_bracket}
RUBY
end
it 'accepts comma inside a heredoc in brackets' do
expect_no_offenses(<<~RUBY)
expect_no_offenses(
expect_no_offenses(<<~SOURCE)
run#{start_bracket}
:foo, defaults.merge(
bar: 3)#{end_bracket}
SOURCE
)
RUBY
end
it 'accepts comma inside a modified heredoc parameter' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
<<-LOREM.delete("\\n")
Something with a , in it
LOREM
#{end_bracket}
RUBY
end
it 'autocorrects unwanted comma after modified heredoc parameter' do
expect_offense(<<~'RUBY', start_bracket: start_bracket, end_bracket: end_bracket)
some_method%{start_bracket}
<<-LOREM.delete("\n"),
^ Avoid comma after the last parameter of a method call.
Something with a , in it
LOREM
%{end_bracket}
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}
<<-LOREM.delete("\\n")
Something with a , in it
LOREM
#{end_bracket}
RUBY
end
context 'when there is string interpolation inside heredoc parameter' do
it 'accepts comma inside a heredoc parameter' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
<<-SQL
\#{variable}.a ASC,
\#{variable}.b ASC
SQL
#{end_bracket}
RUBY
end
it 'accepts comma inside a heredoc parameter when on a single line' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
bar: <<-BAR
\#{variable} foo, bar
BAR
#{end_bracket}
RUBY
end
it 'autocorrects unwanted comma inside string interpolation' do
expect_offense(<<~'RUBY')
some_method(
bar: <<-BAR,
#{other_method(a, b,)} foo, bar
^ Avoid comma after the last parameter of a method call.
BAR
baz: <<-BAZ
#{third_method(c, d,)} foo, bar
^ Avoid comma after the last parameter of a method call.
BAZ
)
RUBY
expect_correction(<<~RUBY)
some_method(
bar: <<-BAR,
\#{other_method(a, b)} foo, bar
BAR
baz: <<-BAZ
\#{third_method(c, d)} foo, bar
BAZ
)
RUBY
end
end
end
end
end
context 'when EnforcedStyleForMultiline is comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'comma' } }
[%w[( )], %w[[ ]]].each do |start_bracket, end_bracket|
context "with `#{start_bracket}#{end_bracket}` brackets" do
context 'when closing bracket is on same line as last value' do
it 'accepts a method call with Hash as last parameter split on multiple lines' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}a: "b",
c: "d"#{end_bracket}
RUBY
end
end
it 'registers an offense for no trailing comma in a method call with ' \
'hash parameters at the end' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1
^^^^ Put a comma after the last parameter of a multiline method call.
#{end_bracket}
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,
#{end_bracket}
RUBY
end
it 'accepts a method call with two parameters on the same line' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}a, b
#{end_bracket}
RUBY
end
it 'accepts trailing comma in a method call with hash parameters at the end' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,
#{end_bracket}
RUBY
end
it 'accepts missing comma after heredoc with comments' do
expect_no_offenses(<<~RUBY)
route#{start_bracket}
a, <<-HELP.chomp
,
# some comment
HELP
#{end_bracket}
RUBY
end
it 'accepts no trailing comma in a method call with a multiline ' \
'braceless hash at the end with more than one parameter on a line' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
a,
b: 0,
c: 0, d: 1
#{end_bracket}
RUBY
end
it 'accepts a trailing comma in a method call with single line hashes' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
{ a: 0, b: 1 },
{ a: 1, b: 0 },
#{end_bracket}
RUBY
end
it 'accepts an empty hash being passed as a method argument' do
expect_no_offenses(<<~RUBY)
Foo.new#{start_bracket}{
}#{end_bracket}
RUBY
end
it 'accepts a multiline call with a single argument and trailing comma' do
expect_no_offenses(<<~RUBY)
method#{start_bracket}
1,
#{end_bracket}
RUBY
end
it 'does not break when a method call is chained on the offending one' do
expect_no_offenses(<<~RUBY)
foo.bar#{start_bracket}
baz: 1,
#{end_bracket}.fetch(:qux)
RUBY
end
it 'does not break when a safe method call is chained on the offending simple one' do
expect_no_offenses(<<~RUBY)
foo
&.do_something#{start_bracket}:bar, :baz#{end_bracket}
RUBY
end
it 'does not break when a safe method call is chained on the offending more complex one' do
expect_no_offenses(<<~RUBY)
foo.bar#{start_bracket}
baz: 1,
#{end_bracket}&.fetch(:qux)
RUBY
end
end
end
end
context 'when EnforcedStyleForMultiline is diff_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'diff_comma' } }
[%w[( )], %w[[ ]]].each do |start_bracket, end_bracket|
context "with `#{start_bracket}#{end_bracket}` brackets" do
it 'registers an offense for no trailing comma when last argument precedes newline' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1
^^^^ Put a comma after the last parameter of a multiline method call.
#{end_bracket}
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,
#{end_bracket}
RUBY
end
it 'registers an offense for trailing comma when last argument is on same line as closing bracket' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}a: "b",
c: "d",#{end_bracket}
^ Avoid comma after the last parameter of a method call, unless that item immediately precedes a newline.
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}a: "b",
c: "d"#{end_bracket}
RUBY
end
it 'registers an offense for trailing comma when last argument is array literal on same line as closing bracket' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
method#{start_bracket}1, [
2,
],#{end_bracket}
^ Avoid comma after the last parameter of a method call, unless that item immediately precedes a newline.
RUBY
expect_correction(<<~RUBY)
method#{start_bracket}1, [
2,
]#{end_bracket}
RUBY
end
it 'accepts trailing comma when last argument precedes newline' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,
#{end_bracket}
RUBY
end
it 'accepts no trailing comma when last argument is on same line as closing bracket' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}a: "b",
c: "d"#{end_bracket}
RUBY
end
it 'accepts no trailing comma when last argument is array literal on same line as closing bracket' do
expect_no_offenses(<<~RUBY)
method#{start_bracket}1, [
2,
]#{end_bracket}
RUBY
end
it 'accepts trailing comma when last argument has inline comment and precedes newline' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1, # comment
#{end_bracket}
RUBY
end
end
end
end
context 'when EnforcedStyleForMultiline is consistent_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } }
[%w[( )], %w[[ ]]].each do |start_bracket, end_bracket|
context "with `#{start_bracket}#{end_bracket}` brackets" do
context 'when closing bracket is on same line as last value' do
it 'registers an offense for a method call, with a Hash as the ' \
'last parameter, split on multiple lines' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}a: "b",
c: "d"#{end_bracket}
^^^^^^ Put a comma after the last parameter of a multiline method call.
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}a: "b",
c: "d",#{end_bracket}
RUBY
end
end
it 'registers an offense for no trailing comma in a method call with ' \
'hash parameters at the end' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1
^^^^ Put a comma after the last parameter of a multiline method call.
#{end_bracket}
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,
#{end_bracket}
RUBY
end
it 'registers an offense for no trailing comma in a method call with' \
'two parameters on the same line' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
some_method#{start_bracket}a, b
^ Put a comma after the last parameter of a multiline method call.
#{end_bracket}
RUBY
expect_correction(<<~RUBY)
some_method#{start_bracket}a, b,
#{end_bracket}
RUBY
end
it 'accepts trailing comma in a method call with hash parameters at the end' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,
#{end_bracket}
RUBY
end
it 'accepts a trailing comma in a method call with a single hash parameter' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
a: 0,
b: 1,
#{end_bracket}
RUBY
end
it 'accepts a trailing comma in a method call with ' \
'a single hash parameter to a receiver object' do
expect_no_offenses(<<~RUBY)
obj.some_method#{start_bracket}
a: 0,
b: 1,
#{end_bracket}
RUBY
end
it 'accepts a trailing comma in a method call with single line hashes' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
{ a: 0, b: 1 },
{ a: 1, b: 0 },
#{end_bracket}
RUBY
end
# this is a sad parse error
it 'accepts no trailing comma in a method call with a block parameter at the end' do
expect_no_offenses(<<~RUBY)
some_method#{start_bracket}
a,
b,
c: 0,
d: 1,
&block
#{end_bracket}
RUBY
end
it 'autocorrects missing comma after a heredoc' do
expect_offense(<<~RUBY, start_bracket: start_bracket, end_bracket: end_bracket)
route#{start_bracket}1, <<-HELP.chomp
^^^^^^^^^^^^^ Put a comma after the last parameter of a multiline method call.
...
HELP
#{end_bracket}
RUBY
expect_correction(<<~RUBY)
route#{start_bracket}1, <<-HELP.chomp,
...
HELP
#{end_bracket}
RUBY
end
it 'accepts a multiline call with a single argument and trailing comma' do
expect_no_offenses(<<~RUBY)
method#{start_bracket}
1,
#{end_bracket}
RUBY
end
it 'accepts a multiline call with arguments on a single line and trailing comma' do
expect_no_offenses(<<~RUBY)
method#{start_bracket}
1, 2,
#{end_bracket}
RUBY
end
it 'accepts a multiline call with single argument on multiple lines' do
expect_no_offenses(<<~RUBY)
method#{start_bracket}a:
"foo"#{end_bracket}
RUBY
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/ip_addresses_spec.rb | spec/rubocop/cop/style/ip_addresses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::IpAddresses, :config do
let(:cop_config) { {} }
it 'does not register an offense on an empty string' do
expect_no_offenses("''")
end
context 'IPv4' do
it 'registers an offense for a valid address' do
expect_offense(<<~RUBY)
'255.255.255.255'
^^^^^^^^^^^^^^^^^ Do not hardcode IP addresses.
RUBY
end
it 'does not register an offense for an invalid address' do
expect_no_offenses('"578.194.591.059"')
end
it 'does not register an offense for an address inside larger text' do
expect_no_offenses('"My IP is 192.168.1.1"')
end
end
context 'IPv6' do
it 'registers an offense for a valid address' do
expect_offense(<<~RUBY)
'2001:0db8:85a3:0000:0000:8a2e:0370:7334'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not hardcode IP addresses.
RUBY
end
it 'registers an offense for an address with 0s collapsed' do
expect_offense(<<~RUBY)
'2001:db8:85a3::8a2e:370:7334'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not hardcode IP addresses.
RUBY
end
it 'registers an offense for a shortened address' do
expect_offense(<<~RUBY)
'2001:db8::1'
^^^^^^^^^^^^^ Do not hardcode IP addresses.
RUBY
end
it 'registers an offense for a very short address' do
expect_offense(<<~RUBY)
'1::'
^^^^^ Do not hardcode IP addresses.
RUBY
end
it 'registers an offense for the loopback address' do
expect_offense(<<~RUBY)
'::1'
^^^^^ Do not hardcode IP addresses.
RUBY
end
it 'does not register an offense for an invalid address' do
expect_no_offenses('"2001:db8::1xyz"')
end
context 'the unspecified address :: (short-form of 0:0:0:0:0:0:0:0)' do
it 'does not register an offense' do
expect_no_offenses('"::"')
end
context 'when it is removed from the allowed addresses' do
let(:cop_config) { { 'AllowedAddresses' => [] } }
it 'registers an offense' do
expect_offense(<<~RUBY)
'::'
^^^^ Do not hardcode IP addresses.
RUBY
end
end
end
end
context 'with allowed addresses' do
let(:cop_config) { { 'AllowedAddresses' => ['a::b'] } }
it 'does not register an offense for an allowed address' do
expect_no_offenses('"a::b"')
end
it 'does not register an offense if the case differs' do
expect_no_offenses('"A::B"')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/sample_spec.rb | spec/rubocop/cop/style/sample_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Sample, :config do
shared_examples 'offense' do |wrong, right|
it "registers an offense for #{wrong}" do
expect_offense(<<~RUBY, wrong: wrong)
[1, 2, 3].%{wrong}
^{wrong} Use `#{right}` instead of `#{wrong}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{right}
RUBY
end
it "registers an offense for safe navigation #{wrong} call" do
expect_offense(<<~RUBY, wrong: wrong)
[1, 2, 3]&.%{wrong}
^{wrong} Use `#{right}` instead of `#{wrong}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.#{right}
RUBY
end
end
shared_examples 'accepts' do |acceptable|
it "accepts #{acceptable}" do
expect_no_offenses("[1, 2, 3].#{acceptable}")
end
end
it_behaves_like('offense', 'shuffle.first', 'sample')
it_behaves_like('offense', 'shuffle.last', 'sample')
it_behaves_like('offense', 'shuffle&.first', 'sample')
it_behaves_like('offense', 'shuffle&.last', 'sample')
it_behaves_like('offense', 'shuffle[0]', 'sample')
it_behaves_like('offense', 'shuffle[-1]', 'sample')
context 'Ruby >= 2.7', :ruby27 do
it_behaves_like('offense', 'shuffle[...3]', 'sample(3)')
end
it_behaves_like('offense', 'shuffle[0, 3]', 'sample(3)')
it_behaves_like('offense', 'shuffle[0..3]', 'sample(4)')
it_behaves_like('offense', 'shuffle[0...3]', 'sample(3)')
it_behaves_like('offense', 'shuffle.first(2)', 'sample(2)')
it_behaves_like('offense', 'shuffle.last(3)', 'sample(3)')
it_behaves_like('offense', 'shuffle.first(foo)', 'sample(foo)')
it_behaves_like('offense', 'shuffle.last(bar)', 'sample(bar)')
it_behaves_like('offense', 'shuffle.at(0)', 'sample')
it_behaves_like('offense', 'shuffle.at(-1)', 'sample')
it_behaves_like('offense', 'shuffle.slice(0)', 'sample')
it_behaves_like('offense', 'shuffle.slice(-1)', 'sample')
it_behaves_like('offense', 'shuffle.slice(0, 3)', 'sample(3)')
it_behaves_like('offense', 'shuffle.slice(0..3)', 'sample(4)')
it_behaves_like('offense', 'shuffle.slice(0...3)', 'sample(3)')
it_behaves_like('offense', 'shuffle(random: Random.new).first', 'sample(random: Random.new)')
it_behaves_like('offense', 'shuffle(random: Random.new).first(2)',
'sample(2, random: Random.new)')
it_behaves_like('offense', 'shuffle(random: foo).last(bar)', 'sample(bar, random: foo)')
it_behaves_like('offense', 'shuffle(random: Random.new)[0..3]', 'sample(4, random: Random.new)')
it_behaves_like('accepts', 'sample')
it_behaves_like('accepts', 'shuffle')
it_behaves_like('accepts', 'shuffle.at(2)') # nil if coll.size < 3
it_behaves_like('accepts', 'shuffle.at(foo)')
it_behaves_like('accepts', 'shuffle.slice(2)') # nil if coll.size < 3
it_behaves_like('accepts', 'shuffle.slice(3, 3)') # nil if coll.size < 3
it_behaves_like('accepts', 'shuffle.slice(2..3)') # empty if coll.size < 3
it_behaves_like('accepts',
'shuffle.slice(2..-3)') # can't compute range size
it_behaves_like('accepts',
'shuffle.slice(foo..3)') # can't compute range size
it_behaves_like('accepts', 'shuffle.slice(-4..-3)') # nil if coll.size < 3
it_behaves_like('accepts', 'shuffle.slice(foo)') # foo could be a Range
it_behaves_like('accepts', 'shuffle.slice(foo, 3)') # nil if coll.size < foo
it_behaves_like('accepts', 'shuffle.slice(foo..bar)')
it_behaves_like('accepts', 'shuffle.slice(foo, bar)')
it_behaves_like('accepts', 'shuffle[2]') # nil if coll.size < 3
it_behaves_like('accepts', 'shuffle[3, 3]') # nil if coll.size < 3
it_behaves_like('accepts', 'shuffle[2..3]') # empty if coll.size < 3
it_behaves_like('accepts', 'shuffle[2..-3]') # can't compute range size
it_behaves_like('accepts', 'shuffle[foo..3]') # can't compute range size
context 'Ruby >= 2.6', :ruby26 do
it_behaves_like('accepts', 'shuffle[3..]') # can't compute range size
it_behaves_like('accepts', 'shuffle[3...]') # can't compute range size
end
it_behaves_like('accepts', 'shuffle[-4..-3]') # nil if coll.size < 3
it_behaves_like('accepts', 'shuffle[foo]') # foo could be a Range
it_behaves_like('accepts', 'shuffle[foo, 3]') # nil if coll.size < foo
it_behaves_like('accepts', 'shuffle[foo..bar]')
it_behaves_like('accepts', 'shuffle[foo, bar]')
it_behaves_like('accepts', 'shuffle(random: Random.new)')
it_behaves_like('accepts', 'shuffle.join([5, 6, 7])')
it_behaves_like('accepts', 'shuffle.map { |e| e }')
it_behaves_like('accepts', 'shuffle(random: Random.new)[2]')
it_behaves_like('accepts', 'shuffle(random: Random.new)[2, 3]')
it_behaves_like('accepts', 'shuffle(random: Random.new).find(&:odd?)')
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_each_spec.rb | spec/rubocop/cop/style/redundant_each_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantEach, :config do
it 'registers an offense when using `each.each`' do
expect_offense(<<~RUBY)
array.each.each { |v| do_something(v) }
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
array.each { |v| do_something(v) }
RUBY
end
it 'registers an offense when using `each&.each`' do
expect_offense(<<~RUBY)
array.each&.each { |v| do_something(v) }
^^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
array.each { |v| do_something(v) }
RUBY
end
it 'registers an offense when using `&.each.each`' do
expect_offense(<<~RUBY)
array&.each.each { |v| do_something(v) }
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
array&.each { |v| do_something(v) }
RUBY
end
it 'registers an offense when using `&.each&.each`' do
expect_offense(<<~RUBY)
array&.each&.each { |v| do_something(v) }
^^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
array&.each { |v| do_something(v) }
RUBY
end
it 'registers an offense when using `each.each(&:foo)`' do
expect_offense(<<~RUBY)
array.each.each(&:foo)
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
array.each(&:foo)
RUBY
end
it 'registers an offense when using `each.each_with_index`' do
expect_offense(<<~RUBY)
array.each.each_with_index { |v| do_something(v) }
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
array.each.with_index { |v| do_something(v) }
RUBY
end
it 'registers an offense when using `each.each_with_object`' do
expect_offense(<<~RUBY)
array.each.each_with_object([]) { |v, o| do_something(v, o) }
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
array.each.with_object([]) { |v, o| do_something(v, o) }
RUBY
end
it 'registers an offense when using a method starting with `each_` with `each_with_index`' do
expect_offense(<<~RUBY)
context.each_child_node.each_with_index.any? do |node, index|
^^^^^^^^^^^^^^^ Use `with_index` to remove redundant `each`.
end
RUBY
expect_correction(<<~RUBY)
context.each_child_node.with_index.any? do |node, index|
end
RUBY
end
it 'registers an offense when using a method starting with `each_` with `each_with_object`' do
expect_offense(<<~RUBY)
context.each_child_node.each_with_object([]) do |node, object|
^^^^^^^^^^^^^^^^ Use `with_object` to remove redundant `each`.
end
RUBY
expect_correction(<<~RUBY)
context.each_child_node.with_object([]) do |node, object|
end
RUBY
end
it 'registers an offense when using `reverse_each.each`' do
expect_offense(<<~RUBY)
context.reverse_each.each { |i| do_something(i) }
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
context.reverse_each { |i| do_something(i) }
RUBY
end
it 'registers an offense when using `reverse_each.each` without a block' do
expect_offense(<<~RUBY)
context.reverse_each.each
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
context.reverse_each
RUBY
end
it 'registers an offense when using `reverse_each&.each`' do
expect_offense(<<~RUBY)
context.reverse_each&.each { |i| do_something(i) }
^^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
context.reverse_each { |i| do_something(i) }
RUBY
end
it 'registers an offense when using `each.reverse_each`' do
expect_offense(<<~RUBY)
context.each.reverse_each { |i| do_something(i) }
^^^^^ Remove redundant `each`.
RUBY
expect_correction(<<~RUBY)
context.reverse_each { |i| do_something(i) }
RUBY
end
it 'registers an offense when using `reverse_each.each_with_index`' do
expect_offense(<<~RUBY)
context.reverse_each.each_with_index.any? do |node, index|
^^^^^^^^^^^^^^^ Use `with_index` to remove redundant `each`.
end
RUBY
expect_correction(<<~RUBY)
context.reverse_each.with_index.any? do |node, index|
end
RUBY
end
it 'registers an offense when using `reverse_each.each_with_object`' do
expect_offense(<<~RUBY)
scope_stack.reverse_each.each_with_object([]) do |scope, variables|
^^^^^^^^^^^^^^^^ Use `with_object` to remove redundant `each`.
end
RUBY
expect_correction(<<~RUBY)
scope_stack.reverse_each.with_object([]) do |scope, variables|
end
RUBY
end
it 'does not register an offense when using only single `each`' do
expect_no_offenses(<<~RUBY)
array.each { |v| do_something(v) }
RUBY
end
it 'does not register an offense when using `each` as enumerator' do
expect_no_offenses(<<~RUBY)
array.each
RUBY
end
it 'does not register an offense when using `each.with_index`' do
expect_no_offenses(<<~RUBY)
array.each.with_index { |v, i| do_something(v, i) }
RUBY
end
it 'does not register an offense when using `each_with_index`' do
expect_no_offenses(<<~RUBY)
array.each_with_index { |v, i| do_something(v, i) }
RUBY
end
it 'does not register an offense when any method is used between methods with `each` in the method name' do
expect_no_offenses(<<~RUBY)
string.each_char.map(&:to_i).reverse.each_with_index.map { |v, i| do_something(v, i) }
RUBY
end
it 'does not register an offense when using `each.with_object`' do
expect_no_offenses(<<~RUBY)
array.each.with_object { |v, o| do_something(v, o) }
RUBY
end
it 'does not register an offense when using `each_with_object`' do
expect_no_offenses(<<~RUBY)
array.each_with_object { |v, o| do_something(v, o) }
RUBY
end
it 'does not register an offense when using `each_with_index.reverse_each`' do
expect_no_offenses(<<~RUBY)
array.each_with_index.reverse_each do |value, index|
end
RUBY
end
it 'does not register an offense when using `each_ancestor.each`' do
expect_no_offenses(<<~RUBY)
node.each_ancestor(:def, :defs, :block).each do |ancestor|
end
RUBY
end
it 'does not register an offense when using `reverse_each {}.each {}`' do
expect_no_offenses(<<~RUBY)
array.reverse_each { |i| foo(i) }.each { |i| bar(i) }
RUBY
end
it 'does not register an offense when using `each {}.reverse_each {}`' do
expect_no_offenses(<<~RUBY)
array.each { |i| foo(i) }.reverse_each { |i| bar(i) }
RUBY
end
it 'does not register an offense when using `each {}.each_with_index {}`' do
expect_no_offenses(<<~RUBY)
array.each { |i| foo(i) }.each_with_index { |i| bar(i) }
RUBY
end
it 'does not register an offense when using `each {}.each_with_object([]) {}`' do
expect_no_offenses(<<~RUBY)
array.each { |i| foo(i) }.each_with_object([]) { |i| bar(i) }
RUBY
end
it 'does not register an offense when using `each_foo {}.each_with_object([]) {}`' do
expect_no_offenses(<<~RUBY)
array.each_foo { |i| foo(i) }.each_with_object([]) { |i| bar(i) }
RUBY
end
it 'does not register an offense when not chaining `each_` calls' do
expect_no_offenses(<<~RUBY)
[foo.each].each
RUBY
end
it 'does not register an offense when using `each` with a symbol proc argument' do
expect_no_offenses(<<~RUBY)
array.each(&:foo).each do |i|
end
RUBY
end
it 'does not register an offense when using `each` with a symbol proc for last argument' do
expect_no_offenses(<<~RUBY)
array.each(foo, &:bar).each do |i|
end
RUBY
end
it 'does not register an offense when using `reverse_each(&:foo).each {...}`' do
expect_no_offenses(<<~RUBY)
array.reverse_each(&:foo).each { |i| bar(i) }
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/fetch_env_var_spec.rb | spec/rubocop/cop/style/fetch_env_var_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FetchEnvVar, :config do
let(:cop_config) { { 'AllowedVars' => [] } }
context 'when it is evaluated with no default values' do
it 'registers an offense' do
expect_offense(<<~RUBY)
ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
ENV.fetch('X', nil)
RUBY
expect_offense(<<~RUBY)
ENV['X' + 'Y']
^^^^^^^^^^^^^^ Use `ENV.fetch('X' + 'Y', nil)` instead of `ENV['X' + 'Y']`.
RUBY
expect_correction(<<~RUBY)
ENV.fetch('X' + 'Y', nil)
RUBY
end
end
context 'with negation' do
it 'registers no offenses' do
expect_no_offenses(<<~RUBY)
!ENV['X']
RUBY
end
end
context 'when it receives a message' do
it 'registers no offenses' do
expect_no_offenses(<<~RUBY)
ENV['X'].some_method
RUBY
end
end
context 'when it receives a message with safe navigation' do
it 'registers no offenses' do
expect_no_offenses(<<~RUBY)
ENV['X']&.some_method
RUBY
end
end
context 'when it is compared `==` with other object' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
ENV['X'] == 1
RUBY
end
end
context 'when it is compared `!=` with other object' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
ENV['X'] != 1
RUBY
end
end
context 'when the node is a receiver of `||=`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
ENV['X'] ||= y
x ||= ENV['X'] ||= y
RUBY
end
end
context 'when the node is a receiver of `&&=`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
ENV['X'] &&= y
x &&= ENV['X'] ||= y
RUBY
end
end
context 'when the node is assigned by `||=`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
y ||= ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
end
end
context 'when the node is assigned by `&&=`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
y &&= ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
end
end
context 'when it is an argument of a method' do
it 'registers an offense' do
expect_offense(<<~RUBY)
some_method(ENV['X'])
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
some_method(ENV.fetch('X', nil))
RUBY
expect_offense(<<~RUBY)
x.some_method(ENV['X'])
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
x.some_method(ENV.fetch('X', nil))
RUBY
expect_offense(<<~RUBY)
some_method(
ENV['A'].some_method,
ENV['B'] || ENV['C'],
^^^^^^^^ Use `ENV.fetch('C', nil)` instead of `ENV['C']`.
ENV['X'],
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
)
RUBY
expect_correction(<<~RUBY)
some_method(
ENV['A'].some_method,
ENV['B'] || ENV.fetch('C', nil),
ENV.fetch('X', nil),
ENV.fetch('Y', nil)
)
RUBY
end
end
context 'when it is assigned to a variable' do
it 'registers an offense when using single assignment' do
expect_offense(<<~RUBY)
x = ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
x = ENV.fetch('X', nil)
RUBY
end
it 'registers an offense when using multiple assignment' do
expect_offense(<<~RUBY)
x, y = ENV['X'],
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
RUBY
expect_correction(<<~RUBY)
x, y = ENV.fetch('X', nil),
ENV.fetch('Y', nil)
RUBY
end
end
context 'when it is an array element' do
it 'registers an offense' do
expect_offense(<<~RUBY)
[
ENV['X'],
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
]
RUBY
expect_correction(<<~RUBY)
[
ENV.fetch('X', nil),
ENV.fetch('Y', nil)
]
RUBY
end
end
context 'when it is a hash key' do
it 'registers an offense' do
expect_offense(<<~RUBY)
{
ENV['X'] => :x,
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
ENV['Y'] => :y
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
}
RUBY
expect_correction(<<~RUBY)
{
ENV.fetch('X', nil) => :x,
ENV.fetch('Y', nil) => :y
}
RUBY
end
end
context 'when it is a hash value' do
it 'registers an offense' do
expect_offense(<<~RUBY)
{
x: ENV['X'],
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
y: ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
}
RUBY
expect_correction(<<~RUBY)
{
x: ENV.fetch('X', nil),
y: ENV.fetch('Y', nil)
}
RUBY
end
end
context 'when it is used in an interpolation' do
it 'registers an offense' do
expect_offense(<<~RUBY)
"\#{ENV['X']}"
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
"\#{ENV.fetch('X', nil)}"
RUBY
end
end
context 'when using `fetch` instead of `[]`' do
it 'registers no offenses' do
expect_no_offenses(<<~RUBY)
ENV.fetch('X')
RUBY
expect_no_offenses(<<~RUBY)
ENV.fetch('X', default_value)
RUBY
end
end
context 'when it is used in a conditional expression' do
it 'registers no offenses with `if`' do
expect_no_offenses(<<~RUBY)
if ENV['X']
puts x
end
RUBY
end
it 'registers no offenses with `unless`' do
expect_no_offenses(<<~RUBY)
unless ENV['X']
puts x
end
RUBY
end
it 'registers no offenses with ternary operator' do
expect_no_offenses(<<~RUBY)
ENV['X'] ? x : y
RUBY
end
it 'registers an offense with `case`' do
expect_offense(<<~RUBY)
case ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
when ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
puts x
end
RUBY
expect_correction(<<~RUBY)
case ENV.fetch('X', nil)
when ENV.fetch('Y', nil)
puts x
end
RUBY
end
it 'registers no offenses when using the same `ENV` var as `if` condition in the body' do
expect_no_offenses(<<~RUBY)
if ENV['X']
puts ENV['X']
end
RUBY
end
it 'registers no offenses when using the same `ENV` var as `if` condition in the body with other conditions' do
expect_no_offenses(<<~RUBY)
if foo? || ENV["X"]
puts ENV.fetch("X")
end
if ENV["Y"] || bar?
puts ENV.fetch("Y")
end
if foo? && ENV["X"]
puts ENV.fetch("X")
end
if ENV["Y"] && bar?
puts ENV.fetch("Y")
end
RUBY
end
it 'registers no offenses when using the same `ENV` var as `if` condition in the body with operator' do
expect_no_offenses(<<~RUBY)
if ENV['X'] == foo
puts ENV['X']
end
if ENV['X'] != foo
puts ENV['X']
end
RUBY
end
it 'registers no offenses when using the same `ENV` var as `if` condition in the body with predicate method' do
expect_no_offenses(<<~RUBY)
if ENV["X"].present?
puts ENV["X"]
end
if ENV["X"].in?(%w[A B C])
puts ENV["X"]
end
if %w[A B C].include?(ENV["X"])
puts ENV["X"]
end
if ENV.key?("X")
puts ENV["X"]
end
RUBY
end
it 'registers an offense when using an `ENV` var that is different from `if` condition in the body' do
expect_offense(<<~RUBY)
if ENV['X']
puts ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
end
RUBY
expect_correction(<<~RUBY)
if ENV['X']
puts ENV.fetch('Y', nil)
end
RUBY
end
it 'registers no offenses when using the same `ENV` var as `if` condition in the body with assignment method' do
expect_no_offenses(<<~RUBY)
if ENV['X'] = x
puts ENV['X']
end
RUBY
end
it 'registers an offense with using an `ENV` var as `if` condition in the body with assignment method' do
expect_offense(<<~RUBY)
if ENV['X'] = x
puts ENV['Y']
^^^^^^^^ Use `ENV.fetch('Y', nil)` instead of `ENV['Y']`.
end
RUBY
expect_correction(<<~RUBY)
if ENV['X'] = x
puts ENV.fetch('Y', nil)
end
RUBY
end
end
it 'registers an offense when using `ENV && x` that is different from `if` condition in the body' do
expect_offense(<<~RUBY)
if ENV && x
ENV[x]
^^^^^^ Use `ENV.fetch(x, nil)` instead of `ENV[x]`.
end
RUBY
expect_correction(<<~RUBY)
if ENV && x
ENV.fetch(x, nil)
end
RUBY
end
it 'registers an offense when using `ENV || x` that is different from `if` condition in the body' do
expect_offense(<<~RUBY)
if ENV || x
ENV[x]
^^^^^^ Use `ENV.fetch(x, nil)` instead of `ENV[x]`.
end
RUBY
expect_correction(<<~RUBY)
if ENV || x
ENV.fetch(x, nil)
end
RUBY
end
it 'registers an offense when using an `ENV` at `if` condition in the body' do
expect_offense(<<~RUBY)
if a == b
ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
end
RUBY
expect_correction(<<~RUBY)
if a == b
ENV.fetch('X', nil)
end
RUBY
end
it 'registers an offense with using an `ENV` at multiple `if` condition in the body' do
expect_offense(<<~RUBY)
if a || b && c
puts ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
end
RUBY
expect_correction(<<~RUBY)
if a || b && c
puts ENV.fetch('X', nil)
end
RUBY
end
context 'when the env val is excluded from the inspection by the config' do
let(:cop_config) { { 'AllowedVars' => ['X'] } }
it 'registers no offenses' do
expect_no_offenses(<<~RUBY)
ENV['X']
RUBY
end
end
context 'when `ENV[]` is the right end of `||` chains' do
it 'registers an offense' do
expect_offense(<<~RUBY)
y || ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
y || z || ENV['X']
^^^^^^^^ Use `ENV.fetch('X', nil)` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
y || ENV.fetch('X', nil)
y || z || ENV.fetch('X', nil)
RUBY
end
end
context 'when `ENV[]` is the LHS of `||`' do
it 'registers no offenses' do
expect_no_offenses(<<~RUBY)
ENV['X'] || y
z || ENV['X'] || y
RUBY
end
end
context 'when `DefaultToNil` is false' do
let(:cop_config) { { 'DefaultToNil' => false } }
it 'registers an offense and corrects to ENV.fetch without nil' do
expect_offense(<<~RUBY)
ENV['X']
^^^^^^^^ Use `ENV.fetch('X')` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
ENV.fetch('X')
RUBY
end
it 'registers an offense for variable assignment' do
expect_offense(<<~RUBY)
x = ENV['X']
^^^^^^^^ Use `ENV.fetch('X')` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
x = ENV.fetch('X')
RUBY
end
it 'registers an offense for method argument' do
expect_offense(<<~RUBY)
some_method(ENV['X'])
^^^^^^^^ Use `ENV.fetch('X')` instead of `ENV['X']`.
RUBY
expect_correction(<<~RUBY)
some_method(ENV.fetch('X'))
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_constant_base_spec.rb | spec/rubocop/cop/style/redundant_constant_base_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantConstantBase, :config do
let(:other_cops) { { 'Lint/ConstantResolution' => { 'Enabled' => false } } }
context 'with prefixed constant in class' do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
class Foo
::Bar
end
RUBY
end
end
context 'with prefixed constant in module' do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
module Foo
::Bar
end
RUBY
end
end
context 'with prefixed constant in neither class nor module' do
it 'registers an offense' do
expect_offense(<<~RUBY)
::Bar
^^ Remove redundant `::`.
RUBY
expect_correction(<<~RUBY)
Bar
RUBY
end
end
context 'with prefixed nested constant in neither class nor module' do
it 'registers an offense' do
expect_offense(<<~RUBY)
::Bar::Baz
^^ Remove redundant `::`.
RUBY
expect_correction(<<~RUBY)
Bar::Baz
RUBY
end
end
context 'with prefixed constant in sclass' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class << self
::Bar
^^ Remove redundant `::`.
end
RUBY
expect_correction(<<~RUBY)
class << self
Bar
end
RUBY
end
end
context 'with prefixed constant as super class' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo < ::Bar
^^ Remove redundant `::`.
end
RUBY
expect_correction(<<~RUBY)
class Foo < Bar
end
RUBY
end
end
context 'with prefixed constant and prefixed super class' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo < ::Bar
^^ Remove redundant `::`.
::A
end
RUBY
expect_correction(<<~RUBY)
class Foo < Bar
::A
end
RUBY
end
end
context 'when `Lint/ConstantResolution` is disabling' do
let(:other_cops) { { 'Lint/ConstantResolution' => { 'Enabled' => true } } }
context 'with prefixed constant in neither class nor module' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
::Bar
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/stabby_lambda_parentheses_spec.rb | spec/rubocop/cop/style/stabby_lambda_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StabbyLambdaParentheses, :config do
shared_examples 'common' do
it 'does not check the old lambda syntax' do
expect_no_offenses('lambda(&:nil?)')
end
it 'does not check a stabby lambda without arguments' do
expect_no_offenses('-> { true }')
end
it 'does not check a method call named lambda' do
expect_no_offenses('o.lambda')
end
end
context 'require_parentheses' do
let(:cop_config) { { 'EnforcedStyle' => 'require_parentheses' } }
it_behaves_like 'common'
it 'registers an offense for a stabby lambda without parentheses' do
expect_offense(<<~RUBY)
->a,b,c { a + b + c }
^^^^^ Wrap stabby lambda arguments with parentheses.
RUBY
expect_correction(<<~RUBY)
->(a,b,c) { a + b + c }
RUBY
end
it 'does not register an offense for a stabby lambda with parentheses' do
expect_no_offenses('->(a,b,c) { a + b + c }')
end
end
context 'require_no_parentheses' do
let(:cop_config) { { 'EnforcedStyle' => 'require_no_parentheses' } }
it_behaves_like 'common'
it 'registers an offense for a stabby lambda with parentheses' do
expect_offense(<<~RUBY)
->(a,b,c) { a + b + c }
^^^^^^^ Do not wrap stabby lambda arguments with parentheses.
RUBY
expect_correction(<<~RUBY)
->a,b,c { a + b + c }
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/exact_regexp_match_spec.rb | spec/rubocop/cop/style/exact_regexp_match_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ExactRegexpMatch, :config do
it 'registers an offense when using `string =~ /\Astring\z/`' do
expect_offense(<<~'RUBY')
string =~ /\Astring\z/
^^^^^^^^^^^^^^^^^^^^^^ Use `string == 'string'`.
RUBY
expect_correction(<<~RUBY)
string == 'string'
RUBY
end
it 'registers an offense when using `string === /\Astring\z/`' do
expect_offense(<<~'RUBY')
string === /\Astring\z/
^^^^^^^^^^^^^^^^^^^^^^^ Use `string == 'string'`.
RUBY
expect_correction(<<~RUBY)
string == 'string'
RUBY
end
it 'registers an offense when using `string.match(/\Astring\z/)`' do
expect_offense(<<~'RUBY')
string.match(/\Astring\z/)
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `string == 'string'`.
RUBY
expect_correction(<<~RUBY)
string == 'string'
RUBY
end
it 'registers an offense when using `string&.match(/\Astring\z/)`' do
expect_offense(<<~'RUBY')
string&.match(/\Astring\z/)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `string == 'string'`.
RUBY
expect_correction(<<~RUBY)
string == 'string'
RUBY
end
it 'does not register an offense when using match without receiver' do
expect_no_offenses('match(/\\Astring\\z/)')
end
it 'registers an offense when using `string.match?(/\Astring\z/)`' do
expect_offense(<<~'RUBY')
string.match?(/\Astring\z/)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `string == 'string'`.
RUBY
expect_correction(<<~RUBY)
string == 'string'
RUBY
end
it 'registers an offense when using `string !~ /\Astring\z/`' do
expect_offense(<<~'RUBY')
string !~ /\Astring\z/
^^^^^^^^^^^^^^^^^^^^^^ Use `string != 'string'`.
RUBY
expect_correction(<<~RUBY)
string != 'string'
RUBY
end
it 'does not register an offense when using `string =~ /\Astring#{interpolation}\z/` (string interpolation)' do
expect_no_offenses(<<~'RUBY')
string =~ /\Astring#{interpolation}\z/
RUBY
end
it 'does not register an offense when using `string === /\A0+\z/` (literal with quantifier)' do
expect_no_offenses(<<~'RUBY')
string === /\A0+\z/
RUBY
end
it 'does not register an offense when using `string =~ /\Astring.*\z/` (any pattern)' do
expect_no_offenses(<<~'RUBY')
string =~ /\Astring.*\z/
RUBY
end
it 'does not register an offense when using `string =~ /^string$/` (multiline matches)' do
expect_no_offenses(<<~RUBY)
string =~ /^string$/
RUBY
end
it 'does not register an offense when using `string =~ /\Astring\z/i` (regexp opt)' do
expect_no_offenses(<<~'RUBY')
string =~ /\Astring\z/i
RUBY
end
context 'invalid regular expressions' do
around { |example| RuboCop::Util.silence_warnings(&example) }
it 'does not register an offense for single invalid regexp' do
expect_no_offenses(<<~'RUBY')
string =~ /^\P$/
RUBY
end
it 'registers an offense for regexp following invalid regexp' do
expect_offense(<<~'RUBY')
string =~ /^\P$/
string.match(/\Astring\z/)
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `string == 'string'`.
RUBY
expect_correction(<<~'RUBY')
string =~ /^\P$/
string == 'string'
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/top_level_method_definition_spec.rb | spec/rubocop/cop/style/top_level_method_definition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TopLevelMethodDefinition, :config do
it 'registers an offense top-level methods' do
expect_offense(<<~RUBY)
def foo; end
^^^^^^^^^^^^ Do not define methods at the top-level.
RUBY
end
it 'registers an offense top-level class methods' do
expect_offense(<<~RUBY)
def self.foo; end
^^^^^^^^^^^^^^^^^ Do not define methods at the top-level.
RUBY
end
context 'top-level define_method' do
it 'registers an offense with inline block' do
expect_offense(<<~RUBY)
define_method(:foo) { puts 1 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not define methods at the top-level.
RUBY
end
context 'Ruby >= 2.7', :ruby27 do
it 'registers an offense with inline numblock' do
expect_offense(<<~RUBY)
define_method(:foo) { puts _1 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not define methods at the top-level.
RUBY
end
end
context 'Ruby >= 3.4', :ruby34 do
it 'registers an offense with inline itblock' do
expect_offense(<<~RUBY)
define_method(:foo) { puts it }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not define methods at the top-level.
RUBY
end
end
it 'registers an offense for multi-line block' do
expect_offense(<<~RUBY)
define_method(:foo) do |x|
^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not define methods at the top-level.
puts 1
end
RUBY
end
it 'registers an offense for proc argument' do
expect_offense(<<~RUBY)
define_method(:foo, instance_method(:bar))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not define methods at the top-level.
RUBY
end
end
it 'registers an offense when defining a top-level method after a class definition' do
expect_offense(<<~RUBY)
class Foo
end
def foo; end
^^^^^^^^^^^^ Do not define methods at the top-level.
RUBY
end
it 'does not register an offense when using module' do
expect_no_offenses(<<~RUBY)
module Foo
def foo; end
end
RUBY
end
it 'does not register an offense when using class' do
expect_no_offenses(<<~RUBY)
class Foo
def self.foo; end
end
RUBY
end
it 'does not register an offense when using Struct' do
expect_no_offenses(<<~RUBY)
Foo = Struct.new do
def foo; end
end
RUBY
end
it 'does not register an offense when defined within arbitrary block' do
expect_no_offenses(<<~RUBY)
Foo = types.each do |type|
def foo(type)
puts type
end
end
RUBY
end
it 'does not register an offense when define_method is not top-level' do
expect_no_offenses(<<~RUBY)
class Foo
define_method(:a) { puts 1 }
define_method(:b) do |x|
puts x
end
define_method(:c, instance_method(:d))
end
RUBY
end
it 'does not register an offense when just called method on top-level' do
expect_no_offenses(<<~RUBY)
require_relative 'foo'
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/magic_comment_format_spec.rb | spec/rubocop/cop/style/magic_comment_format_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MagicCommentFormat, :config do
subject(:cop_config) do
{
'EnforcedStyle' => enforced_style,
'DirectiveCapitalization' => directive_capitalization,
'ValueCapitalization' => value_capitalization
}
end
let(:enforced_style) { 'snake_case' }
let(:directive_capitalization) { nil }
let(:value_capitalization) { nil }
context 'invalid config' do
let(:source) do
<<~RUBY
# encoding: utf-8
puts 1
RUBY
end
context 'DirectiveCapitalization' do
let(:directive_capitalization) { 'foobar' }
it 'raises an error' do
expect { inspect_source(source) }
.to raise_error('Unknown `DirectiveCapitalization` foobar selected!')
end
end
context 'ValueCapitalization' do
let(:value_capitalization) { 'foobar' }
it 'raises an error' do
expect { inspect_source(source) }
.to raise_error('Unknown `ValueCapitalization` foobar selected!')
end
end
end
context 'snake case style' do
let(:enforced_style) { 'snake_case' }
it 'accepts a magic comments in snake case' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
# encoding: utf-8
# shareable_constant_value: literal
# typed: ignore
puts 1
RUBY
end
it 'accepts a frozen string literal in snake case in emacs style' do
expect_no_offenses(<<~RUBY)
# -*- encoding: ASCII-8BIT; frozen_string_literal: true -*-
puts 1
RUBY
end
it 'accepts an empty source' do
expect_no_offenses('')
end
it 'accepts a source with no tokens' do
expect_no_offenses(' ')
end
it 'registers an offense for kebab case' do
expect_offense(<<~RUBY)
# frozen-string-literal: true
^^^^^^^^^^^^^^^^^^^^^ Prefer snake case for magic comments.
# encoding: utf-8
# shareable-constant-value: literal
^^^^^^^^^^^^^^^^^^^^^^^^ Prefer snake case for magic comments.
# typed: ignore
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
# encoding: utf-8
# shareable_constant_value: literal
# typed: ignore
puts 1
RUBY
end
it 'registers an offense for kebab case in emacs style' do
expect_offense(<<~RUBY)
# -*- encoding: ASCII-8BIT; frozen-string-literal: true -*-
^^^^^^^^^^^^^^^^^^^^^ Prefer snake case for magic comments.
puts 1
RUBY
expect_correction(<<~RUBY)
# -*- encoding: ASCII-8BIT; frozen_string_literal: true -*-
puts 1
RUBY
end
it 'registers an offense for mixed case' do
expect_offense(<<~RUBY)
# frozen-string_literal: true
^^^^^^^^^^^^^^^^^^^^^ Prefer snake case for magic comments.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'does not register an offense for dashes in other comments' do
expect_no_offenses('# foo-bar-baz ')
end
it 'does not register an offense for incorrect style in comments after the first statement' do
expect_no_offenses(<<~RUBY)
puts 1
# frozen-string-literal: true
RUBY
end
end
context 'kebab case style' do
let(:enforced_style) { 'kebab_case' }
it 'accepts a magic comments in kebab case' do
expect_no_offenses(<<~RUBY)
# frozen-string-literal: true
# encoding: utf-8
# shareable-constant-value: literal
# typed: ignore
puts 1
RUBY
end
it 'accepts a frozen string literal in snake case in emacs style' do
expect_no_offenses(<<~RUBY)
# -*- encoding: ASCII-8BIT; frozen-string-literal: true -*-
puts 1
RUBY
end
it 'accepts an empty source' do
expect_no_offenses('')
end
it 'accepts a source with no tokens' do
expect_no_offenses(' ')
end
it 'registers an offense for snake case' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
^^^^^^^^^^^^^^^^^^^^^ Prefer kebab case for magic comments.
# encoding: utf-8
# shareable_constant_value: literal
^^^^^^^^^^^^^^^^^^^^^^^^ Prefer kebab case for magic comments.
# typed: ignore
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen-string-literal: true
# encoding: utf-8
# shareable-constant-value: literal
# typed: ignore
puts 1
RUBY
end
it 'registers an offense for snake case in emacs style' do
expect_offense(<<~RUBY)
# -*- encoding: ASCII-8BIT; frozen_string_literal: true -*-
^^^^^^^^^^^^^^^^^^^^^ Prefer kebab case for magic comments.
puts 1
RUBY
expect_correction(<<~RUBY)
# -*- encoding: ASCII-8BIT; frozen-string-literal: true -*-
puts 1
RUBY
end
it 'registers an offense for mixed case' do
expect_offense(<<~RUBY)
# frozen-string_literal: true
^^^^^^^^^^^^^^^^^^^^^ Prefer kebab case for magic comments.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen-string-literal: true
puts 1
RUBY
end
it 'does not register an offense for dashes in other comments' do
expect_no_offenses('# foo-bar-baz ')
end
it 'does not register an offense for incorrect style in comments after the first statement' do
expect_no_offenses(<<~RUBY)
puts 1
# frozen-_string_literal: true
RUBY
end
end
context 'DirectiveCapitalization' do
context 'when not set' do
it 'does not change the case of magic comment directives' do
expect_no_offenses(<<~RUBY)
# eNcOdInG: utf-8
puts 1
RUBY
end
end
context 'when lowercase' do
let(:directive_capitalization) { 'lowercase' }
it 'registers an offense and corrects when the case does not match' do
expect_offense(<<~RUBY)
# eNcOdInG: utf-8
^^^^^^^^ Prefer lower snake case for magic comments.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
puts 1
RUBY
end
end
context 'when uppercase' do
let(:directive_capitalization) { 'uppercase' }
it 'registers an offense and corrects when the case does not match' do
expect_offense(<<~RUBY)
# eNcOdInG: utf-8
^^^^^^^^ Prefer upper snake case for magic comments.
puts 1
RUBY
expect_correction(<<~RUBY)
# ENCODING: utf-8
puts 1
RUBY
end
end
end
context 'ValueCapitalization' do
context 'when not set' do
it 'does not change the case of magic comment directives' do
expect_no_offenses(<<~RUBY)
# encoding: UtF-8
puts 1
RUBY
end
end
context 'when lowercase' do
let(:value_capitalization) { 'lowercase' }
it 'registers an offense and corrects when the case does not match' do
expect_offense(<<~RUBY)
# encoding: UtF-8
^^^^^ Prefer lowercase for magic comment values.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
puts 1
RUBY
end
end
context 'when uppercase' do
let(:value_capitalization) { 'uppercase' }
it 'registers an offense and corrects when the case does not match' do
expect_offense(<<~RUBY)
# encoding: UtF-8
^^^^^ Prefer uppercase for magic comment values.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: UTF-8
puts 1
RUBY
end
end
end
context 'all issues at once' do
let(:enforced_style) { 'snake_case' }
let(:directive_capitalization) { 'uppercase' }
let(:value_capitalization) { 'lowercase' }
it 'registers and corrects multiple issues' do
expect_offense(<<~RUBY)
# frozen-STRING-literal: TRUE
^^^^ Prefer lowercase for magic comment values.
^^^^^^^^^^^^^^^^^^^^^ Prefer upper snake case for magic comments.
puts 1
RUBY
expect_correction(<<~RUBY)
# FROZEN_STRING_LITERAL: true
puts 1
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_regexp_escape_spec.rb | spec/rubocop/cop/style/redundant_regexp_escape_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantRegexpEscape, :config do
context 'with a single-line `//` regexp' do
context 'without escapes' do
it 'does not register an offense' do
expect_no_offenses('foo = /a/')
end
end
context 'with escaped slashes' do
it 'does not register an offense' do
expect_no_offenses('foo = /\/a\//')
end
end
context 'with a line continuation' do
it 'does not register an offense' do
expect_no_offenses("foo = /a\\\nb/")
end
end
context 'with a line continuation within a character class' do
it 'does not register an offense' do
expect_no_offenses("foo = /[a\\\nb]/")
end
end
[
('a'..'z').to_a - %w[c g k n p u x],
('A'..'Z').to_a - %w[C M P],
%w[n101 x41 u0041 u{0041} cc C-c p{alpha} P{alpha}]
].flatten.each do |escape|
context "with an escaped '#{escape}' outside a character class" do
it 'does not register an offense' do
expect_no_offenses("foo = /\\#{escape}/")
end
end
context "with an escaped '#{escape}' inside a character class" do
it 'does not register an offense' do
expect_no_offenses("foo = /[\\#{escape}]/")
end
end
end
context "with an invalid \g escape" do
it 'does not register an offense' do
# See https://ruby-doc.org/core-2.7.1/Regexp.html#class-Regexp-label-Subexpression+Calls
# \g should be \g<name>
expect_no_offenses('foo = /\g/')
end
end
context "with an escaped 'M-a' outside a character class" do
it 'does not register an offense' do
expect_no_offenses('foo = /\\M-a/n')
end
end
context "with an escaped 'M-a' inside a character class" do
it 'does not register an offense' do
expect_no_offenses('foo = /[\\M-a]/n')
end
end
described_class::ALLOWED_OUTSIDE_CHAR_CLASS_METACHAR_ESCAPES.each do |char|
context "with an escaped '#{char}' outside a character class" do
it 'does not register an offense' do
expect_no_offenses("foo = /\\#{char}/")
end
end
context "with an escaped '#{char}' inside a character class" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /[\\#{char}]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /[#{char}]/
RUBY
end
end
end
context "with an escaped '+' inside a character class inside a group" do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /([\+])/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /([+])/
RUBY
end
end
context 'with an escaped . inside a character class beginning with :' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[:\.]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /[:.]/
RUBY
end
end
context "with an escaped '-' character being the last character inside a character class" do
context 'with a regexp %r{...} literal' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = %r{[0-9\-]}
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = %r{[0-9-]}
RUBY
end
end
context 'with a regexp /.../ literal' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[0-9\-]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /[0-9-]/
RUBY
end
end
context "with an escaped opening square bracket before an escaped '-' character" do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\[\-]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~'RUBY')
foo = /[\[-]/
RUBY
end
end
end
context "with an escaped '-' character being the first character inside a character class" do
context 'with a regexp %r{...} literal' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = %r{[\-0-9]}
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = %r{[-0-9]}
RUBY
end
end
context 'with a regexp /.../ literal' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\-0-9]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /[-0-9]/
RUBY
end
end
end
context "with an escaped '-' character being neither first nor last inside a character class" do
it 'does not register an offense' do
expect_no_offenses('foo = %r{[\w\-\#]}')
expect_no_offenses('foo = /[\w\-\#]/')
expect_no_offenses('foo = /[\[\-\]]/')
end
end
context 'with an escaped character class and following escaped char' do
it 'does not register an offense' do
expect_no_offenses('foo = /\[\+/')
end
end
context 'with a character class and following escaped char' do
it 'does not register an offense' do
expect_no_offenses('foo = /[a]\+/')
end
end
context 'with a nested character class then allowed escape' do
it 'does not register an offense' do
expect_no_offenses('foo = /[a-w&&[^c-g]\-1-9]/')
end
end
context 'with a nested character class containing redundant escape' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[[:punct:]&&[^\.]]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /[[:punct:]&&[^.]]/
RUBY
end
end
context 'with a POSIX character class then allowed escape inside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = /[[:alnum:]\-_]+/')
end
end
context 'with a POSIX character class then disallowed escape inside a character class' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[[:alnum:]\.]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /[[:alnum:].]/
RUBY
end
end
context 'with a backreference' do
it 'does not register an offense' do
expect_no_offenses('foo = /([a-z])\s*\1/')
end
end
context 'with an interpolated unnecessary-escape regexp' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /a#{/\-/}c/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~'RUBY')
foo = /a#{/-/}c/
RUBY
end
end
context 'with an escaped instance variable after `#`' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
foo = /[#\@not_ivar]/
RUBY
end
end
context 'with an escaped class variable after `#`' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
foo = /[#\@@not_cvar]/
RUBY
end
end
context 'with an escaped global variable after `#`' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
foo = /[#\$not_gvar]/
RUBY
end
end
context 'with an escape inside an interpolated string' do
it 'does not register an offense' do
expect_no_offenses('foo = /#{"\""}/')
end
end
context 'with an escaped interpolation outside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = /\#\{[a-z_]+\}/')
end
end
context 'with an escaped interpolation inside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = /[\#{}]/')
end
end
context 'with an uppercase metacharacter inside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = /[\H]/')
end
end
context 'with an uppercase metacharacter outside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = /\H/')
end
end
context 'with a free-spaced mode regex' do
context 'with a commented [ and ]' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
r = /
foo # shouldn't start a char class: [
\+ # escape is only redundant inside a char class, so not redundant here
bar # shouldn't end a char class: ]
/x
RUBY
end
end
context 'with a commented redundant escape' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
r = /
foo # redundant unless commented: \-
/x
RUBY
end
end
context 'with a commented redundant escape on a single line' do
it 'does not register an offense' do
expect_no_offenses('r = /foo # redundant unless commented: \-/x')
end
end
context 'with redundant escape preceded by an escaped comment' do
it 'registers offenses and corrects' do
expect_offense(<<~'RUBY')
r = /
foo \# \-
^^ Redundant escape inside regexp literal
/x
RUBY
expect_correction(<<~'RUBY')
r = /
foo \# -
/x
RUBY
end
end
end
context 'with regexp options and a redundant escape' do
it 'registers offenses and corrects' do
expect_offense(<<~'RUBY')
r = /\-/i
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
r = /-/i
RUBY
end
end
context 'with an interpolation followed by redundant escapes' do
it 'registers offenses and corrects' do
expect_offense(<<~'RUBY')
METHOD_NAME = /\#?#{IDENTIFIER}[\!\?]?\(?/.freeze
^^ Redundant escape inside regexp literal
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~'RUBY')
METHOD_NAME = /\#?#{IDENTIFIER}[!?]?\(?/.freeze
RUBY
end
end
context 'with multiple escaped metachars inside a character class' do
it 'registers offenses and corrects' do
expect_offense(<<~'RUBY')
foo = /[\s\(\|\{\[;,\*\=]/
^^ Redundant escape inside regexp literal
^^ Redundant escape inside regexp literal
^^ Redundant escape inside regexp literal
^^ Redundant escape inside regexp literal
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~'RUBY')
foo = /[\s(|{\[;,*=]/
RUBY
end
end
described_class::ALLOWED_ALWAYS_ESCAPES.each do |char|
context "with an escaped '#{char}' outside a character class" do
it 'does not register an offense' do
expect_no_offenses("foo = /\\#{char}/")
end
end
# Avoid an empty character class
next if char == "\n"
context "with an escaped '#{char}' inside a character class" do
it 'does not register an offense' do
expect_no_offenses("foo = /[\\#{char}]/")
end
end
end
described_class::ALLOWED_WITHIN_CHAR_CLASS_METACHAR_ESCAPES.each do |char|
context "with an escaped '#{char}' outside a character class" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /a\\#{char}b/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /a#{char}b/
RUBY
end
end
context "with an escaped '#{char}' inside a character class" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /a[\\#{char}]b/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = /a[#{char}]b/
RUBY
end
end
end
end
context 'with a single-line %r{} regexp' do
context 'without escapes' do
it 'does not register an offense' do
expect_no_offenses('foo = %r{a}')
end
end
context 'with an escaped { or } outside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = %r{\{\}}')
end
end
context 'with an escaped { or } inside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = %r{[\{\}]}')
end
end
context 'with redundantly-escaped slashes' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = %r{\/a\/}
^^ Redundant escape inside regexp literal
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
foo = %r{/a/}
RUBY
end
end
end
[
'!',
'~',
'@',
'_',
'^',
'<>',
'()'
].each do |delims|
l, r = delims.chars
r = l if r.nil?
escaped_delims = "\\#{l}\\#{r}"
context "with a single-line %r#{l}#{r} regexp" do
context 'without escapes' do
it 'does not register an offense' do
expect_no_offenses("foo = %r#{l}a#{r}")
end
end
context 'with escaped delimiters and regexp options' do
it 'does not register an offense' do
expect_no_offenses("foo = %r#{l}#{escaped_delims}#{r}i")
end
end
context 'with escaped delimiters outside a character-class' do
it 'does not register an offense' do
expect_no_offenses("foo = %r#{l}#{escaped_delims}#{r}")
end
end
context 'with escaped delimiters inside a character-class' do
it 'does not register an offense' do
expect_no_offenses("foo = %r#{l}a[#{escaped_delims}]b#{r}")
end
end
end
end
context 'with a single-line %r// regexp' do
context 'without escapes' do
it 'does not register an offense' do
expect_no_offenses('foo = %r/a/')
end
end
context 'with escaped slashes' do
it 'does not register an offense' do
expect_no_offenses('foo = %r/\/a\//')
end
end
end
context 'with a multi-line %r{} regexp' do
context 'without escapes' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo = %r{
a
b
}x
RUBY
end
end
context 'with a # inside a character class' do
it 'does not register an offense' do
# See https://github.com/rubocop/rubocop/issues/8805 - the # inside the character class
# must not be treated as starting a comment (which makes the following \. redundant)
expect_no_offenses(<<~'RUBY')
regexp = %r{
\A[a-z#] # letters or #
\.[a-z]\z # dot + letters
}x
RUBY
end
end
context 'with redundantly-escaped slashes' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = %r{
\/a
^^ Redundant escape inside regexp literal
b\/
^^ Redundant escape inside regexp literal
}x
RUBY
expect_correction(<<~RUBY)
foo = %r{
/a
b/
}x
RUBY
end
end
context 'with a redundant escape after a line with comment' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = %r{
foo # this should not affect the position of the escape below
\-
^^ Redundant escape inside regexp literal
}x
RUBY
expect_correction(<<~RUBY)
foo = %r{
foo # this should not affect the position of the escape below
-
}x
RUBY
end
end
end
context 'with a multi-line %r// regexp' do
context 'without escapes' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo = %r/
a
b
/x
RUBY
end
end
context 'with escaped slashes' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
foo = %r/
\/a
b\/
/x
RUBY
end
end
end
context 'with multibyte characters' do
it 'removes the escape character at the right position' do
# The indicator should take character widths into account in the
# future.
expect_offense(<<~'RUBY')
x = s[/[一二三四\.]+/]
^^ Redundant escape inside regexp literal
p x
RUBY
expect_correction(<<~RUBY)
x = s[/[一二三四.]+/]
p x
RUBY
end
end
context 'with escaping invalid byte sequence in UTF-8' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
r = /[\§]/
^^ Redundant escape inside regexp literal
RUBY
expect_correction(<<~RUBY)
r = /[§]/
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/operator_method_call_spec.rb | spec/rubocop/cop/style/operator_method_call_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::OperatorMethodCall, :config do
described_class::RESTRICT_ON_SEND.each do |operator_method|
it "registers an offense when using `foo.#{operator_method} bar`" do
expect_offense(<<~RUBY, operator_method: operator_method)
foo.#{operator_method} bar
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo #{operator_method} bar
RUBY
end
it "registers an offense when using `foo.#{operator_method}bar`" do
expect_offense(<<~RUBY, operator_method: operator_method)
foo.#{operator_method}bar
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo #{operator_method} bar
RUBY
end
it "does not register an offense when using `foo #{operator_method} bar`" do
expect_no_offenses(<<~RUBY)
foo #{operator_method} bar
RUBY
end
it "registers an offense when using `foo.#{operator_method} 42`" do
expect_offense(<<~RUBY)
foo.#{operator_method} 42
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo #{operator_method} 42
RUBY
end
it "registers an offense when using `foo bar.#{operator_method} baz`" do
expect_offense(<<~RUBY)
foo bar.#{operator_method} baz
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo bar #{operator_method} baz
RUBY
end
unless operator_method == :/
it "registers an offense when using `foo.#{operator_method}(bar)`" do
expect_offense(<<~RUBY, operator_method: operator_method)
foo.#{operator_method}(bar)
^ Redundant dot detected.
RUBY
# Redundant parentheses in `(bar)` are left to `Style/RedundantParentheses` to fix.
expect_correction(<<~RUBY)
foo #{operator_method}(bar)
RUBY
end
end
it "registers an offense when chaining `foo.bar.#{operator_method}(baz).round(2)`" do
expect_offense(<<~RUBY, operator_method: operator_method)
foo.bar.#{operator_method}(baz).quux(2)
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
(foo.bar #{operator_method} baz).quux(2)
RUBY
end
it 'does not register an offense when using multiple arguments' do
expect_no_offenses(<<~RUBY)
foo.#{operator_method}(bar, baz)
RUBY
end
end
it 'registers an offense when using `foo.==({})`' do
expect_offense(<<~RUBY)
foo.==({})
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo ==({})
RUBY
end
it 'registers an offense when using `foo.+ @bar.to_s`' do
expect_offense(<<~RUBY)
foo.+ @bar.to_s
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo + @bar.to_s
RUBY
end
it 'registers an offense and corrects when using `foo./(bar)`' do
expect_offense(<<~RUBY)
foo./(bar)
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo / (bar)
RUBY
end
it 'registers an offense and corrects when using `foo./ (bar)`' do
expect_offense(<<~RUBY)
foo./ (bar)
^ Redundant dot detected.
RUBY
expect_correction(<<~RUBY)
foo / (bar)
RUBY
end
it 'does not register an offense when using `foo.+(@bar).to_s`' do
expect_no_offenses(<<~RUBY)
foo.+(@bar).to_s
RUBY
end
it 'does not register an offense when using `foo.+@bar`' do
expect_no_offenses(<<~RUBY)
foo.+@ bar
RUBY
end
it 'does not register an offense when using `foo.-@bar`' do
expect_no_offenses(<<~RUBY)
foo.-@ bar
RUBY
end
it 'does not register an offense when using `foo.!@bar`' do
expect_no_offenses(<<~RUBY)
foo.!@ bar
RUBY
end
it 'does not register an offense when using `foo.~@bar`' do
expect_no_offenses(<<~RUBY)
foo.~@ bar
RUBY
end
it 'does not register an offense when using `foo.`bar`' do
expect_no_offenses(<<~RUBY)
foo.` bar
RUBY
end
it 'does not register an offense when using `Foo.+(bar)`' do
expect_no_offenses(<<~RUBY)
Foo.+(bar)
RUBY
end
it 'does not register an offense when using `obj.!`' do
expect_no_offenses(<<~RUBY)
obj.!
RUBY
end
it 'does not register an offense when using forwarding method arguments', :ruby27 do
expect_no_offenses(<<~RUBY)
def foo(...)
bar.==(...)
end
RUBY
end
it 'does not register an offense when using named block forwarding' do
expect_no_offenses(<<~RUBY)
def foo(&blk)
bar.==(&blk)
end
RUBY
end
it 'does not register an offense when using anonymous block forwarding', :ruby31 do
expect_no_offenses(<<~RUBY)
def foo(&)
bar.==(&)
end
RUBY
end
it 'does not register an offense when using named rest arguments forwarding' do
expect_no_offenses(<<~RUBY)
def foo(*args)
bar.==(*args)
end
RUBY
end
it 'does not register an offense when using anonymous rest arguments forwarding', :ruby32 do
expect_no_offenses(<<~RUBY)
def foo(*)
bar.==(*)
end
RUBY
end
it 'does not register an offense when named anonymous keyword rest arguments forwarding' do
expect_no_offenses(<<~RUBY)
def foo(**kwargs)
bar.==(**kwargs)
end
RUBY
end
it 'does not register an offense when using anonymous keyword rest arguments forwarding', :ruby32 do
expect_no_offenses(<<~RUBY)
def foo(**)
bar.==(**)
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/for_spec.rb | spec/rubocop/cop/style/for_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::For, :config do
context 'when each is the enforced style' do
let(:cop_config) { { 'EnforcedStyle' => 'each' } }
it 'registers an offense for for' do
expect_offense(<<~RUBY)
def func
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
[1, 2, 3].each do |n|
puts n
end
end
RUBY
end
it 'registers an offense for opposite + correct style' do
expect_offense(<<~RUBY)
def func
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
[1, 2, 3].each do |n|
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
end
RUBY
end
it 'registers multiple offenses' do
expect_offense(<<~RUBY)
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
[1, 2, 3].each do |n|
puts n
end
for n in [1, 2, 3] do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
[1, 2, 3].each do |n|
puts n
end
RUBY
end
context 'autocorrect' do
context 'with range' do
let(:expected_each_with_range) do
<<~RUBY
def func
(1...value).each do |n|
puts n
end
end
RUBY
end
it 'changes for to each' do
expect_offense(<<~RUBY)
def func
for n in (1...value) do
^^^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(expected_each_with_range)
end
it 'changes for that does not have do or semicolon to each' do
expect_offense(<<~RUBY)
def func
for n in (1...value)
^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(expected_each_with_range)
end
context 'without parentheses' do
it 'changes for to each' do
expect_offense(<<~RUBY)
def func
for n in 1...value do
^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(expected_each_with_range)
end
it 'changes for that does not have do or semicolon to each' do
expect_offense(<<~RUBY)
def func
for n in 1...value
^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(expected_each_with_range)
end
end
end
it 'corrects a tuple of items' do
expect_offense(<<~RUBY)
def func
for (a, b) in {a: 1, b: 2, c: 3} do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts a, b
end
end
RUBY
expect_correction(<<~RUBY)
def func
{a: 1, b: 2, c: 3}.each do |(a, b)|
puts a, b
end
end
RUBY
end
it 'changes for that does not have do or semicolon to each' do
expect_offense(<<~RUBY)
def func
for n in [1, 2, 3]
^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
[1, 2, 3].each do |n|
puts n
end
end
RUBY
end
it 'corrects an array with `+` operator' do
expect_offense(<<~RUBY)
def func
a = [1, 2]
b = [3, 4]
c = [5]
for n in a + b + c
^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
a = [1, 2]
b = [3, 4]
c = [5]
(a + b + c).each do |n|
puts n
end
end
RUBY
end
it 'corrects an array with `-` operator' do
expect_offense(<<~RUBY)
def func
a = [1, 2, 3, 4]
b = [3]
for n in a - b
^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
a = [1, 2, 3, 4]
b = [3]
(a - b).each do |n|
puts n
end
end
RUBY
end
it 'corrects an array with `*` operator' do
expect_offense(<<~RUBY)
def func
for n in [1, 2, 3, 4] * 3
^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
([1, 2, 3, 4] * 3).each do |n|
puts n
end
end
RUBY
end
it 'corrects an array with `|` operator' do
expect_offense(<<~RUBY)
def func
a = [1, 2, 3, 4]
b = [4, 5]
for n in a | b
^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
a = [1, 2, 3, 4]
b = [4, 5]
(a | b).each do |n|
puts n
end
end
RUBY
end
it 'corrects an array with `&` operator' do
expect_offense(<<~RUBY)
def func
a = [1, 2, 3, 4]
b = [4, 5]
for n in a & b
^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
a = [1, 2, 3, 4]
b = [4, 5]
(a & b).each do |n|
puts n
end
end
RUBY
end
it 'corrects an array with `&&` operator' do
expect_offense(<<~RUBY)
def func
a = []
b = [1, 2, 3]
for n in a && b
^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
a = []
b = [1, 2, 3]
(a && b).each do |n|
puts n
end
end
RUBY
end
it 'corrects an array with `||` operator' do
expect_offense(<<~RUBY)
def func
a = nil
b = [1, 2, 3]
for n in a || b
^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
a = nil
b = [1, 2, 3]
(a || b).each do |n|
puts n
end
end
RUBY
end
it 'corrects to `each` without parenthesize collection if non-operator method called' do
expect_offense(<<~RUBY)
def func
for n in [1, 2, nil].compact
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
[1, 2, nil].compact.each do |n|
puts n
end
end
RUBY
end
it 'corrects to `each` with safe navigation if collection ends with safe navigation' do
expect_offense(<<~RUBY)
for item in foo&.items
^^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`.
end
RUBY
expect_correction(<<~RUBY)
foo&.items&.each do |item|
end
RUBY
end
end
it 'accepts multiline each' do
expect_no_offenses(<<~RUBY)
def func
[1, 2, 3].each do |n|
puts n
end
end
RUBY
end
it 'accepts :for' do
expect_no_offenses('[:for, :ala, :bala]')
end
it 'accepts def for' do
expect_no_offenses('def for; end')
end
end
context 'when for is the enforced style' do
let(:cop_config) { { 'EnforcedStyle' => 'for' } }
it 'accepts for' do
expect_no_offenses(<<~RUBY)
def func
for n in [1, 2, 3] do
puts n
end
end
RUBY
end
it 'registers an offense for multiline each' do
expect_offense(<<~RUBY)
def func
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
for n in [1, 2, 3] do
puts n
end
end
RUBY
end
it 'registers an offense for each without an item and uses _ as the item' do
expect_offense(<<~RUBY)
def func
[1, 2, 3].each do
^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
something
end
end
RUBY
expect_correction(<<~RUBY)
def func
for _ in [1, 2, 3] do
something
end
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for each without an item and uses _ as the item' do
expect_offense(<<~RUBY)
def func
[1, 2, 3].each do
^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts _1
end
end
RUBY
expect_correction(<<~RUBY)
def func
for _ in [1, 2, 3] do
puts _1
end
end
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for each without an item and uses _ as the item' do
expect_offense(<<~RUBY)
def func
[1, 2, 3].each do
^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts it
end
end
RUBY
expect_correction(<<~RUBY)
def func
for _ in [1, 2, 3] do
puts it
end
end
RUBY
end
end
it 'registers an offense for correct + opposite style' do
expect_offense(<<~RUBY)
def func
for n in [1, 2, 3] do
puts n
end
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
end
RUBY
expect_correction(<<~RUBY)
def func
for n in [1, 2, 3] do
puts n
end
for n in [1, 2, 3] do
puts n
end
end
RUBY
end
it 'registers no offense when there is no receiver' do
expect_no_offenses(<<~RUBY)
each do |n|
puts n
end
RUBY
end
it 'registers multiple offenses' do
expect_offense(<<~RUBY)
for n in [1, 2, 3] do
puts n
end
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
[1, 2, 3].each do |n|
^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts n
end
RUBY
expect_correction(<<~RUBY)
for n in [1, 2, 3] do
puts n
end
for n in [1, 2, 3] do
puts n
end
for n in [1, 2, 3] do
puts n
end
RUBY
end
it 'registers an offense for a tuple of items' do
expect_offense(<<~RUBY)
def func
{a: 1, b: 2, c: 3}.each do |(a, b)|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`.
puts a, b
end
end
RUBY
expect_correction(<<~RUBY)
def func
for (a, b) in {a: 1, b: 2, c: 3} do
puts a, b
end
end
RUBY
end
it 'accepts single line each' do
expect_no_offenses(<<~RUBY)
def func
[1, 2, 3].each { |n| puts n }
end
RUBY
end
context 'when using safe navigation operator', :ruby23 do
it 'does not break' do
expect_no_offenses(<<~RUBY)
def func
[1, 2, 3]&.each { |n| puts n }
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/even_odd_spec.rb | spec/rubocop/cop/style/even_odd_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EvenOdd, :config do
it 'converts x % 2 == 0 to #even?' do
expect_offense(<<~RUBY)
x % 2 == 0
^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.even?
RUBY
end
it 'converts x % 2 != 0 to #odd?' do
expect_offense(<<~RUBY)
x % 2 != 0
^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts (x % 2) == 0 to #even?' do
expect_offense(<<~RUBY)
(x % 2) == 0
^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.even?
RUBY
end
it 'converts (x % 2) != 0 to #odd?' do
expect_offense(<<~RUBY)
(x % 2) != 0
^^^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts x % 2 == 1 to #odd?' do
expect_offense(<<~RUBY)
x % 2 == 1
^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts x % 2 != 1 to #even?' do
expect_offense(<<~RUBY)
x % 2 != 1
^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.even?
RUBY
end
it 'converts (x % 2) == 1 to #odd?' do
expect_offense(<<~RUBY)
(x % 2) == 1
^^^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts (y % 2) != 1 to #even?' do
expect_offense(<<~RUBY)
(y % 2) != 1
^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
y.even?
RUBY
end
it 'converts (x.y % 2) != 1 to #even?' do
expect_offense(<<~RUBY)
(x.y % 2) != 1
^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.y.even?
RUBY
end
it 'converts (x(y) % 2) != 1 to #even?' do
expect_offense(<<~RUBY)
(x(y) % 2) != 1
^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x(y).even?
RUBY
end
it 'accepts x % 2 == 2' do
expect_no_offenses('x % 2 == 2')
end
it 'accepts x % 3 == 0' do
expect_no_offenses('x % 3 == 0')
end
it 'accepts x % 3 != 0' do
expect_no_offenses('x % 3 != 0')
end
it 'converts (x._(y) % 2) != 1 to even?' do
expect_offense(<<~RUBY)
(x._(y) % 2) != 1
^^^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x._(y).even?
RUBY
end
it 'converts (x._(y)) % 2 != 1 to even?' do
expect_offense(<<~RUBY)
(x._(y)) % 2 != 1
^^^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
(x._(y)).even?
RUBY
end
it 'converts x._(y) % 2 != 1 to even?' do
expect_offense(<<~RUBY)
x._(y) % 2 != 1
^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x._(y).even?
RUBY
end
it 'converts 1 % 2 != 1 to even?' do
expect_offense(<<~RUBY)
1 % 2 != 1
^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
1.even?
RUBY
end
it 'converts complex examples' do
expect_offense(<<~RUBY)
if (y % 2) != 1
^^^^^^^^^^^^ Replace with `Integer#even?`.
method == :== ? :even : :odd
elsif x % 2 == 1
^^^^^^^^^^ Replace with `Integer#odd?`.
method == :== ? :odd : :even
end
RUBY
expect_correction(<<~RUBY)
if y.even?
method == :== ? :even : :odd
elsif x.odd?
method == :== ? :odd : :even
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/disable_cops_within_source_code_directive_spec.rb | spec/rubocop/cop/style/disable_cops_within_source_code_directive_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DisableCopsWithinSourceCodeDirective, :config do
it 'registers an offense for disabled cop within source code' do
expect_offense(<<~RUBY)
def foo # rubocop:disable Metrics/CyclomaticComplexity
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuboCop disable/enable directives are not permitted.
end
RUBY
expect_correction(<<~RUBY)
def foo#{trailing_whitespace}
end
RUBY
end
it 'registers an offense for enabled cop within source code' do
expect_offense(<<~RUBY)
def foo # rubocop:enable Metrics/CyclomaticComplexity
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuboCop disable/enable directives are not permitted.
end
RUBY
expect_correction(<<~RUBY)
def foo#{trailing_whitespace}
end
RUBY
end
it 'registers an offense for disabling all cops' do
expect_offense(<<~RUBY)
def foo # rubocop:enable all
^^^^^^^^^^^^^^^^^^^^ RuboCop disable/enable directives are not permitted.
end
RUBY
expect_correction(<<~RUBY)
def foo#{trailing_whitespace}
end
RUBY
end
context 'with AllowedCops' do
let(:cop_config) { { 'AllowedCops' => ['Metrics/CyclomaticComplexity', 'Metrics/AbcSize'] } }
context 'when an allowed cop is disabled' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo # rubocop:disable Metrics/CyclomaticComplexity
end
RUBY
end
end
context 'when a non-allowed cop is disabled' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
def foo # rubocop:disable Layout/LineLength
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuboCop disable/enable directives for `Layout/LineLength` are not permitted.
end
RUBY
expect_correction(<<~RUBY)
def foo#{trailing_whitespace}
end
RUBY
end
end
context 'when a mix of cops are disabled' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
def foo # rubocop:disable Metrics/AbcSize, Layout/LineLength, Metrics/CyclomaticComplexity, Style/AndOr
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuboCop disable/enable directives for `Layout/LineLength`, `Style/AndOr` are not permitted.
end
RUBY
expect_correction(<<~RUBY)
def foo # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
end
RUBY
end
end
context 'when using leading source comment' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
# comment
class Foo
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/send_spec.rb | spec/rubocop/cop/style/send_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Send, :config do
context 'with send' do
context 'and with a receiver' do
it 'registers an offense for an invocation with args' do
expect_offense(<<~RUBY)
Object.send(foo)
^^^^ Prefer `Object#__send__` or `Object#public_send` to `send`.
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense for an invocation with args' do
expect_offense(<<~RUBY)
Object&.send(foo)
^^^^ Prefer `Object#__send__` or `Object#public_send` to `send`.
RUBY
end
end
it 'does not register an offense for an invocation without args' do
expect_no_offenses('Object.send')
end
end
context 'and without a receiver' do
it 'registers an offense for an invocation with args' do
expect_offense(<<~RUBY)
send(foo)
^^^^ Prefer `Object#__send__` or `Object#public_send` to `send`.
RUBY
end
it 'does not register an offense for an invocation without args' do
expect_no_offenses('send')
end
end
end
context 'with __send__' do
context 'and with a receiver' do
it 'does not register an offense for an invocation with args' do
expect_no_offenses('Object.__send__(foo)')
end
it 'does not register an offense for an invocation without args' do
expect_no_offenses('Object.__send__')
end
end
context 'and without a receiver' do
it 'does not register an offense for an invocation with args' do
expect_no_offenses('__send__(foo)')
end
it 'does not register an offense for an invocation without args' do
expect_no_offenses('__send__')
end
end
end
context 'with public_send' do
context 'and with a receiver' do
it 'does not register an offense for an invocation with args' do
expect_no_offenses('Object.public_send(foo)')
end
it 'does not register an offense for an invocation without args' do
expect_no_offenses('Object.public_send')
end
end
context 'and without a receiver' do
it 'does not register an offense for an invocation with args' do
expect_no_offenses('public_send(foo)')
end
it 'does not register an offense for an invocation without args' do
expect_no_offenses('public_send')
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/super_with_args_parentheses_spec.rb | spec/rubocop/cop/style/super_with_args_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SuperWithArgsParentheses, :config do
it 'registers an offense when using `super` without parenthesized arguments' do
expect_offense(<<~RUBY)
super name, age
^^^^^^^^^^^^^^^ Use parentheses for `super` with arguments.
RUBY
expect_correction(<<~RUBY)
super(name, age)
RUBY
end
it 'does not register an offense when using `super` with parenthesized arguments' do
expect_no_offenses(<<~RUBY)
super(name, age)
RUBY
end
it 'does not register an offense when using `super` without arguments' do
expect_no_offenses(<<~RUBY)
super()
RUBY
end
it 'does not register an offense when using zero arity `super`' do
expect_no_offenses(<<~RUBY)
super
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trailing_comma_in_hash_literal_spec.rb | spec/rubocop/cop/style/trailing_comma_in_hash_literal_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrailingCommaInHashLiteral, :config do
shared_examples 'single line lists' do |extra_info|
it 'registers an offense for trailing comma in a literal' do
expect_offense(<<~RUBY)
MAP = { a: 1001, b: 2020, c: 3333, }
^ Avoid comma after the last item of a hash#{extra_info}.
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001, b: 2020, c: 3333 }
RUBY
end
it 'accepts literal without trailing comma' do
expect_no_offenses('MAP = { a: 1001, b: 2020, c: 3333 }')
end
it 'accepts single element literal without trailing comma' do
expect_no_offenses('MAP = { a: 10001 }')
end
it 'accepts empty literal' do
expect_no_offenses('MAP = {}')
end
end
context 'with single line list of values' do
context 'when EnforcedStyleForMultiline is no_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'no_comma' } }
it_behaves_like 'single line lists', ''
end
context 'when EnforcedStyleForMultiline is comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'comma' } }
it_behaves_like 'single line lists', ', unless each item is on its own line'
end
context 'when EnforcedStyleForMultiline is diff_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'diff_comma' } }
it_behaves_like 'single line lists', ', unless that item immediately precedes a newline'
end
context 'when EnforcedStyleForMultiline is consistent_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } }
it_behaves_like 'single line lists', ', unless items are split onto multiple lines'
end
end
context 'with multi-line list of values' do
context 'when EnforcedStyleForMultiline is no_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'no_comma' } }
it 'registers an offense for trailing comma in literal' do
expect_offense(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333,
^ Avoid comma after the last item of a hash.
}
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333
}
RUBY
end
it 'accepts literal with no trailing comma' do
expect_no_offenses(<<~RUBY)
MAP = {
a: 1001,
b: 2020,
c: 3333
}
RUBY
end
it 'accepts comma inside a heredoc parameters at the end' do
expect_no_offenses(<<~RUBY)
route(help: {
'auth' => <<-HELP.chomp
,
HELP
})
RUBY
end
it 'accepts comma in comment after last value item' do
expect_no_offenses(<<~RUBY)
{
foo: 'foo',
bar: 'bar'.delete(',')#,
}
RUBY
end
end
context 'when EnforcedStyleForMultiline is comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'comma' } }
context 'when closing bracket is on same line as last value' do
it 'accepts literal with no trailing comma' do
expect_no_offenses(<<~RUBY)
VALUES = {
a: "b",
c: "d",
e: "f"}
RUBY
end
end
it 'registers an offense for no trailing comma' do
expect_offense(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333
^^^^^^^ Put a comma after the last item of a multiline hash.
}
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333,
}
RUBY
end
it 'registers an offense for trailing comma in a comment' do
expect_offense(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333 # a comment,
^^^^^^^ Put a comma after the last item of a multiline hash.
}
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333, # a comment,
}
RUBY
end
it 'accepts trailing comma' do
expect_no_offenses(<<~RUBY)
MAP = {
a: 1001,
b: 2020,
c: 3333,
}
RUBY
end
it 'accepts trailing comma after a heredoc' do
expect_no_offenses(<<~RUBY)
route(help: {
'auth' => <<-HELP.chomp,
...
HELP
})
RUBY
end
it 'accepts a multiline hash with a single pair and trailing comma' do
expect_no_offenses(<<~RUBY)
bar = {
a: 123,
}
RUBY
end
end
context 'when EnforcedStyleForMultiline is diff_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'diff_comma' } }
context 'when closing bracket is on same line as last value' do
it 'accepts a literal with no trailing comma' do
expect_no_offenses(<<~RUBY)
VALUES = {
a: "b",
b: "c",
d: "e"}
RUBY
end
end
it 'registers an offense for no trailing comma' do
expect_offense(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333
^^^^^^^ Put a comma after the last item of a multiline hash.
}
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333,
}
RUBY
end
it 'accepts trailing comma' do
expect_no_offenses(<<~RUBY)
MAP = {
a: 1001,
b: 2020,
c: 3333,
}
RUBY
end
it 'accepts trailing comma with comment' do
expect_no_offenses(<<~RUBY)
MAP = {
a: 1001,
b: 2020,
c: 3333, # comment
}
RUBY
end
it 'registers an offense for a trailing comma on same line as closing brace' do
expect_offense(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333, }
^ Avoid comma after the last item of a hash, unless that item immediately precedes a newline.
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333 }
RUBY
end
it 'accepts trailing comma after a heredoc' do
expect_no_offenses(<<~RUBY)
route(help: {
'auth' => <<-HELP.chomp,
...
HELP
})
RUBY
end
it 'accepts a multiline hash with a single pair and trailing comma' do
expect_no_offenses(<<~RUBY)
bar = {
a: 123,
}
RUBY
end
it 'accepts a multiline hash with pairs on a single line and trailing comma' do
expect_no_offenses(<<~RUBY)
bar = {
a: 1001, b: 2020,
}
RUBY
end
end
context 'when EnforcedStyleForMultiline is consistent_comma' do
let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } }
context 'when closing bracket is on same line as last value' do
it 'registers an offense for literal with no trailing comma' do
expect_offense(<<~RUBY)
VALUES = {
a: "b",
b: "c",
d: "e"}
^^^^^^ Put a comma after the last item of a multiline hash.
RUBY
expect_correction(<<~RUBY)
VALUES = {
a: "b",
b: "c",
d: "e",}
RUBY
end
end
it 'registers an offense for no trailing comma' do
expect_offense(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333
^^^^^^^ Put a comma after the last item of a multiline hash.
}
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333,
}
RUBY
end
it 'accepts trailing comma' do
expect_no_offenses(<<~RUBY)
MAP = {
a: 1001,
b: 2020,
c: 3333,
}
RUBY
end
it 'registers an offense for no trailing comma on same line as closing brace' do
expect_offense(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333 }
^^^^^^^ Put a comma after the last item of a multiline hash.
RUBY
expect_correction(<<~RUBY)
MAP = { a: 1001,
b: 2020,
c: 3333, }
RUBY
end
it 'accepts trailing comma after a heredoc' do
expect_no_offenses(<<~RUBY)
route(help: {
'auth' => <<-HELP.chomp,
...
HELP
})
RUBY
end
it 'accepts a multiline hash with a single pair and trailing comma' do
expect_no_offenses(<<~RUBY)
bar = {
a: 123,
}
RUBY
end
it 'accepts a multiline hash with pairs on a single line and trailing comma' do
expect_no_offenses(<<~RUBY)
bar = {
a: 1001, b: 2020,
}
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/strip_spec.rb | spec/rubocop/cop/style/strip_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Strip, :config do
it 'registers an offense for `str.lstrip.rstrip`' do
expect_offense(<<~RUBY)
str.lstrip.rstrip
^^^^^^^^^^^^^ Use `strip` instead of `lstrip.rstrip`.
RUBY
expect_correction(<<~RUBY)
str.strip
RUBY
end
it 'registers an offense for `str&.lstrip.rstrip`' do
expect_offense(<<~RUBY)
str&.lstrip.rstrip
^^^^^^^^^^^^^ Use `strip` instead of `lstrip.rstrip`.
RUBY
expect_correction(<<~RUBY)
str&.strip
RUBY
end
it 'registers an offense for `str&.lstrip&.rstrip`' do
expect_offense(<<~RUBY)
str&.lstrip&.rstrip
^^^^^^^^^^^^^^ Use `strip` instead of `lstrip&.rstrip`.
RUBY
expect_correction(<<~RUBY)
str&.strip
RUBY
end
it 'registers an offense for `str.rstrip.lstrip`' do
expect_offense(<<~RUBY)
str.rstrip.lstrip
^^^^^^^^^^^^^ Use `strip` instead of `rstrip.lstrip`.
RUBY
expect_correction(<<~RUBY)
str.strip
RUBY
end
it 'registers an offense for `str&.rstrip.lstrip`' do
expect_offense(<<~RUBY)
str&.rstrip.lstrip
^^^^^^^^^^^^^ Use `strip` instead of `rstrip.lstrip`.
RUBY
expect_correction(<<~RUBY)
str&.strip
RUBY
end
it 'registers an offense for `str&.rstrip&.lstrip`' do
expect_offense(<<~RUBY)
str&.rstrip&.lstrip
^^^^^^^^^^^^^^ Use `strip` instead of `rstrip&.lstrip`.
RUBY
expect_correction(<<~RUBY)
str&.strip
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/empty_heredoc_spec.rb | spec/rubocop/cop/style/empty_heredoc_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyHeredoc, :config do
it 'registers an offense when using empty `<<~EOS` heredoc' do
expect_offense(<<~RUBY)
<<~EOS
^^^^^^ Use an empty string literal instead of heredoc.
EOS
RUBY
expect_correction(<<~RUBY)
''
RUBY
end
it 'registers an offense when using empty `<<-EOS` heredoc' do
expect_offense(<<~RUBY)
<<-EOS
^^^^^^ Use an empty string literal instead of heredoc.
EOS
RUBY
expect_correction(<<~RUBY)
''
RUBY
end
it 'registers an offense when using empty `<<EOS` heredoc' do
expect_offense(<<~RUBY)
<<EOS
^^^^^ Use an empty string literal instead of heredoc.
EOS
RUBY
expect_correction(<<~RUBY)
''
RUBY
end
it 'registers an offense when using empty heredoc single argument' do
expect_offense(<<~RUBY)
do_something(<<~EOS)
^^^^^^ Use an empty string literal instead of heredoc.
EOS
RUBY
expect_correction(<<~RUBY)
do_something('')
RUBY
end
it 'registers an offense when using empty heredoc argument with other argument' do
expect_offense(<<~RUBY)
do_something(<<~EOS, arg)
^^^^^^ Use an empty string literal instead of heredoc.
EOS
RUBY
expect_correction(<<~RUBY)
do_something('', arg)
RUBY
end
it 'does not register an offense when using not empty heredoc' do
expect_no_offenses(<<~RUBY)
<<~EOS
Hello.
EOS
RUBY
end
context 'when double-quoted string literals are preferred' do
let(:other_cops) do
super().merge('Style/StringLiterals' => { 'EnforcedStyle' => 'double_quotes' })
end
it 'registers an offense when using empty `<<~EOS` heredoc' do
expect_offense(<<~RUBY)
<<~EOS
^^^^^^ Use an empty string literal instead of heredoc.
EOS
RUBY
expect_correction(<<~RUBY)
""
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_condition_spec.rb | spec/rubocop/cop/style/redundant_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantCondition, :config do
context 'when regular condition (if)' do
it 'accepts different when the condition does not match the branch' do
expect_no_offenses(<<~RUBY)
if a
b
else
c
end
RUBY
end
it 'accepts elsif' do
expect_no_offenses(<<~RUBY)
if a
b
elsif d
d
else
c
end
RUBY
end
context 'when condition and if_branch are same' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
c
end
RUBY
expect_correction(<<~RUBY)
b || c
RUBY
end
it 'registers an offense and does not autocorrect when if branch has a comment' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
# Important note.
b
else
c
end
RUBY
expect_no_corrections
end
it 'registers an offense and does not autocorrect when else branch has a comment' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
# Important note.
c
end
RUBY
expect_no_corrections
end
it 'does not register an offense when using assignment by hash key access' do
expect_no_offenses(<<~RUBY)
if @cache[key]
@cache[key]
else
@cache[key] = heavy_load[key]
end
RUBY
end
it 'registers an offense and corrects when `raise` without argument parentheses in `else`' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
raise 'foo'
end
RUBY
expect_correction(<<~RUBY)
b || raise('foo')
RUBY
end
it 'registers an offense with extra parentheses and modifier `if` in `else`' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
('foo' if $VERBOSE)
end
RUBY
expect_correction(<<~RUBY)
b || ('foo' if $VERBOSE)
RUBY
end
it 'registers an offense with double extra parentheses and modifier `if` in `else`' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
(('foo' if $VERBOSE))
end
RUBY
expect_correction(<<~RUBY)
b || (('foo' if $VERBOSE))
RUBY
end
it 'registers an offense and corrects when a method without argument parentheses in `else`' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
do_something foo, bar, key: :value
end
RUBY
expect_correction(<<~RUBY)
b || do_something(foo, bar, key: :value)
RUBY
end
it 'registers an offense and corrects when using operator method in `else`' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
c + d
end
RUBY
expect_correction(<<~RUBY)
b || c + d
RUBY
end
it 'registers an offense and corrects complex one liners' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
(c || d)
end
RUBY
expect_correction(<<~RUBY)
b || (c || d)
RUBY
end
it 'registers an offense and corrects modifier nodes offense' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
c while d
end
RUBY
expect_correction(<<~RUBY)
b || (c while d)
RUBY
end
it 'registers an offense and corrects multiline nodes' do
expect_offense(<<~RUBY)
if b
^^^^ Use double pipes `||` instead.
b
else
y(x,
z)
end
RUBY
expect_correction(<<~RUBY)
b || y(x,
z)
RUBY
end
it 'autocorrects when using `<<` method higher precedence than `||` operator' do
expect_offense(<<~RUBY)
ary << if foo
^^^^^^ Use double pipes `||` instead.
foo
else
bar
end
RUBY
expect_correction(<<~RUBY)
ary << (foo || bar)
RUBY
end
it 'accepts complex else branches' do
expect_no_offenses(<<~RUBY)
if b
b
else
c
d
end
RUBY
end
it 'accepts an elsif branch' do
expect_no_offenses(<<~RUBY)
if a
a
elsif cond
d
end
RUBY
end
it 'does not register an offense when using modifier `if`' do
expect_no_offenses(<<~RUBY)
bar if bar
RUBY
end
it 'does not register an offense when using modifier `unless`' do
expect_no_offenses(<<~RUBY)
bar unless bar
RUBY
end
it 'registers an offense and corrects when `if` condition and `then` ' \
'branch are the same and it has no `else` branch' do
expect_offense(<<~RUBY)
if do_something
^^^^^^^^^^^^^^^ This condition is not needed.
do_something
end
RUBY
expect_correction(<<~RUBY)
do_something
RUBY
end
it 'accepts when using ternary if in `else` branch' do
expect_no_offenses(<<~RUBY)
if a
a
else
b ? c : d
end
RUBY
end
it 'registers an offense and corrects when the else branch contains an irange' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
foo
else
1..2
end
RUBY
expect_correction(<<~RUBY)
foo || (1..2)
RUBY
end
it 'registers an offense and corrects when defined inside method and the branches contains assignment' do
expect_offense(<<~RUBY)
def test
if foo
^^^^^^ Use double pipes `||` instead.
@value = foo
else
@value = 'bar'
end
end
RUBY
expect_correction(<<~RUBY)
def test
@value = foo || 'bar'
end
RUBY
end
it 'registers an offense and corrects when the branches contains local variable assignment' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
value = foo
else
value = 'bar'
end
RUBY
expect_correction(<<~RUBY)
value = foo || 'bar'
RUBY
end
it 'registers an offense and corrects when the branches contains instance variable assignment' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
@value = foo
else
@value = 'bar'
end
RUBY
expect_correction(<<~RUBY)
@value = foo || 'bar'
RUBY
end
it 'registers an offense and corrects when the branches contains class variable assignment' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
@@value = foo
else
@@value = 'bar'
end
RUBY
expect_correction(<<~RUBY)
@@value = foo || 'bar'
RUBY
end
it 'registers an offense and corrects when the branches contains global variable assignment' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
$value = foo
else
$value = 'bar'
end
RUBY
expect_correction(<<~RUBY)
$value = foo || 'bar'
RUBY
end
it 'registers an offense and corrects when the branches contains constant assignment' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
CONST = foo
else
CONST = 'bar'
end
RUBY
expect_correction(<<~RUBY)
CONST = foo || 'bar'
RUBY
end
it 'registers an offense and corrects when the branches contains assignment method' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
test.bar = foo
else
test.bar = 'baz'
end
RUBY
expect_correction(<<~RUBY)
test.bar = foo || 'baz'
RUBY
end
it 'registers an offense and corrects when the branches contains arithmetic operation' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
@value - foo
else
@value - 'bar'
end
RUBY
expect_correction(<<~RUBY)
@value - (foo || 'bar')
RUBY
end
it 'registers an offense and corrects when the branches contains method call' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
bar foo
else
bar 1..2
end
RUBY
expect_correction(<<~RUBY)
bar foo || (1..2)
RUBY
end
it 'registers an offense and corrects when the branches contains method call with braced hash' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
bar foo
else
bar({ baz => quux })
end
RUBY
expect_correction(<<~RUBY)
bar foo || { baz => quux }
RUBY
end
it 'registers an offense and corrects when the branches contains method call with non-braced hash' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
bar foo
else
bar baz => quux
end
RUBY
expect_correction(<<~RUBY)
bar foo || { baz => quux }
RUBY
end
it 'registers an offense and corrects when the branches contains parenthesized method call' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
bar(foo)
else
bar(1..2)
end
RUBY
expect_correction(<<~RUBY)
bar(foo || (1..2))
RUBY
end
it 'registers an offense and corrects when the branches contains empty hash literal argument' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use double pipes `||` instead.
bar(foo)
else
bar({})
end
RUBY
expect_correction(<<~RUBY)
bar(foo || {})
RUBY
end
it 'does not register an offense when the branches contains splat argument' do
expect_no_offenses(<<~RUBY)
if foo
bar(foo)
else
bar(*baz)
end
RUBY
end
it 'does not register an offense when the branches contains double splat argument' do
expect_no_offenses(<<~RUBY)
if foo
bar(foo)
else
bar(**baz)
end
RUBY
end
it 'does not register an offense when the branches contains block argument' do
expect_no_offenses(<<~RUBY)
if foo
bar(foo)
else
bar(&baz)
end
RUBY
end
it 'does not register an offense when the branches contains anonymous splat argument', :ruby32 do
expect_no_offenses(<<~RUBY)
def do_something(foo, *)
if foo
bar(foo)
else
bar(*)
end
end
RUBY
end
it 'does not register an offense when the branches contains anonymous double splat argument', :ruby32 do
expect_no_offenses(<<~RUBY)
def do_something(foo, **)
if foo
bar(foo)
else
bar(**)
end
end
RUBY
end
it 'does not register an offense when the branches contains anonymous block argument', :ruby31 do
expect_no_offenses(<<~RUBY)
def do_something(foo, &)
if foo
bar(foo)
else
bar(&)
end
end
RUBY
end
it 'does not register an offense when the branches contains arguments forwarding', :ruby27 do
expect_no_offenses(<<~RUBY)
def do_something(foo, ...)
if foo
bar(foo)
else
bar(...)
end
end
RUBY
end
it 'does not register offenses when using `nil?` and the branches contains assignment' do
expect_no_offenses(<<~RUBY)
if foo.nil?
@value = foo
else
@value = 'bar'
end
RUBY
end
it 'does not register offenses when the branches contains assignment but target not matched' do
expect_no_offenses(<<~RUBY)
if foo
@foo = foo
else
@baz = 'quux'
end
RUBY
end
it 'does not register offenses when using `nil?` and the branches contains method which has multiple arguments' do
expect_no_offenses(<<~RUBY)
if foo.nil?
test.bar foo, bar
else
test.bar = 'baz', 'quux'
end
RUBY
end
it 'does not register offenses when the branches contains hash key access' do
expect_no_offenses(<<~RUBY)
if foo
bar[foo]
else
bar[1]
end
RUBY
end
it 'registers an offense and correct when the branches are the same with the same receivers' do
expect_offense(<<~RUBY)
if x
^^^^ Use double pipes `||` instead.
X.find(x)
else
X.find(y)
end
RUBY
expect_correction(<<~RUBY)
X.find(x || y)
RUBY
end
it 'does not register an offense when the branches are the same with different receivers' do
expect_no_offenses(<<~RUBY)
if x
X.find(x)
else
Y.find(y)
end
RUBY
end
end
context 'when `true` as the true branch' do
it 'does not register an offense when true is used as the true branch and the condition is a local variable' do
expect_no_offenses(<<~RUBY)
variable = do_something
if variable
true
else
a
end
RUBY
end
it 'does not register an offense when true is used as the true branch and the condition is an instance variable' do
expect_no_offenses(<<~RUBY)
if @variable
true
else
a
end
RUBY
end
it 'does not register an offense when true is used as the true branch and the condition is a class variable' do
expect_no_offenses(<<~RUBY)
if @@variable
true
else
a
end
RUBY
end
it 'does not register an offense when true is used as the true branch and the condition is a global variable' do
expect_no_offenses(<<~RUBY)
if $variable
true
else
a
end
RUBY
end
it 'does not register an offense when true is used as the true branch and the condition is a constant' do
expect_no_offenses(<<~RUBY)
if CONST
true
else
a
end
RUBY
end
it 'does not register an offense when true is used as the true branch and the condition is not a predicate method' do
expect_no_offenses(<<~RUBY)
if a[:key]
true
else
a
end
RUBY
end
it 'registers an offense and autocorrects when true is used as the true branch' do
expect_offense(<<~RUBY)
if a.zero?
^^^^^^^^^^ Use double pipes `||` instead.
true
else
a
end
RUBY
expect_correction(<<~RUBY)
a.zero? || a
RUBY
end
it 'registers an offense and autocorrects when true is used as the true branch and the condition uses safe navigation' do
expect_offense(<<~RUBY)
if a&.zero?
^^^^^^^^^^^ Use double pipes `||` instead.
true
else
a
end
RUBY
expect_correction(<<~RUBY)
a&.zero? || a
RUBY
end
it 'registers an offense and autocorrects when true is used as the true branch and the condition takes arguments' do
expect_offense(<<~RUBY)
if foo? arg
^^^^^^^^^^^ Use double pipes `||` instead.
true
else
bar
end
RUBY
expect_correction(<<~RUBY)
foo?(arg) || bar
RUBY
end
it 'registers an offense and autocorrects when true is used the true branch and the condition is a parenthesized predicate call with arguments' do
expect_offense(<<~RUBY)
if foo?(arg)
^^^^^^^^^^^^ Use double pipes `||` instead.
true
else
bar
end
RUBY
expect_correction(<<~RUBY)
foo?(arg) || bar
RUBY
end
it 'registers an offense and autocorrects when true is used as the true branch and the condition takes arguments with safe navigation' do
expect_offense(<<~RUBY)
if obj&.foo? arg
^^^^^^^^^^^^^^^^ Use double pipes `||` instead.
true
else
bar
end
RUBY
expect_correction(<<~RUBY)
obj&.foo?(arg) || bar
RUBY
end
it 'does not register an offense when false is used as the else branch and the condition is not a predicate method' do
expect_no_offenses(<<~RUBY)
if !a[:key]
a
else
false
end
RUBY
end
it 'registers an offense and autocorrects when true is used as the true branch and the false branch is a string' do
expect_offense(<<~RUBY)
if b.nil?
^^^^^^^^^ Use double pipes `||` instead.
true
else
'hello world'
end
RUBY
expect_correction(<<~RUBY)
b.nil? || 'hello world'
RUBY
end
it 'registers an offense and autocorrects when true is used as the true branch and the false branch is an array' do
expect_offense(<<~RUBY)
if c.empty?
^^^^^^^^^^^ Use double pipes `||` instead.
true
else
[1, 2, 3]
end
RUBY
expect_correction(<<~RUBY)
c.empty? || [1, 2, 3]
RUBY
end
context 'when if branch has a comment or else branch has a comment' do
it 'does not autocorrect when the true branch has a comment after it' do
expect_offense(<<~RUBY)
if a.zero?
^^^^^^^^^^ Use double pipes `||` instead.
true # comment
else
a
end
RUBY
expect_no_corrections
end
it 'does not autocorrect when the true branch has a comment before it' do
expect_offense(<<~RUBY)
if a.zero?
^^^^^^^^^^ Use double pipes `||` instead.
# comment
true
else
a
end
RUBY
expect_no_corrections
end
it 'does not autocorrect when the false branch has a comment after it' do
expect_offense(<<~RUBY)
if a.zero?
^^^^^^^^^^ Use double pipes `||` instead.
true
else
a # comment
end
RUBY
expect_no_corrections
end
it 'does not autocorrect when the false branch has a comment before it' do
expect_offense(<<~RUBY)
if a.zero?
^^^^^^^^^^ Use double pipes `||` instead.
true
else
# comment
a
end
RUBY
expect_no_corrections
end
end
end
context 'when the true branch is `not true`' do
it 'does not register an offense when the true branch is a string' do
expect_no_offenses(<<~RUBY)
if a.zero?
'true'
else
a
end
RUBY
end
it 'does not register an offense when the true branch is a quoted string' do
expect_no_offenses(<<~RUBY)
if a.zero?
"true"
else
a
end
RUBY
end
it 'does not register an offense when the true branch is false' do
expect_no_offenses(<<~RUBY)
if a.zero?
false
else
a
end
RUBY
end
it 'does not register an offense when the true branch is a number' do
expect_no_offenses(<<~RUBY)
if a.zero?
1
else
a
end
RUBY
end
it 'does not register an offense when there is no else branch' do
expect_no_offenses(<<~RUBY)
if a.zero?
true
else
end
RUBY
end
it 'does not register an offense when there is no if branch' do
expect_no_offenses(<<~RUBY)
if a.zero?
else
a
end
RUBY
end
it 'does not register an offense when there are two different branches' do
expect_no_offenses(<<~RUBY)
if a.zero?
a
else
b
end
RUBY
end
end
end
context 'ternary expression (?:)' do
it 'accepts expressions when the condition and if branch do not match' do
expect_no_offenses('b ? d : c')
end
it 'registers an offense with extra parentheses and modifier `if` in `else`' do
expect_offense(<<~RUBY)
b ? b : (raise 'foo' if $VERBOSE)
^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
b || (raise 'foo' if $VERBOSE)
RUBY
end
context 'when condition and if_branch are same' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
b ? b : c
^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
b || c
RUBY
end
it 'registers an offense and corrects with empty arguments' do
expect_offense(<<~RUBY)
test ? test : Proc.new {}
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
test || Proc.new {}
RUBY
end
it 'registers an offense and corrects nested vars' do
expect_offense(<<~RUBY)
b.x ? b.x : c
^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
b.x || c
RUBY
end
it 'registers an offense and corrects class vars' do
expect_offense(<<~RUBY)
@b ? @b : c
^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
@b || c
RUBY
end
it 'registers an offense and corrects functions' do
expect_offense(<<~RUBY)
a = b(x) ? b(x) : c
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
a = b(x) || c
RUBY
end
it 'registers an offense and corrects brackets accesses' do
expect_offense(<<~RUBY)
a = b[:x] ? b[:x] : b[:y]
^^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
a = b[:x] || b[:y]
RUBY
end
it 'registers an offense and corrects when the else branch contains an irange' do
expect_offense(<<~RUBY)
time_period = updated_during ? updated_during : 2.days.ago..Time.now
^^^^^^^^^^^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
time_period = updated_during || (2.days.ago..Time.now)
RUBY
end
it 'registers an offense and corrects when the else branch contains an erange' do
expect_offense(<<~RUBY)
time_period = updated_during ? updated_during : 2.days.ago...Time.now
^^^^^^^^^^^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
time_period = updated_during || (2.days.ago...Time.now)
RUBY
end
it 'registers an offense and corrects with ternary expression and the branches contains parenthesized method call' do
expect_offense(<<~RUBY)
foo ? bar(foo) : bar(quux)
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
bar(foo || quux)
RUBY
end
it 'registers an offense and corrects with ternary expression and the branches contains chained parenthesized method call' do
expect_offense(<<~RUBY)
foo ? foo(foo).bar(foo) : foo(foo).bar(quux)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
foo(foo).bar(foo || quux)
RUBY
end
it 'registers an offense and corrects when the else branch contains `rescue`' do
expect_offense(<<~RUBY)
if a
^^^^ Use double pipes `||` instead.
a
else
b rescue c
end
RUBY
expect_correction(<<~RUBY)
a || (b rescue c)
RUBY
end
it 'registers an offense and corrects when the else branch contains `and`' do
expect_offense(<<~RUBY)
if a
^^^^ Use double pipes `||` instead.
a
else
b and c
end
RUBY
expect_correction(<<~RUBY)
a || (b and c)
RUBY
end
end
context 'when `true` as the true branch' do
it 'registers an offense and autocorrects when the true branch is true and the false branch is a variable' do
expect_offense(<<~RUBY)
a.zero? ? true : a
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
a.zero? || a
RUBY
end
it 'registers an offense and autocorrects when the true branch is true and the false branch is a number' do
expect_offense(<<~RUBY)
a.zero? ? true : 5
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
a.zero? || 5
RUBY
end
it 'registers an offense and autocorrects when the true branch is true and the false branch is a string' do
expect_offense(<<~RUBY)
a.zero? ? true : 'a string'
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
a.zero? || 'a string'
RUBY
end
it 'registers an offense and autocorrects when the true branch is true and the false branch is assigned to a variable' do
expect_offense(<<~RUBY)
something = a.zero? ? true : a
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
something = a.zero? || a
RUBY
end
it 'registers an offense and autocorrects when the true branch is true and the false branch is an array' do
expect_offense(<<~RUBY)
b.nil? ? true : [1, 2, 3]
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
b.nil? || [1, 2, 3]
RUBY
end
it 'registers an offense and autocorrects assignment when the true branch is true and the false branch is a variable' do
expect_offense(<<~RUBY)
something = a.nil? ? true : a
^^^^^^^^ Use double pipes `||` instead.
RUBY
expect_correction(<<~RUBY)
something = a.nil? || a
RUBY
end
end
context 'when the true branch is `not true`' do
it 'does not register an offense when the true branch is a string' do
expect_no_offenses(<<~RUBY)
a.zero? ? 'true' : a
RUBY
end
it 'does not register an offense when the true branch is a quoted string' do
expect_no_offenses(<<~RUBY)
a.zero? ? "true" : a
RUBY
end
it 'does not register an offense when the true branch is false' do
expect_no_offenses(<<~RUBY)
a.zero? ? false : a
RUBY
end
it 'does not register an offense when the true branch is a number' do
expect_no_offenses(<<~RUBY)
a.zero? ? 1 : a
RUBY
end
it 'does not register an offense when the true and false branches are different variables' do
expect_no_offenses(<<~RUBY)
a.zero? ? a : b
RUBY
end
end
end
context 'when inverted condition (unless)' do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
unless a
b
else
c
end
RUBY
end
context 'when condition and else branch are same' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless b
^^^^^^^^ Use double pipes `||` instead.
y(x, z)
else
b
end
RUBY
expect_correction(<<~RUBY)
b || y(x, z)
RUBY
end
it 'accepts complex unless branches' do
expect_no_offenses(<<~RUBY)
unless b
c
d
else
b
end
RUBY
end
end
end
context 'when `AllowedMethods: nonzero?`' do
let(:cop_config) { { 'AllowedMethods' => ['nonzero?'] } }
it 'does not register an offense when using `nonzero?`' do
expect_no_offenses(<<~RUBY)
if a.nonzero?
true
else
false
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/open_struct_use_spec.rb | spec/rubocop/cop/style/open_struct_use_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::OpenStructUse, :config do
context 'when using OpenStruct' do
['OpenStruct', '::OpenStruct'].each do |klass|
context "for #{klass}" do
context 'when used in assignments' do
it 'registers an offense' do
expect_offense(<<~RUBY, klass: klass)
a = %{klass}.new(a: 42)
^{klass} Avoid using `OpenStruct`;[...]
RUBY
end
end
context 'when inheriting from it via <' do
it 'registers an offense' do
expect_offense(<<~RUBY, klass: klass)
class SubClass < %{klass}
^{klass} Avoid using `OpenStruct`;[...]
end
RUBY
end
end
context 'when inheriting from it via Class.new' do
it 'registers an offense' do
expect_offense(<<~RUBY, klass: klass)
SubClass = Class.new(%{klass})
^{klass} Avoid using `OpenStruct`;[...]
RUBY
end
end
end
end
end
context 'when using custom namespaced OpenStruct' do
context 'when inheriting from it' do
specify { expect_no_offenses('class A < SomeNamespace::OpenStruct; end') }
end
context 'when defined in custom namespace' do
context 'when class' do
specify do
expect_no_offenses(<<~RUBY)
module SomeNamespace
class OpenStruct
end
end
RUBY
end
end
context 'when module' do
specify do
expect_no_offenses(<<~RUBY)
module SomeNamespace
module OpenStruct
end
end
RUBY
end
end
end
context 'when used in assignments' do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
a = SomeNamespace::OpenStruct.new
RUBY
end
end
end
context 'when not using OpenStruct' do
it 'registers no offense', :aggregate_failures do
expect_no_offenses('class A < B; end')
expect_no_offenses('a = 42')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/single_argument_dig_spec.rb | spec/rubocop/cop/style/single_argument_dig_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SingleArgumentDig, :config do
describe 'dig over literal' do
context 'with single argument' do
it 'registers an offense and corrects unsuitable use of dig' do
expect_offense(<<~RUBY)
{ key: 'value' }.dig(:key)
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `{ key: 'value' }[:key]` instead of `{ key: 'value' }.dig(:key)`.
RUBY
expect_correction(<<~RUBY)
{ key: 'value' }[:key]
RUBY
end
it 'does not register an offense unsuitable use of dig with safe navigation operator' do
expect_no_offenses(<<~RUBY)
{ key: 'value' }&.dig(:key)
RUBY
end
end
context 'with multiple arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
{ key1: { key2: 'value' } }.dig(:key1, :key2)
RUBY
end
end
context 'when using dig with splat operator' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
{ key1: { key2: 'value' } }.dig(*%i[key1 key2])
RUBY
end
end
end
context '>= Ruby 2.7', :ruby27 do
context 'when using dig with arguments forwarding' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo(...)
{ key: 'value' }.dig(...)
end
RUBY
end
end
end
context '>= Ruby 3.1', :ruby31 do
context 'when using dig with anonymous block argument forwarding' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo(&)
{ key: 'value' }.dig(&)
end
RUBY
end
end
end
context 'Ruby <= 3.2', :ruby32 do
context 'when using dig with anonymous rest argument forwarding' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo(*)
{ key: 'value' }.dig(*)
end
RUBY
end
end
context 'when using dig with anonymous keyword argument forwarding' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo(**)
{ key: 'value' }.dig(**)
end
RUBY
end
end
end
describe 'dig over a variable as caller' do
context 'with single argument' do
it 'registers an offense and corrects unsuitable use of dig' do
expect_offense(<<~RUBY)
data.dig(var)
^^^^^^^^^^^^^ Use `data[var]` instead of `data.dig(var)`.
RUBY
expect_correction(<<~RUBY)
data[var]
RUBY
end
end
context 'with multiple arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
data.dig(var1, var2)
RUBY
end
end
context 'when using multiple `dig` in a method chain' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
data.dig(var1)[0].dig(var2)
^^^^^^^^^^^^^^ Use `data[var1]` instead of `data.dig(var1)`.
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `data.dig(var1)[0][var2]` instead of `data.dig(var1)[0].dig(var2)`.
RUBY
expect_correction(<<~RUBY)
data.dig(var1)[0][var2]
RUBY
end
end
context 'when using dig with splat operator' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
data.dig(*[var1, var2])
RUBY
end
end
end
context 'when without a receiver' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
dig(:key)
RUBY
end
end
context 'when there is a chain of digs' do
context 'and `Style/DigChain` is enabled' do
let(:other_cops) do
{ 'Style/DigChain' => { 'Enabled' => true } }
end
it 'does not register an offense for chained `dig` calls' do
expect_no_offenses(<<~RUBY)
data.dig(var1).dig(var2)
RUBY
end
end
context 'and `Style/DigChain` is not enabled' do
let(:other_cops) do
{ 'Style/DigChain' => { 'Enabled' => false } }
end
it 'does registers an offense for chained `dig` calls' do
expect_offense(<<~RUBY)
data.dig(var1).dig(var2)
^^^^^^^^^^^^^^ Use `data[var1]` instead of `data.dig(var1)`.
^^^^^^^^^^^^^^^^^^^^^^^^ Use `data.dig(var1)[var2]` instead of `data.dig(var1).dig(var2)`.
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/min_max_spec.rb | spec/rubocop/cop/style/min_max_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MinMax, :config do
context 'with an array literal containing calls to `#min` and `#max`' do
context 'when the expression stands alone' do
it 'registers an offense if the receivers match' do
expect_offense(<<~RUBY)
[foo.min, foo.max]
^^^^^^^^^^^^^^^^^^ Use `foo.minmax` instead of `[foo.min, foo.max]`.
RUBY
expect_correction(<<~RUBY)
foo.minmax
RUBY
end
it 'does not register an offense if the receivers do not match' do
expect_no_offenses(<<~RUBY)
[foo.min, bar.max]
RUBY
end
it 'does not register an offense if there are additional elements' do
expect_no_offenses(<<~RUBY)
[foo.min, foo.baz, foo.max]
RUBY
end
it 'does not register an offense if the receiver is implicit' do
expect_no_offenses(<<~RUBY)
[min, max]
RUBY
end
end
context 'when the expression is used in a parallel assignment' do
it 'registers an offense if the receivers match' do
expect_offense(<<~RUBY)
bar = foo.min, foo.max
^^^^^^^^^^^^^^^^ Use `foo.minmax` instead of `foo.min, foo.max`.
RUBY
expect_correction(<<~RUBY)
bar = foo.minmax
RUBY
end
it 'does not register an offense if the receivers do not match' do
expect_no_offenses(<<~RUBY)
baz = foo.min, bar.max
RUBY
end
it 'does not register an offense if there are additional elements' do
expect_no_offenses(<<~RUBY)
bar = foo.min, foo.baz, foo.max
RUBY
end
it 'does not register an offense if the receiver is implicit' do
expect_no_offenses(<<~RUBY)
bar = min, max
RUBY
end
end
context 'when the expression is used as a return value' do
it 'registers an offense if the receivers match' do
expect_offense(<<~RUBY)
return foo.min, foo.max
^^^^^^^^^^^^^^^^ Use `foo.minmax` instead of `foo.min, foo.max`.
RUBY
expect_correction(<<~RUBY)
return foo.minmax
RUBY
end
it 'does not register an offense if the receivers do not match' do
expect_no_offenses(<<~RUBY)
return foo.min, bar.max
RUBY
end
it 'does not register an offense if there are additional elements' do
expect_no_offenses(<<~RUBY)
return foo.min, foo.baz, foo.max
RUBY
end
it 'does not register an offense if the receiver is implicit' do
expect_no_offenses(<<~RUBY)
return min, max
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/while_until_modifier_spec.rb | spec/rubocop/cop/style/while_until_modifier_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::WhileUntilModifier, :config do
it_behaves_like 'condition modifier cop', :while
it_behaves_like 'condition modifier cop', :until
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_argument_spec.rb | spec/rubocop/cop/style/redundant_argument_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantArgument, :config do
let(:cop_config) do
{
'Methods' => {
'join' => '', 'sum' => 0, 'exit' => true, 'exit!' => false,
'to_i' => 10, 'split' => ' ', 'chomp' => "\n", 'chomp!' => "\n"
}
}
end
it 'registers an offense and corrects when method called on variable' do
expect_offense(<<~'RUBY')
foo.join('')
^^^^ Argument '' is redundant because it is implied by default.
foo.sum(0)
^^^ Argument 0 is redundant because it is implied by default.
exit(true)
^^^^^^ Argument true is redundant because it is implied by default.
exit!(false)
^^^^^^^ Argument false is redundant because it is implied by default.
foo.to_i(10)
^^^^ Argument 10 is redundant because it is implied by default.
foo.split(' ')
^^^^^ Argument ' ' is redundant because it is implied by default.
foo.chomp("\n")
^^^^^^ Argument "\n" is redundant because it is implied by default.
foo.chomp!("\n")
^^^^^^ Argument "\n" is redundant because it is implied by default.
RUBY
expect_correction(<<~RUBY)
foo.join
foo.sum
exit
exit!
foo.to_i
foo.split
foo.chomp
foo.chomp!
RUBY
end
it 'registers an offense and corrects when safe navigation method called on variable' do
expect_offense(<<~'RUBY')
foo&.join('')
^^^^ Argument '' is redundant because it is implied by default.
foo&.sum(0)
^^^ Argument 0 is redundant because it is implied by default.
foo&.split(' ')
^^^^^ Argument ' ' is redundant because it is implied by default.
foo&.chomp("\n")
^^^^^^ Argument "\n" is redundant because it is implied by default.
foo&.chomp!("\n")
^^^^^^ Argument "\n" is redundant because it is implied by default.
RUBY
expect_correction(<<~RUBY)
foo&.join
foo&.sum
foo&.split
foo&.chomp
foo&.chomp!
RUBY
end
it 'registers an offense and corrects when method called without parenthesis on variable' do
expect_offense(<<~RUBY)
foo.join ''
^^^ Argument '' is redundant because it is implied by default.
foo.split ' '
^^^^ Argument ' ' is redundant because it is implied by default.
RUBY
expect_correction(<<~RUBY)
foo.join
foo.split
RUBY
end
it 'registers an offense and corrects when method called on literals' do
expect_offense(<<~RUBY)
[1, 2, 3].join('')
^^^^ Argument '' is redundant because it is implied by default.
"first second".split(' ')
^^^^^ Argument ' ' is redundant because it is implied by default.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].join
"first second".split
RUBY
end
it 'registers an offense and corrects when method called without parenthesis on literals' do
expect_offense(<<~RUBY)
[1, 2, 3].join ''
^^^ Argument '' is redundant because it is implied by default.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].join
RUBY
end
it 'works with double-quoted strings when configuration is single-quotes' do
expect_offense(<<~RUBY)
foo.join("")
^^^^ Argument "" is redundant because it is implied by default.
"first second".split(" ")
^^^^^ Argument " " is redundant because it is implied by default.
RUBY
expect_correction(<<~RUBY)
foo.join
"first second".split
RUBY
end
it 'does not register an offense when single-quoted strings for newline cntrl character' do
expect_no_offenses(<<~'RUBY')
foo.chomp('\n')
foo.chomp!('\n')
RUBY
end
it 'does not fail on invalid encoding of string literal' do
expect_no_offenses(<<~'RUBY')
foo.chomp("\x82")
RUBY
end
context 'with invalid encoding of string literal configured as default argument' do
let(:cop_config) do
{
'Methods' => {
'chomp' => "\x82"
}
}
end
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo.chomp("\x82")
^^^^^^^^ Argument "\x82" is redundant because it is implied by default.
RUBY
end
end
it 'does not register an offense when method called with no arguments' do
expect_no_offenses(<<~RUBY)
foo.join
"first second".split
RUBY
end
it 'does not register an offense when method called with more than one arguments' do
expect_no_offenses(<<~RUBY)
foo.join('', 2)
[1, 2, 3].split(" ", true, {})
RUBY
end
it 'does not register an offense when method called with different argument' do
expect_no_offenses(<<~RUBY)
foo.join(',')
foo.sum(42)
foo.split(',')
RUBY
end
it 'does not register an offense when method called with no receiver' do
expect_no_offenses(<<~RUBY)
join('')
split(' ')
RUBY
end
context 'non-builtin method' do
let(:cop_config) { { 'Methods' => { 'foo' => 2 } } }
it 'registers an offense and corrects with configured argument' do
expect_offense(<<~RUBY)
A.foo(2)
^^^ Argument 2 is redundant because it is implied by default.
RUBY
expect_correction(<<~RUBY)
A.foo
RUBY
end
it 'does not register an offense with other argument' do
expect_no_offenses(<<~RUBY)
A.foo(5)
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/float_division_spec.rb | spec/rubocop/cop/style/float_division_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FloatDivision, :config do
context 'EnforcedStyle is left_coerce' do
let(:cop_config) { { 'EnforcedStyle' => 'left_coerce' } }
it 'registers an offense and corrects for right coerce' do
expect_offense(<<~RUBY)
a / b.to_f
^^^^^^^^^^ Prefer using `.to_f` on the left side.
RUBY
expect_correction(<<~RUBY)
a.to_f / b
RUBY
end
it 'does not register an offense for right coerce with `nth_ref`' do
expect_no_offenses(<<~RUBY)
a / $1.to_f
RUBY
end
it 'does not register an offense for right coerce with `Regexp.last_match(1)`' do
expect_no_offenses(<<~RUBY)
a / Regexp.last_match(1).to_f
RUBY
end
it 'registers an offense and corrects for both coerce' do
expect_offense(<<~RUBY)
a.to_f / b.to_f
^^^^^^^^^^^^^^^ Prefer using `.to_f` on the left side.
RUBY
expect_correction(<<~RUBY)
a.to_f / b
RUBY
end
it 'does not register an offense for both coerce with `nth_ref`' do
expect_no_offenses(<<~RUBY)
$1.to_f / $2.to_f
RUBY
end
it 'does not register an offense for both coerce with `Regexp.last_match`' do
expect_no_offenses(<<~RUBY)
Regexp.last_match(1).to_f / Regexp.last_match(1).to_f
RUBY
end
it 'does not register an offense for both coerce with `::Regexp.last_match`' do
expect_no_offenses(<<~RUBY)
::Regexp.last_match(1).to_f / ::Regexp.last_match(1).to_f
RUBY
end
it 'registers an offense and corrects for right coerce with calculations' do
expect_offense(<<~RUBY)
(a * b) / (c - d / 2).to_f
^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer using `.to_f` on the left side.
RUBY
expect_correction(<<~RUBY)
(a * b).to_f / (c - d / 2)
RUBY
end
it 'does not register offense for right coerce with implicit receiver' do
expect_no_offenses('a / to_f')
end
it 'does not register offense for left coerce' do
expect_no_offenses('a.to_f / b')
end
end
context 'EnforcedStyle is right_coerce' do
let(:cop_config) { { 'EnforcedStyle' => 'right_coerce' } }
it 'registers an offense and corrects for left coerce' do
expect_offense(<<~RUBY)
a.to_f / b
^^^^^^^^^^ Prefer using `.to_f` on the right side.
RUBY
expect_correction(<<~RUBY)
a / b.to_f
RUBY
end
it 'does not register an offense for left coerce with `nth_ref`' do
expect_no_offenses(<<~RUBY)
$1.to_f / b
RUBY
end
it 'does not register an offense for left coerce with `Regexp.last_match(1)`' do
expect_no_offenses(<<~RUBY)
Regexp.last_match(1).to_f / b
RUBY
end
it 'registers an offense and corrects for both coerce' do
expect_offense(<<~RUBY)
a.to_f / b.to_f
^^^^^^^^^^^^^^^ Prefer using `.to_f` on the right side.
RUBY
expect_correction(<<~RUBY)
a / b.to_f
RUBY
end
it 'registers an offense and corrects for left coerce with calculations' do
expect_offense(<<~RUBY)
(a - b).to_f / (c * 3 * d / 2)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer using `.to_f` on the right side.
RUBY
expect_correction(<<~RUBY)
(a - b) / (c * 3 * d / 2).to_f
RUBY
end
it 'does not register offense for left coerce with implicit receiver' do
expect_no_offenses('to_f / b')
end
it 'does not register offense for right coerce' do
expect_no_offenses('a / b.to_f')
end
end
context 'EnforcedStyle is single_coerce' do
let(:cop_config) { { 'EnforcedStyle' => 'single_coerce' } }
it 'registers an offense and corrects for both coerce' do
expect_offense(<<~RUBY)
a.to_f / b.to_f
^^^^^^^^^^^^^^^ Prefer using `.to_f` on one side only.
RUBY
expect_correction(<<~RUBY)
a.to_f / b
RUBY
end
it 'registers an offense and corrects for left coerce with calculations' do
expect_offense(<<~RUBY)
(a - b).to_f / (3 * d / 2).to_f
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer using `.to_f` on one side only.
RUBY
expect_correction(<<~RUBY)
(a - b).to_f / (3 * d / 2)
RUBY
end
it 'does not register offense for left coerce only' do
expect_no_offenses('a.to_f / b')
end
it 'does not register offense for right coerce only' do
expect_no_offenses('a / b.to_f')
end
it 'does not register offense for left coerce with implicit receiver' do
expect_no_offenses('a / to_f')
end
it 'does not register offense for rigjt coerce with implicit receiver' do
expect_no_offenses('to_f / b')
end
it 'does not register offense for coercions with implicit receivers' do
expect_no_offenses('to_f / to_f')
end
end
context 'EnforcedStyle is fdiv' do
let(:cop_config) { { 'EnforcedStyle' => 'fdiv' } }
it 'registers an offense and corrects for right coerce' do
expect_offense(<<~RUBY)
a / b.to_f
^^^^^^^^^^ Prefer using `fdiv` for float divisions.
RUBY
expect_correction(<<~RUBY)
a.fdiv(b)
RUBY
end
it 'registers an offense and corrects for both coerce' do
expect_offense(<<~RUBY)
a.to_f / b.to_f
^^^^^^^^^^^^^^^ Prefer using `fdiv` for float divisions.
RUBY
expect_correction(<<~RUBY)
a.fdiv(b)
RUBY
end
it 'registers an offense and corrects for left coerce' do
expect_offense(<<~RUBY)
a.to_f / b
^^^^^^^^^^ Prefer using `fdiv` for float divisions.
RUBY
expect_correction(<<~RUBY)
a.fdiv(b)
RUBY
end
it 'registers an offense and corrects for left coerce with calculations' do
expect_offense(<<~RUBY)
(a - b).to_f / (c * 3 * d / 2)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer using `fdiv` for float divisions.
RUBY
expect_correction(<<~RUBY)
(a - b).fdiv(c * 3 * d / 2)
RUBY
end
it 'does not register offense on usage of fdiv' do
expect_no_offenses('a.fdiv(b)')
end
it 'does not register offense for left coerce with implicit receiver' do
expect_no_offenses('to_f / b')
end
it 'does not register offense for right coerce with implicit receiver' do
expect_no_offenses('a / to_f')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/lambda_spec.rb | spec/rubocop/cop/style/lambda_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Lambda, :config do
context 'with enforced `lambda` style' do
let(:cop_config) { { 'EnforcedStyle' => 'lambda' } }
context 'with a single line lambda literal' do
context 'with arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = ->(x) { x }
^^ Use the `lambda` method for all lambdas.
RUBY
expect_correction(<<~RUBY)
f = lambda { |x| x }
RUBY
end
end
context 'without arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = -> { x }
^^ Use the `lambda` method for all lambdas.
RUBY
expect_correction(<<~RUBY)
f = lambda { x }
RUBY
end
end
context 'without argument parens and spaces' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = ->x{ p x }
^^ Use the `lambda` method for all lambdas.
RUBY
expect_correction(<<~RUBY)
f = lambda{ |x| p x }
RUBY
end
end
end
context 'with a multiline lambda literal' do
context 'with arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = ->(x) do
^^ Use the `lambda` method for all lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
f = lambda do |x|
x
end
RUBY
end
end
context 'without arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = -> do
^^ Use the `lambda` method for all lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
f = lambda do
x
end
RUBY
end
end
end
end
context 'with enforced `literal` style' do
let(:cop_config) { { 'EnforcedStyle' => 'literal' } }
context 'with a single line lambda method call' do
context 'with arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda { |x| x }
^^^^^^ Use the `-> { ... }` lambda literal syntax for all lambdas.
RUBY
expect_correction(<<~RUBY)
f = ->(x) { x }
RUBY
end
end
context 'without arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda { x }
^^^^^^ Use the `-> { ... }` lambda literal syntax for all lambdas.
RUBY
expect_correction(<<~RUBY)
f = -> { x }
RUBY
end
end
end
context 'with a multiline lambda method call' do
context 'with arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda do |x|
^^^^^^ Use the `-> { ... }` lambda literal syntax for all lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
f = ->(x) do
x
end
RUBY
end
end
context 'without arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda do
^^^^^^ Use the `-> { ... }` lambda literal syntax for all lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
f = -> do
x
end
RUBY
end
end
end
end
context 'with default `line_count_dependent` style' do
let(:cop_config) { { 'EnforcedStyle' => 'line_count_dependent' } }
context 'with a single line lambda method call' do
context 'with arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda { |x| x }
^^^^^^ Use the `-> { ... }` lambda literal syntax for single line lambdas.
RUBY
expect_correction(<<~RUBY)
f = ->(x) { x }
RUBY
end
end
context 'without arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda { x }
^^^^^^ Use the `-> { ... }` lambda literal syntax for single line lambdas.
RUBY
expect_correction(<<~RUBY)
f = -> { x }
RUBY
end
end
end
context 'with a multiline lambda method call' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
l = lambda do |x|
x
end
RUBY
end
end
context 'with a single line lambda literal' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
lambda = ->(x) { x }
lambda.(1)
RUBY
end
end
context '>= Ruby 2.7', :ruby27 do
context 'when using numbered parameter' do
context 'with a single line lambda method call' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda { _1 }
^^^^^^ Use the `-> { ... }` lambda literal syntax for single line lambdas.
RUBY
expect_correction(<<~RUBY)
f = -> { _1 }
RUBY
end
end
context 'with a multiline `->` call' do
it 'registers an offense' do
expect_offense(<<~RUBY)
-> {
^^ Use the `lambda` method for multiline lambdas.
_1.do_something
}
RUBY
expect_correction(<<~RUBY)
lambda {
_1.do_something
}
RUBY
end
end
context 'with a multiline lambda method call' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
l = lambda do
_1
end
RUBY
end
end
context 'with a single line lambda literal' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
lambda = -> { _1 }
lambda.(1)
RUBY
end
end
end
end
context '>= Ruby 3.4', :ruby34 do
context 'when using `it` parameter' do
context 'with a single line lambda method call' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = lambda { it }
^^^^^^ Use the `-> { ... }` lambda literal syntax for single line lambdas.
RUBY
expect_correction(<<~RUBY)
f = -> { it }
RUBY
end
end
context 'with a multiline `->` call' do
it 'registers an offense' do
expect_offense(<<~RUBY)
-> {
^^ Use the `lambda` method for multiline lambdas.
it.do_something
}
RUBY
expect_correction(<<~RUBY)
lambda {
it.do_something
}
RUBY
end
end
context 'with a multiline lambda method call' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
l = lambda do
it
end
RUBY
end
end
context 'with a single line lambda literal' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
lambda = -> { it }
lambda.(1)
RUBY
end
end
end
end
context 'with a multiline lambda literal' do
context 'with arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = ->(x) do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
f = lambda do |x|
x
end
RUBY
end
end
context 'without arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
f = -> do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
f = lambda do
x
end
RUBY
end
end
end
context 'unusual lack of spacing' do
# The lack of spacing shown here is valid ruby syntax,
# and can be the result of previous autocorrects re-writing
# a multi-line `->(x){ ... }` to `->(x)do ... end`.
# See rubocop/cop/style/block_delimiters.rb.
# Tests correction of an issue resulting in `lambdado` syntax errors.
context 'without any spacing' do
it 'registers an offense' do
expect_offense(<<~RUBY)
->(x)do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
lambda do |x|
x
end
RUBY
end
end
context 'without spacing after arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
-> (x)do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
lambda do |x|
x
end
RUBY
end
end
context 'without spacing before arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
->(x) do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
lambda do |x|
x
end
RUBY
end
end
context 'with a multiline lambda literal' do
context 'with empty arguments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
->()do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
lambda do
x
end
RUBY
end
end
context 'with no arguments and bad spacing' do
it 'registers an offense' do
expect_offense(<<~RUBY)
-> ()do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
lambda do
x
end
RUBY
end
end
context 'with no arguments and no spacing' do
it 'registers an offense' do
expect_offense(<<~RUBY)
->do
^^ Use the `lambda` method for multiline lambdas.
x
end
RUBY
expect_correction(<<~RUBY)
lambda do
x
end
RUBY
end
end
context 'without parentheses' do
it 'registers an offense' do
expect_offense(<<~RUBY)
-> hello do
^^ Use the `lambda` method for multiline lambdas.
puts hello
end
RUBY
expect_correction(<<~RUBY)
lambda do |hello|
puts hello
end
RUBY
end
end
context 'with no parentheses and bad spacing' do
it 'registers an offense' do
expect_offense(<<~RUBY)
-> hello do
^^ Use the `lambda` method for multiline lambdas.
puts hello
end
RUBY
expect_correction(<<~RUBY)
lambda do |hello|
puts hello
end
RUBY
end
end
context 'with no parentheses and many args' do
it 'registers an offense' do
expect_offense(<<~RUBY)
-> hello, user do
^^ Use the `lambda` method for multiline lambdas.
puts hello
end
RUBY
expect_correction(<<~RUBY)
lambda do |hello, user|
puts hello
end
RUBY
end
end
end
end
context 'when calling a lambda method without a block' do
it 'does not register an offense' do
expect_no_offenses('l = lambda.test')
end
end
context 'with a multiline lambda literal as an argument' do
it 'registers an offense' do
expect_offense(<<~RUBY)
has_many :kittens, -> do
^^ Use the `lambda` method for multiline lambdas.
where(cats: Cat.young.where_values_hash)
end, source: cats
RUBY
expect_correction(<<~RUBY)
has_many :kittens, lambda {
where(cats: Cat.young.where_values_hash)
}, source: cats
RUBY
end
end
context 'with a multiline braces lambda literal as a keyword argument' do
it 'registers an offense' do
expect_offense(<<~RUBY)
has_many opt: -> do
^^ Use the `lambda` method for multiline lambdas.
where(cats: Cat.young.where_values_hash)
end
RUBY
expect_correction(<<~RUBY)
has_many opt: lambda {
where(cats: Cat.young.where_values_hash)
}
RUBY
end
end
context 'with a multiline do-end lambda literal as a keyword argument' do
it 'registers an offense' do
expect_offense(<<~RUBY)
has_many opt: -> {
^^ Use the `lambda` method for multiline lambdas.
where(cats: Cat.young.where_values_hash)
}
RUBY
expect_correction(<<~RUBY)
has_many opt: lambda {
where(cats: Cat.young.where_values_hash)
}
RUBY
end
end
context 'with a multiline do-end lambda as a parenthesized kwarg' do
it 'registers an offense' do
expect_offense(<<~RUBY)
has_many(
opt: -> do
^^ Use the `lambda` method for multiline lambdas.
where(cats: Cat.young.where_values_hash)
end
)
RUBY
expect_correction(<<~RUBY)
has_many(
opt: lambda do
where(cats: Cat.young.where_values_hash)
end
)
RUBY
end
end
end
context 'when using safe navigation operator', :ruby23 do
it 'does not break' do
expect_no_offenses(<<~RUBY)
foo&.bar do |_|
baz
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/conditional_assignment_assign_to_condition_spec.rb | spec/rubocop/cop/style/conditional_assignment_assign_to_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ConditionalAssignment, :config do
let(:config) do
RuboCop::Config.new('Style/ConditionalAssignment' => {
'Enabled' => true,
'SingleLineConditionsOnly' => true,
'IncludeTernaryExpressions' => true,
'EnforcedStyle' => 'assign_to_condition',
'SupportedStyles' => %w[assign_to_condition
assign_inside_condition]
},
'Layout/EndAlignment' => {
'EnforcedStyleAlignWith' => end_alignment_align_with,
'Enabled' => true
},
'Layout/LineLength' => {
'Max' => 80,
'Enabled' => true
})
end
let(:end_alignment_align_with) { 'start_of_line' }
shared_examples 'else followed by new conditional without else' do |keyword|
it "allows if elsif else #{keyword}" do
expect_no_offenses(<<~RUBY)
if var.any?(:prob_a_check)
@errors << 'Problem A'
elsif var.any?(:prob_a_check)
@errors << 'Problem B'
else
#{keyword} var.all?(:save)
@errors << 'Save failed'
end
end
RUBY
end
end
it_behaves_like 'else followed by new conditional without else', 'if'
it_behaves_like 'else followed by new conditional without else', 'unless'
context 'for if elsif else if else' do
let(:annotated_source) do
<<~RUBY
if var.any?(:prob_a_check)
@errors << 'Problem A'
elsif var.any?(:prob_a_check)
@errors << 'Problem B'
else
if var.all?(:save)
^^^^^^^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
@errors << 'Save failed'
else
@errors << 'Other'
end
end
RUBY
end
it 'autocorrects the inner offense first' do
expect_offense(annotated_source)
expect_correction(<<~RUBY, loop: false)
if var.any?(:prob_a_check)
@errors << 'Problem A'
elsif var.any?(:prob_a_check)
@errors << 'Problem B'
else
@errors << if var.all?(:save)
'Save failed'
else
'Other'
end
end
RUBY
end
it 'autocorrects the outer offense later' do
expect_offense(annotated_source)
expect_correction(<<~RUBY, loop: true)
@errors << if var.any?(:prob_a_check)
'Problem A'
elsif var.any?(:prob_a_check)
'Problem B'
else
if var.all?(:save)
'Save failed'
else
'Other'
end
end
RUBY
end
end
it 'counts array assignment when determining multiple assignment' do
expect_no_offenses(<<~RUBY)
if foo
array[1] = 1
a = 1
else
array[1] = 2
a = 2
end
RUBY
end
it 'allows method calls in conditionals' do
expect_no_offenses(<<~RUBY)
if line.is_a?(String)
expect(actual[ix]).to eq(line)
else
expect(actual[ix]).to match(line)
end
RUBY
end
it 'allows if else without variable assignment' do
expect_no_offenses(<<~RUBY)
if foo
1
else
2
end
RUBY
end
it 'allows assignment to the result of a ternary operation' do
expect_no_offenses('bar = foo? ? "a" : "b"')
end
it 'registers an offense for assignment in ternary operation using strings' do
expect_offense(<<~RUBY)
foo? ? bar = "a" : bar = "b"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
RUBY
expect_correction(<<~RUBY)
bar = foo? ? "a" : "b"
RUBY
end
it 'allows modifier if' do
expect_no_offenses('return if a == 1')
end
it 'allows modifier if inside of if else' do
expect_no_offenses(<<~RUBY)
if foo
a unless b
else
c unless d
end
RUBY
end
it "doesn't crash when assignment statement uses chars which have " \
'special meaning in a regex' do
# regression test; see GH issue 2876
expect_offense(<<~RUBY)
if condition
^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
default['key-with-dash'] << a
else
default['key-with-dash'] << b
end
RUBY
expect_correction(<<~RUBY)
default['key-with-dash'] << if condition
a
else
b
end
RUBY
end
it "doesn't crash with empty braces" do
expect_no_offenses(<<~RUBY)
if condition
()
else
()
end
RUBY
end
shared_examples 'comparison methods' do |method|
it 'registers an offense for comparison methods in ternary operations' do
source = "foo? ? bar #{method} 1 : bar #{method} 2"
expect_offense(<<~RUBY, source: source)
%{source}
^{source} Use the return of the conditional for variable assignment and comparison.
RUBY
expect_correction(<<~RUBY)
bar #{method} (foo? ? 1 : 2)
RUBY
end
%w[start_of_line keyword].each do |align_with|
context "with end alignment to #{align_with}" do
let(:end_alignment_align_with) { align_with }
let(:indent_end) { align_with == 'keyword' }
it 'corrects comparison methods in if elsif else' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
a #{method} b
elsif bar
a #{method} c
else
a #{method} d
end
RUBY
indent = ' ' * "a #{method} ".length if indent_end
expect_correction(<<~RUBY)
a #{method} if foo
b
elsif bar
c
else
d
#{indent}end
RUBY
end
it 'corrects comparison methods in unless else' do
expect_offense(<<~RUBY)
unless foo
^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
a #{method} b
else
a #{method} d
end
RUBY
indent = ' ' * "a #{method} ".length if indent_end
expect_correction(<<~RUBY)
a #{method} unless foo
b
else
d
#{indent}end
RUBY
end
it 'corrects comparison methods in case when' do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
when bar
a #{method} b
else
a #{method} d
end
RUBY
indent = ' ' * "a #{method} ".length if indent_end
expect_correction(<<~RUBY)
a #{method} case foo
when bar
b
else
d
#{indent}end
RUBY
end
context '>= Ruby 2.7', :ruby27 do
it 'corrects comparison methods in case in' do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
in bar
a #{method} b
else
a #{method} d
end
RUBY
indent = ' ' * "a #{method} ".length if indent_end
expect_correction(<<~RUBY)
a #{method} case foo
in bar
b
else
d
#{indent}end
RUBY
end
end
end
end
end
it_behaves_like('comparison methods', '==')
it_behaves_like('comparison methods', '!=')
it_behaves_like('comparison methods', '=~')
it_behaves_like('comparison methods', '!~')
it_behaves_like('comparison methods', '<=>')
it_behaves_like('comparison methods', '===')
it_behaves_like('comparison methods', '<=')
it_behaves_like('comparison methods', '>=')
it_behaves_like('comparison methods', '<')
it_behaves_like('comparison methods', '>')
context 'empty branch' do
it 'allows an empty if statement' do
expect_no_offenses(<<~RUBY)
if foo
# comment
else
do_something
end
RUBY
end
it 'allows an empty elsif statement' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
elsif baz
# empty
else
bar = 2
end
RUBY
end
it 'allows if elsif without else' do
expect_no_offenses(<<~RUBY)
if foo
bar = 'some string'
elsif bar
bar = 'another string'
end
RUBY
end
it 'allows assignment in if without an else' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
end
RUBY
end
it 'allows assignment in unless without an else' do
expect_no_offenses(<<~RUBY)
unless foo
bar = 1
end
RUBY
end
it 'allows assignment in case when without an else' do
expect_no_offenses(<<~RUBY)
case foo
when "a"
bar = 1
when "b"
bar = 2
end
RUBY
end
it 'allows an empty when branch with an else' do
expect_no_offenses(<<~RUBY)
case foo
when "a"
# empty
when "b"
bar = 2
else
bar = 3
end
RUBY
end
it 'allows case with an empty else' do
expect_no_offenses(<<~RUBY)
case foo
when "b"
bar = 2
else
# empty
end
RUBY
end
end
it 'allows assignment of different variables in if else' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
else
baz = 1
end
RUBY
end
it 'allows method calls in if else' do
expect_no_offenses(<<~RUBY)
if foo
bar
else
baz
end
RUBY
end
it 'allows if elsif else with the same assignment only in if else' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
elsif foobar
baz = 2
else
bar = 1
end
RUBY
end
it 'allows if elsif else with the same assignment only in if elsif' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
elsif foobar
bar = 2
else
baz = 1
end
RUBY
end
it 'allows if elsif else with the same assignment only in elsif else' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
elsif foobar
baz = 2
else
baz = 1
end
RUBY
end
it 'allows assignment using different operators in if else' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
else
bar << 2
end
RUBY
end
it 'allows assignment using different (method) operators in if..else' do
expect_no_offenses(<<~RUBY)
if foo
bar[index] = 1
else
bar << 2
end
RUBY
end
it 'allows aref assignment with different indices in if..else' do
expect_no_offenses(<<~RUBY)
if foo
bar[1] = 1
else
bar[2] = 2
end
RUBY
end
it 'allows assignment using different operators in if elsif else' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
elsif foobar
bar += 2
else
bar << 3
end
RUBY
end
it 'allows assignment of different variables in case when else' do
expect_no_offenses(<<~RUBY)
case foo
when "a"
bar = 1
else
baz = 2
end
RUBY
end
it 'registers an offense in an if else if the assignment is already at the line length limit' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
bar = #{'a' * 72}
else
bar = #{'b' * 72}
end
RUBY
expect_correction(<<~RUBY)
bar = if foo
#{'a' * 72}
else
#{'b' * 72}
end
RUBY
end
context 'correction would exceed max line length' do
it 'allows assignment to the same variable in if else if the correction ' \
'would create a line longer than the configured LineLength' do
expect_no_offenses(<<~RUBY)
if foo
#{'a' * 78}
bar = 1
else
bar = 2
end
RUBY
end
it 'allows assignment to the same variable in if else if the correction ' \
'would cause the condition to exceed the configured LineLength' do
expect_no_offenses(<<~RUBY)
if #{'a' * 78}
bar = 1
else
bar = 2
end
RUBY
end
it 'allows assignment to the same variable in case when else if the ' \
'correction would create a line longer than the configured LineLength' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
#{'a' * 78}
bar = 1
else
bar = 2
end
RUBY
end
end
shared_examples 'all variable types' do |variable, add_parens: false|
it 'registers an offense assigning any variable type in ternary' do
source = "foo? ? #{variable} = 1 : #{variable} = 2"
expect_offense(<<~RUBY, source: source)
%{source}
^{source} Use the return of the conditional for variable assignment and comparison.
RUBY
rhs = 'foo? ? 1 : 2'
rhs = "(#{rhs})" if add_parens
expect_correction(<<~RUBY)
#{variable} = #{rhs}
RUBY
end
it 'registers an offense assigning any variable type in if else' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
#{variable} = 1
else
#{variable} = 2
end
RUBY
expect_correction(<<~RUBY)
#{variable} = if foo
1
else
2
end
RUBY
end
it 'registers an offense assigning any variable type in case when' do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
when "a"
#{variable} = 1
else
#{variable} = 2
end
RUBY
expect_correction(<<~RUBY)
#{variable} = case foo
when "a"
1
else
2
end
RUBY
end
it 'allows assignment to the return of if else' do
expect_no_offenses(<<~RUBY)
#{variable} = if foo
1
else
2
end
RUBY
end
it 'allows assignment to the return of case when' do
expect_no_offenses(<<~RUBY)
#{variable} = case foo
when bar
1
else
2
end
RUBY
end
it 'allows assignment to the return of a ternary' do
expect_no_offenses(<<~RUBY)
#{variable} = foo? ? 1 : 2
RUBY
end
end
it_behaves_like('all variable types', 'bar')
it_behaves_like('all variable types', 'BAR')
it_behaves_like('all variable types', '@bar')
it_behaves_like('all variable types', '@@bar')
it_behaves_like('all variable types', '$BAR')
it_behaves_like('all variable types', 'foo.bar', add_parens: true)
it_behaves_like('all variable types', 'foo[1]')
shared_examples 'all assignment types' do |assignment, add_parens: false|
variable_types = { 'local variable' => 'bar',
'constant' => 'CONST',
'class variable' => '@@cvar',
'instance variable' => '@ivar',
'global variable' => '$gvar' }
variable_types.each do |type, name|
context "for a #{type} lval" do
it "registers an offense for assignment using #{assignment} in ternary" do
source = "foo? ? #{name} #{assignment} 1 : #{name} #{assignment} 2"
expect_offense(<<~RUBY, source: source)
%{source}
^{source} Use the return of the conditional for variable assignment and comparison.
RUBY
rhs = 'foo? ? 1 : 2'
rhs = "(#{rhs})" if add_parens
expect_correction(<<~RUBY)
#{name} #{assignment} #{rhs}
RUBY
end
end
end
%w[start_of_line keyword].each do |align_with|
context "with end alignment to #{align_with}" do
let(:end_alignment_align_with) { align_with }
let(:indent_end) { align_with == 'keyword' }
variable_types.each do |type, name|
context "for a #{type} lval" do
it "registers an offense for assignment using #{assignment} in if else" do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
#{name} #{assignment} 1
else
#{name} #{assignment} 2
end
RUBY
indent = ' ' * "#{name} #{assignment} ".length if indent_end
expect_correction(<<~RUBY)
#{name} #{assignment} if foo
1
else
2
#{indent}end
RUBY
end
it "registers an offense for assignment using #{assignment} in case when" do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
when "a"
#{name} #{assignment} 1
else
#{name} #{assignment} 2
end
RUBY
indent = ' ' * "#{name} #{assignment} ".length if indent_end
expect_correction(<<~RUBY)
#{name} #{assignment} case foo
when "a"
1
else
2
#{indent}end
RUBY
end
end
end
end
end
end
it_behaves_like('all assignment types', '=')
it_behaves_like('all assignment types', '+=')
it_behaves_like('all assignment types', '-=')
it_behaves_like('all assignment types', '*=')
it_behaves_like('all assignment types', '**=')
it_behaves_like('all assignment types', '/=')
it_behaves_like('all assignment types', '%=')
it_behaves_like('all assignment types', '^=')
it_behaves_like('all assignment types', '&=')
it_behaves_like('all assignment types', '|=')
it_behaves_like('all assignment types', '<<=')
it_behaves_like('all assignment types', '>>=')
it_behaves_like('all assignment types', '||=')
it_behaves_like('all assignment types', '&&=')
it_behaves_like('all assignment types', '<<', add_parens: true)
it 'registers an offense for assignment in if elsif else' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
bar = 1
elsif baz
bar = 2
else
bar = 3
end
RUBY
expect_correction(<<~RUBY)
bar = if foo
1
elsif baz
2
else
3
end
RUBY
end
it 'registers an offense for assignment in if elsif elsif else' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
bar = 1
elsif baz
bar = 2
elsif foobar
bar = 3
else
bar = 4
end
RUBY
expect_correction(<<~RUBY)
bar = if foo
1
elsif baz
2
elsif foobar
3
else
4
end
RUBY
end
it 'autocorrects assignment in if else when the assignment spans multiple lines' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
foo = {
a: 1,
b: 2,
c: 2,
d: 2,
e: 2,
f: 2,
g: 2,
h: 2
}
else
foo = { }
end
RUBY
expect_correction(<<~RUBY)
foo = if foo
{
a: 1,
b: 2,
c: 2,
d: 2,
e: 2,
f: 2,
g: 2,
h: 2
}
else
{ }
end
RUBY
end
shared_examples 'allows out of order multiple assignment in if elsif else' do
it 'allows out of order multiple assignment in if elsif else' do
expect_no_offenses(<<~RUBY)
if baz
bar = 1
foo = 1
elsif foobar
foo = 2
bar = 2
else
foo = 3
bar = 3
end
RUBY
end
end
context 'assignment as the last statement' do
it 'allows more than variable assignment in if else' do
expect_no_offenses(<<~RUBY)
if foo
method_call
bar = 1
else
method_call
bar = 2
end
RUBY
end
it 'allows more than variable assignment in if elsif else' do
expect_no_offenses(<<~RUBY)
if foo
method_call
bar = 1
elsif foobar
method_call
bar = 2
else
method_call
bar = 3
end
RUBY
end
it 'allows multiple assignment in if else' do
expect_no_offenses(<<~RUBY)
if baz
foo = 1
bar = 1
else
foo = 2
bar = 2
end
RUBY
end
it 'allows multiple assignment in if elsif else' do
expect_no_offenses(<<~RUBY)
if baz
foo = 1
bar = 1
elsif foobar
foo = 2
bar = 2
else
foo = 3
bar = 3
end
RUBY
end
it 'allows multiple assignment in if elsif elsif else' do
expect_no_offenses(<<~RUBY)
if baz
foo = 1
bar = 1
elsif foobar
foo = 2
bar = 2
elsif barfoo
foo = 3
bar = 3
else
foo = 4
bar = 4
end
RUBY
end
it 'allows multiple assignment in if elsif else when the last ' \
'assignment is the same and the earlier assignments do not appear in ' \
'all branches' do
expect_no_offenses(<<~RUBY)
if baz
foo = 1
bar = 1
elsif foobar
baz = 2
bar = 2
else
boo = 3
bar = 3
end
RUBY
end
it 'allows multiple assignment in case when else when the last ' \
'assignment is the same and the earlier assignments do not appear ' \
'in all branches' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
baz = 1
bar = 1
when foobaz
boo = 2
bar = 2
else
faz = 3
bar = 3
end
RUBY
end
it_behaves_like 'allows out of order multiple assignment in if elsif else'
it 'allows multiple assignment in unless else' do
expect_no_offenses(<<~RUBY)
unless baz
foo = 1
bar = 1
else
foo = 2
bar = 2
end
RUBY
end
it 'allows multiple assignments in case when with only one when' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
foo = 1
bar = 1
else
foo = 3
bar = 3
end
RUBY
end
it 'allows multiple assignments in case when with multiple whens' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
foo = 1
bar = 1
when foobaz
foo = 2
bar = 2
else
foo = 3
bar = 3
end
RUBY
end
it 'allows multiple assignments in case when if there are uniq ' \
'variables in the when branches' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
foo = 1
baz = 1
bar = 1
when foobaz
foo = 2
baz = 2
bar = 2
else
foo = 3
bar = 3
end
RUBY
end
it 'allows multiple assignment in case statements when the last ' \
'assignment is the same and the earlier assignments do not appear in ' \
'all branches' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
foo = 1
bar = 1
when foobaz
baz = 2
bar = 2
else
boo = 3
bar = 3
end
RUBY
end
it 'allows assignment in if elsif else with some branches only ' \
'containing variable assignment and others containing more than ' \
'variable assignment' do
expect_no_offenses(<<~RUBY)
if foo
bar = 1
elsif foobar
method_call
bar = 2
elsif baz
bar = 3
else
method_call
bar = 4
end
RUBY
end
it 'allows variable assignment in unless else with more than variable assignment' do
expect_no_offenses(<<~RUBY)
unless foo
method_call
bar = 1
else
method_call
bar = 2
end
RUBY
end
it 'allows variable assignment in case when else with more than variable assignment' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
method_call
bar = 1
else
method_call
bar = 2
end
RUBY
end
context 'multiple assignment in only one branch' do
it 'allows multiple assignment is in if' do
expect_no_offenses(<<~RUBY)
if foo
baz = 1
bar = 1
elsif foobar
method_call
bar = 2
else
other_method
bar = 3
end
RUBY
end
it 'allows multiple assignment is in elsif' do
expect_no_offenses(<<~RUBY)
if foo
method_call
bar = 1
elsif foobar
baz = 2
bar = 2
else
other_method
bar = 3
end
RUBY
end
it 'does not register an offense when multiple assignment is in else' do
expect_no_offenses(<<~RUBY)
if foo
method_call
bar = 1
elsif foobar
other_method
bar = 2
else
baz = 3
bar = 3
end
RUBY
end
end
end
it 'registers an offense for assignment in if then elsif then else' do
expect_offense(<<~RUBY)
if foo then bar = 1
^^^^^^^^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
elsif cond then bar = 2
else bar = 2
end
RUBY
expect_correction(<<~RUBY)
bar = if foo then 1
elsif cond then 2
else 2
end
RUBY
end
it 'registers an offense for assignment in unless else' do
expect_offense(<<~RUBY)
unless foo
^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
bar = 1
else
bar = 2
end
RUBY
expect_correction(<<~RUBY)
bar = unless foo
1
else
2
end
RUBY
end
it 'registers an offense for assignment in case when then else' do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
when bar then baz = 1
else baz = 2
end
RUBY
expect_correction(<<~RUBY)
baz = case foo
when bar then 1
else 2
end
RUBY
end
it 'registers an offense for assignment in case with when else' do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
when foobar
bar = 1
when baz
bar = 2
else
bar = 3
end
RUBY
expect_correction(<<~RUBY)
bar = case foo
when foobar
1
when baz
2
else
3
end
RUBY
end
it 'allows different assignment types in case with when else' do
expect_no_offenses(<<~RUBY)
case foo
when foobar
bar = 1
else
bar << 2
end
RUBY
end
it 'allows assignment in multiple branches when it is wrapped in a modifier' do
expect_no_offenses(<<~RUBY)
if foo
bar << 1
else
bar << 2 if foobar
end
RUBY
end
describe 'autocorrect' do
it 'corrects =~ in ternary operations' do
expect_offense(<<~RUBY)
foo? ? bar =~ /a/ : bar =~ /b/
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
RUBY
expect_correction(<<~RUBY)
bar =~ (foo? ? /a/ : /b/)
RUBY
end
it 'corrects assignment to unbracketed array in if else' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
bar = 1
else
bar = 2, 5, 6
end
RUBY
expect_correction(<<~RUBY)
bar = if foo
1
else
[2, 5, 6]
end
RUBY
end
context 'assignment from a method' do
it 'corrects if else' do
expect_offense(<<~RUBY)
if foo?(scope.node)
^^^^^^^^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
bar << foobar(var, all)
else
bar << baz(var, all)
end
RUBY
expect_correction(<<~RUBY)
bar << if foo?(scope.node)
foobar(var, all)
else
baz(var, all)
end
RUBY
end
it 'corrects unless else' do
expect_offense(<<~RUBY)
unless foo?(scope.node)
^^^^^^^^^^^^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
bar << foobar(var, all)
else
bar << baz(var, all)
end
RUBY
expect_correction(<<~RUBY)
bar << unless foo?(scope.node)
foobar(var, all)
else
baz(var, all)
end
RUBY
end
it 'corrects case when' do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
when foobar
bar << foobar(var, all)
else
bar << baz(var, all)
end
RUBY
expect_correction(<<~RUBY)
bar << case foo
when foobar
foobar(var, all)
else
baz(var, all)
end
RUBY
end
end
it 'preserves comments during correction in if else' do
expect_offense(<<~RUBY)
if foo
^^^^^^ Use the return of the conditional for variable assignment and comparison.
# comment in if
bar = 1
else
# comment in else
bar = 2
end
RUBY
expect_correction(<<~RUBY)
bar = if foo
# comment in if
1
else
# comment in else
2
end
RUBY
end
it 'preserves comments during correction in case when else' do
expect_offense(<<~RUBY)
case foo
^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
when foobar
# comment in when
bar = 1
else
# comment in else
bar = 2
end
RUBY
expect_correction(<<~RUBY)
bar = case foo
when foobar
# comment in when
1
else
# comment in else
2
end
RUBY
end
context 'aref assignment' do
it 'corrects if..else' do
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/not_spec.rb | spec/rubocop/cop/style/not_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Not, :config do
it 'registers an offense for not' do
expect_offense(<<~RUBY)
not test
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
!test
RUBY
end
it 'does not register an offense for !' do
expect_no_offenses('!test')
end
it 'autocorrects "not" with !' do
expect_offense(<<~RUBY)
x = 10 if not y
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
x = 10 if !y
RUBY
end
it 'autocorrects "not" followed by parens with !' do
expect_offense(<<~RUBY)
not(test)
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
!(test)
RUBY
end
it 'uses the reverse operator when `not` is applied to a comparison' do
expect_offense(<<~RUBY)
not x < y
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
x >= y
RUBY
end
it 'parenthesizes when `not` would change the meaning of a binary exp' do
expect_offense(<<~RUBY)
not a >> b
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
!(a >> b)
RUBY
end
it 'parenthesizes when `not` is applied to a ternary op' do
expect_offense(<<~RUBY)
not a ? b : c
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
!(a ? b : c)
RUBY
end
it 'parenthesizes when `not` is applied to and' do
expect_offense(<<~RUBY)
not a && b
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
!(a && b)
RUBY
end
it 'parenthesizes when `not` is applied to or' do
expect_offense(<<~RUBY)
not a || b
^^^ Use `!` instead of `not`.
RUBY
expect_correction(<<~RUBY)
!(a || b)
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/and_or_spec.rb | spec/rubocop/cop/style/and_or_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::AndOr, :config do
context 'when style is conditionals' do
cop_config = { 'EnforcedStyle' => 'conditionals' }
let(:cop_config) { cop_config }
{ 'and' => '&&', 'or' => '||' }.each do |operator, prefer|
it "accepts \"#{operator}\" outside of conditional" do
expect_no_offenses(<<~RUBY)
x = a + b #{operator} return x
RUBY
end
it "registers an offense for \"#{operator}\" in if condition" do
expect_offense(<<~RUBY, operator: operator)
if a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
do_something
end
RUBY
expect_correction(<<~RUBY)
if a #{prefer} b
do_something
end
RUBY
end
it "accepts \"#{operator}\" in if body" do
expect_no_offenses(<<~RUBY)
if some_condition
do_something #{operator} return
end
RUBY
end
it "registers an offense for \"#{operator}\" in while condition" do
expect_offense(<<~RUBY, operator: operator)
while a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
do_something
end
RUBY
expect_correction(<<~RUBY)
while a #{prefer} b
do_something
end
RUBY
end
it "accepts \"#{operator}\" in while body" do
expect_no_offenses(<<~RUBY)
while some_condition
do_something #{operator} return
end
RUBY
end
it "registers an offense for \"#{operator}\" in until condition" do
expect_offense(<<~RUBY, operator: operator)
until a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
do_something
end
RUBY
expect_correction(<<~RUBY)
until a #{prefer} b
do_something
end
RUBY
end
it "accepts \"#{operator}\" in until body" do
expect_no_offenses(<<~RUBY)
until some_condition
do_something #{operator} return
end
RUBY
end
it "registers an offense for \"#{operator}\" in post-while condition" do
expect_offense(<<~RUBY, operator: operator)
begin
do_something
end while a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
begin
do_something
end while a #{prefer} b
RUBY
end
it "accepts \"#{operator}\" in post-while body" do
expect_no_offenses(<<~RUBY)
begin
do_something #{operator} return
end while some_condition
RUBY
end
it "registers an offense for \"#{operator}\" in post-until condition" do
expect_offense(<<~RUBY, operator: operator)
begin
do_something
end until a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
begin
do_something
end until a #{prefer} b
RUBY
end
it "accepts \"#{operator}\" in post-until body" do
expect_no_offenses(<<~RUBY)
begin
do_something #{operator} return
end until some_condition
RUBY
end
end
%w[&& ||].each do |operator|
it "accepts #{operator} inside of conditional" do
expect_no_offenses(<<~RUBY)
test if a #{operator} b
RUBY
end
it "accepts #{operator} outside of conditional" do
expect_no_offenses(<<~RUBY)
x = a #{operator} b
RUBY
end
end
end
context 'when style is always' do
cop_config = { 'EnforcedStyle' => 'always' }
let(:cop_config) { cop_config }
{ 'and' => '&&', 'or' => '||' }.each do |operator, prefer|
it "registers an offense for \"#{operator}\"" do
expect_offense(<<~RUBY, operator: operator)
test if a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
test if a #{prefer} b
RUBY
end
it "autocorrects \"#{operator}\" inside def" do
expect_offense(<<~RUBY, operator: operator)
def z(a, b)
return true if a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
end
RUBY
expect_correction(<<~RUBY)
def z(a, b)
return true if a #{prefer} b
end
RUBY
end
end
it 'autocorrects "or" with an assignment on the left' do
expect_offense(<<~RUBY)
x = y or teststring.include? 'b'
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
(x = y) || teststring.include?('b')
RUBY
end
it 'autocorrects "or" with an assignment on the right' do
expect_offense(<<~RUBY)
teststring.include? 'b' or x = y
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
teststring.include?('b') || (x = y)
RUBY
end
it 'autocorrects "and" with an Enumerable accessor on either side' do
expect_offense(<<~RUBY)
foo[:bar] and foo[:baz]
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
foo[:bar] && foo[:baz]
RUBY
end
{ 'and' => '&&', 'or' => '||' }.each do |operator, prefer|
it "warns on short-circuit (#{operator})" do
expect_offense(<<~RUBY, operator: operator)
x = a + b %{operator} return x
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
(x = a + b) #{prefer} (return x)
RUBY
end
it "also warns on non short-circuit (#{operator})" do
expect_offense(<<~RUBY, operator: operator)
x = a + b if a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
x = a + b if a #{prefer} b
RUBY
end
it "also warns on non short-circuit (#{operator}) (unless)" do
expect_offense(<<~RUBY, operator: operator)
x = a + b unless a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
x = a + b unless a #{prefer} b
RUBY
end
it "also warns on while (#{operator})" do
expect_offense(<<~RUBY, operator: operator)
x = a + b while a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
x = a + b while a #{prefer} b
RUBY
end
it "also warns on until (#{operator})" do
expect_offense(<<~RUBY, operator: operator)
x = a + b until a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
x = a + b until a #{prefer} b
RUBY
end
it "autocorrects \"#{operator}\" with #{prefer} in method calls" do
expect_offense(<<~RUBY, operator: operator)
method a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
method(a) #{prefer} b
RUBY
end
it "autocorrects \"#{operator}\" with #{prefer} in method calls (2)" do
expect_offense(<<~RUBY, operator: operator)
method a,b %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
method(a,b) #{prefer} b
RUBY
end
it "autocorrects \"#{operator}\" with #{prefer} in method calls (3)" do
expect_offense(<<~RUBY, operator: operator)
obj.method a %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
obj.method(a) #{prefer} b
RUBY
end
it "autocorrects \"#{operator}\" with #{prefer} in method calls (4)" do
expect_offense(<<~RUBY, operator: operator)
obj.method a,b %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
obj.method(a,b) #{prefer} b
RUBY
end
it "autocorrects \"#{operator}\" with #{prefer} and doesn't add extra parentheses" do
expect_offense(<<~RUBY, operator: operator)
method(a, b) %{operator} b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
method(a, b) #{prefer} b
RUBY
end
it "autocorrects \"#{operator}\" with #{prefer} and adds parentheses to expr" do
expect_offense(<<~RUBY, operator: operator)
b %{operator} method a,b
^{operator} Use `#{prefer}` instead of `#{operator}`.
RUBY
expect_correction(<<~RUBY)
b #{prefer} method(a,b)
RUBY
end
end
context 'with !obj.method arg on right' do
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
x and !obj.method arg
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
x && !obj.method(arg)
RUBY
end
end
context 'with !obj.method arg on left' do
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
!obj.method arg and x
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
!obj.method(arg) && x
RUBY
end
end
context 'with obj.method = arg on left' do
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
obj.method = arg and x
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
(obj.method = arg) && x
RUBY
end
end
context 'with obj.method= arg on left' do
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
obj.method= arg and x
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
(obj.method= arg) && x
RUBY
end
end
context 'with predicate method with arg without space on right' do
it 'autocorrects "or" with || and adds parens' do
expect_offense(<<~RUBY)
false or 3.is_a?Integer
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
false || 3.is_a?(Integer)
RUBY
end
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
false and 3.is_a?Integer
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
false && 3.is_a?(Integer)
RUBY
end
end
context 'with two predicate methods with args without spaces on right' do
it 'autocorrects "or" with || and adds parens' do
expect_offense(<<~RUBY)
'1'.is_a?Integer or 1.is_a?Integer
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
'1'.is_a?(Integer) || 1.is_a?(Integer)
RUBY
end
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
'1'.is_a?Integer and 1.is_a?Integer
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
'1'.is_a?(Integer) && 1.is_a?(Integer)
RUBY
end
end
context 'with one predicate method without space on right and another method' do
it 'autocorrects "or" with || and adds parens' do
expect_offense(<<~RUBY)
'1'.is_a?Integer or 1.is_a? Integer
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
'1'.is_a?(Integer) || 1.is_a?(Integer)
RUBY
end
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
'1'.is_a?Integer and 1.is_a? Integer
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
'1'.is_a?(Integer) && 1.is_a?(Integer)
RUBY
end
end
context 'with `not` expression on right' do
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
x and not arg
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
x && (not arg)
RUBY
end
end
context 'with `not` expression on left' do
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
not arg and x
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
(not arg) && x
RUBY
end
end
context 'with !variable on left' do
it "doesn't crash and burn" do
# regression test; see GH issue 2482
expect_offense(<<~RUBY)
!var or var.empty?
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
!var || var.empty?
RUBY
end
end
context 'within a nested begin node' do
# regression test; see GH issue 2531
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
def x
end
def y
a = b and a.c
^^^ Use `&&` instead of `and`.
end
RUBY
expect_correction(<<~RUBY)
def x
end
def y
(a = b) && a.c
end
RUBY
end
end
context 'when left hand side is a comparison method' do
# Regression: https://github.com/rubocop/rubocop/issues/4451
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
foo == bar and baz
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
(foo == bar) && baz
RUBY
end
end
context 'when `or` precedes `and`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo or bar and baz
^^ Use `||` instead of `or`.
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
(foo || bar) && baz
RUBY
end
end
context 'when `or` precedes `&&`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo or bar && baz
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
foo || bar && baz
RUBY
end
end
context 'when `and` precedes `or`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo and bar or baz
^^^ Use `&&` instead of `and`.
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
foo && bar || baz
RUBY
end
end
context 'when `and` precedes `||`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo and bar || baz
^^^ Use `&&` instead of `and`.
RUBY
expect_correction(<<~RUBY)
foo && (bar || baz)
RUBY
end
end
context 'within a nested begin node with one child only' do
# regression test; see GH issue 2531
it 'autocorrects "and" with && and adds parens' do
expect_offense(<<~RUBY)
(def y
a = b and a.c
^^^ Use `&&` instead of `and`.
end)
RUBY
expect_correction(<<~RUBY)
(def y
(a = b) && a.c
end)
RUBY
end
end
context 'with a file which contains __FILE__' do
# regression test; see GH issue 2609
it 'autocorrects "or" with ||' do
expect_offense(<<~RUBY)
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
system('bundle check') or system!('bundle install')
^^ Use `||` instead of `or`.
RUBY
expect_correction(<<~RUBY)
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
system('bundle check') || system!('bundle install')
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_interpolation_unfreeze_spec.rb | spec/rubocop/cop/style/redundant_interpolation_unfreeze_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantInterpolationUnfreeze, :config do
context 'target_ruby_version >= 3.0', :ruby30 do
it 'registers an offense for `@+`' do
expect_offense(<<~'RUBY')
+"#{foo} bar"
^ Don't unfreeze interpolated strings as they are already unfrozen.
RUBY
expect_correction(<<~'RUBY')
"#{foo} bar"
RUBY
end
it 'registers an offense for `@+` as a normal method call' do
expect_offense(<<~'RUBY')
"#{foo} bar".+@
^^ Don't unfreeze interpolated strings as they are already unfrozen.
RUBY
expect_correction(<<~'RUBY')
"#{foo} bar"
RUBY
end
it 'registers an offense for `dup`' do
expect_offense(<<~'RUBY')
"#{foo} bar".dup
^^^ Don't unfreeze interpolated strings as they are already unfrozen.
RUBY
expect_correction(<<~'RUBY')
"#{foo} bar"
RUBY
end
it 'registers an offense for interpolated heredoc with `@+`' do
expect_offense(<<~'RUBY')
foo(+<<~MSG)
^ Don't unfreeze interpolated strings as they are already unfrozen.
foo #{bar}
baz
MSG
RUBY
expect_correction(<<~'RUBY')
foo(<<~MSG)
foo #{bar}
baz
MSG
RUBY
end
it 'registers an offense for interpolated strings with global variables' do
expect_offense(<<~'RUBY')
+"#$var"
^ Don't unfreeze interpolated strings as they are already unfrozen.
RUBY
expect_correction(<<~'RUBY')
"#$var"
RUBY
end
it 'registers an offense for strings with interpolated instance variables' do
expect_offense(<<~'RUBY')
+"#@var"
^ Don't unfreeze interpolated strings as they are already unfrozen.
RUBY
expect_correction(<<~'RUBY')
"#@var"
RUBY
end
it 'registers an offense for strings with interpolated class variables' do
expect_offense(<<~'RUBY')
+"#@@var"
^ Don't unfreeze interpolated strings as they are already unfrozen.
RUBY
expect_correction(<<~'RUBY')
"#@@var"
RUBY
end
it 'registers an offense for interpolated heredoc with `dup`' do
expect_offense(<<~'RUBY')
foo(<<~MSG.dup)
^^^ Don't unfreeze interpolated strings as they are already unfrozen.
foo #{bar}
baz
MSG
RUBY
expect_correction(<<~'RUBY')
foo(<<~MSG)
foo #{bar}
baz
MSG
RUBY
end
it 'registers no offense for uninterpolated heredoc' do
expect_no_offenses(<<~'RUBY')
foo(+<<~'MSG')
foo #{bar}
baz
MSG
RUBY
end
it 'registers no offense for plain string literals' do
expect_no_offenses(<<~RUBY)
"foo".dup
RUBY
end
it 'registers no offense for other types' do
expect_no_offenses(<<~RUBY)
local.dup
RUBY
end
it 'registers no offense when the method has arguments' do
expect_no_offenses(<<~'RUBY')
"#{foo} bar".dup(baz)
RUBY
end
it 'registers no offense for multiline string literals' do
expect_no_offenses(<<~RUBY)
+'foo' \
'bar'
RUBY
end
it 'registers no offense when there is no receiver' do
expect_no_offenses(<<~RUBY)
dup
RUBY
end
end
context 'target_ruby_version < 3.0', :ruby27, unsupported_on: :prism do
it 'accepts unfreezing an interpolated string' do
expect_no_offenses('+"#{foo} bar"')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_sort_by_spec.rb | spec/rubocop/cop/style/redundant_sort_by_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantSortBy, :config do
it 'autocorrects array.sort_by { |x| x }' do
expect_offense(<<~RUBY)
array.sort_by { |x| x }
^^^^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { |x| x }`.
RUBY
expect_correction(<<~RUBY)
array.sort
RUBY
end
it 'autocorrects array&.sort_by { |x| x }' do
expect_offense(<<~RUBY)
array&.sort_by { |x| x }
^^^^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { |x| x }`.
RUBY
expect_correction(<<~RUBY)
array&.sort
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'autocorrects array.sort_by { |x| x }' do
expect_offense(<<~RUBY)
array.sort_by { _1 }
^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { _1 }`.
RUBY
expect_correction(<<~RUBY)
array.sort
RUBY
end
it 'autocorrects array&.sort_by { |x| x }' do
expect_offense(<<~RUBY)
array&.sort_by { _1 }
^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { _1 }`.
RUBY
expect_correction(<<~RUBY)
array&.sort
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'autocorrects array.sort_by { |x| x }' do
expect_offense(<<~RUBY)
array.sort_by { it }
^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { it }`.
RUBY
expect_correction(<<~RUBY)
array.sort
RUBY
end
it 'autocorrects array&.sort_by { |x| x }' do
expect_offense(<<~RUBY)
array&.sort_by { it }
^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { it }`.
RUBY
expect_correction(<<~RUBY)
array&.sort
RUBY
end
end
it 'autocorrects array.sort_by { |y| y }' do
expect_offense(<<~RUBY)
array.sort_by { |y| y }
^^^^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { |y| y }`.
RUBY
expect_correction(<<~RUBY)
array.sort
RUBY
end
it 'autocorrects array.sort_by do |x| x end' do
expect_offense(<<~RUBY)
array.sort_by do |x|
^^^^^^^^^^^^^^ Use `sort` instead of `sort_by { |x| x }`.
x
end
RUBY
expect_correction(<<~RUBY)
array.sort
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/map_to_hash_spec.rb | spec/rubocop/cop/style/map_to_hash_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MapToHash, :config do
context '>= Ruby 2.6', :ruby26 do
%i[map collect].each do |method|
context "for `#{method}.to_h` with block arity 1" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |x| [x, x * 2] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h { |x| [x, x * 2] }
RUBY
end
end
context "for `#{method}.to_h` with block arity 1 and destructuring argument" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |(k, v)| [k, v * 2] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h { |k, v| [k, v * 2] }
RUBY
end
end
context "for `#{method}.to_h` with block arity 2" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |x, y| [x.to_s, y.to_i] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h { |x, y| [x.to_s, y.to_i] }
RUBY
end
end
context "for `#{method}.to_h` without receiver" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
#{method} { |x| [x, x * 2] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
to_h { |x| [x, x * 2] }
RUBY
end
end
context "for `#{method}&.to_h` with block arity 1" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo&.#{method} { |x| [x, x * 2] }&.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}&.to_h`.
RUBY
expect_correction(<<~RUBY)
foo&.to_h { |x| [x, x * 2] }
RUBY
end
end
context "for `&.#{method}.to_h` with block arity 1" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo&.#{method} { |x| [x, x * 2] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h { |x| [x, x * 2] }
RUBY
end
end
context "for `#{method}&.to_h` with block arity 2" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo&.#{method} { |x, y| [x.to_s, y.to_i] }&.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}&.to_h`.
RUBY
expect_correction(<<~RUBY)
foo&.to_h { |x, y| [x.to_s, y.to_i] }
RUBY
end
end
context 'when using numbered parameters', :ruby27 do
context "for `#{method}.to_h` with block arity 1" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { [_1, _1 * 2] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h { [_1, _1 * 2] }
RUBY
end
end
context "for `#{method}.to_h` with block arity 2" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { [_1.to_s, _2.to_i] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h { [_1.to_s, _2.to_i] }
RUBY
end
end
end
context "for `#{method}.to_h` with symbol proc" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method}(&:do_something).to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h(&:do_something)
RUBY
end
end
context "for `#{method}&.to_h` with symbol proc" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo&.#{method}(&:do_something)&.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}&.to_h`.
RUBY
expect_correction(<<~RUBY)
foo&.to_h(&:do_something)
RUBY
end
end
context 'when the receiver is an array' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].#{method} { |x| [x, x * 2] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].to_h { |x| [x, x * 2] }
RUBY
end
end
context 'when the receiver is a hash' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
{ foo: :bar }.#{method} { |x, y| [x.to_s, y.to_s] }.to_h
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
{ foo: :bar }.to_h { |x, y| [x.to_s, y.to_s] }
RUBY
end
end
context 'when chained further' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |x| x * 2 }.to_h.bar
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
RUBY
expect_correction(<<~RUBY)
foo.to_h { |x| x * 2 }.bar
RUBY
end
end
context "`#{method}` without `to_h`" do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }
RUBY
end
end
context "`#{method}` followed by `to_h` with a block passed to `to_h`" do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }.to_h { |x| [x.to_s, x] }
RUBY
end
end
context "`#{method}` followed by `to_h` with a numbered block passed to `to_h`", :ruby27 do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }.to_h { |x| [x.to_s, x] }
RUBY
end
end
context "`#{method}` followed by `to_h` with an `it` block passed to `to_h`", :ruby34 do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }.to_h { [it.to_s, it] }
RUBY
end
end
context "`map` and `#{method}.to_h` with newlines" do
it 'registers an offense and corrects with newline removal' do
expect_offense(<<~RUBY, method: method)
{foo: bar}
.#{method} { |k, v| [k.to_s, v.do_something] }
^{method} Pass a block to `to_h` instead of calling `#{method}.to_h`.
.to_h
.freeze
RUBY
expect_correction(<<~RUBY)
{foo: bar}
.to_h { |k, v| [k.to_s, v.do_something] }
.freeze
RUBY
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/empty_lambda_parameter_spec.rb | spec/rubocop/cop/style/empty_lambda_parameter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyLambdaParameter, :config do
it 'registers an offense for an empty block parameter with a lambda' do
expect_offense(<<~RUBY)
-> () { do_something }
^^ Omit parentheses for the empty lambda parameters.
RUBY
expect_correction(<<~RUBY)
-> { do_something }
RUBY
end
it 'accepts a keyword lambda' do
expect_no_offenses(<<~RUBY)
lambda { || do_something }
RUBY
end
it 'does not crash on a super' do
expect_no_offenses(<<~RUBY)
def foo
super { || do_something }
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/parentheses_around_condition_spec.rb | spec/rubocop/cop/style/parentheses_around_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ParenthesesAroundCondition, :config do
let(:cop_config) { { 'AllowSafeAssignment' => true } }
it 'registers an offense for parentheses around condition' do
expect_offense(<<~RUBY)
if (x > 10)
^^^^^^^^ Don't use parentheses around the condition of an `if`.
elsif (x < 3)
^^^^^^^ Don't use parentheses around the condition of an `elsif`.
end
unless (x > 10)
^^^^^^^^ Don't use parentheses around the condition of an `unless`.
end
while (x > 10)
^^^^^^^^ Don't use parentheses around the condition of a `while`.
end
until (x > 10)
^^^^^^^^ Don't use parentheses around the condition of an `until`.
end
x += 1 if (x < 10)
^^^^^^^^ Don't use parentheses around the condition of an `if`.
x += 1 unless (x < 10)
^^^^^^^^ Don't use parentheses around the condition of an `unless`.
x += 1 until (x < 10)
^^^^^^^^ Don't use parentheses around the condition of an `until`.
x += 1 while (x < 10)
^^^^^^^^ Don't use parentheses around the condition of a `while`.
RUBY
expect_correction(<<~RUBY)
if x > 10
elsif x < 3
end
unless x > 10
end
while x > 10
end
until x > 10
end
x += 1 if x < 10
x += 1 unless x < 10
x += 1 until x < 10
x += 1 while x < 10
RUBY
end
it 'accepts parentheses if there is no space between the keyword and (.' do
expect_no_offenses(<<~RUBY)
if(x > 5) then something end
do_something until(x > 5)
RUBY
end
it 'accepts parentheses around condition in a ternary' do
expect_no_offenses('(a == 0) ? b : a')
end
it 'is not confused by leading parentheses in subexpression' do
expect_no_offenses('(a > b) && other ? one : two')
end
it 'is not confused by parentheses in subexpression' do
expect_no_offenses(<<~RUBY)
if (a + b).c()
end
RUBY
end
%w[rescue if unless while until].each do |op|
it "allows parens if the condition node is a modifier #{op} op" do
expect_no_offenses(<<~RUBY)
if (something #{op} top)
end
RUBY
end
end
it 'does not blow up when the condition is a ternary op' do
expect_offense(<<~RUBY)
x if (a ? b : c)
^^^^^^^^^^^ Don't use parentheses around the condition of an `if`.
RUBY
expect_correction(<<~RUBY)
x if a ? b : c
RUBY
end
it 'does not blow up for empty if condition' do
expect_no_offenses(<<~RUBY)
if ()
end
RUBY
end
it 'does not blow up for empty unless condition' do
expect_no_offenses(<<~RUBY)
unless ()
end
RUBY
end
it 'does not register an offense when using a method call with `do`...`end` block as a condition in `while` loop' do
expect_no_offenses(<<~RUBY)
while (foo do
end)
end
RUBY
end
it 'does not register an offense when using a method call with `do`...`end` block as a condition in `until` loop' do
expect_no_offenses(<<~RUBY)
until (foo do
end)
end
RUBY
end
it 'does not register an offense when using a method call with `do`...`end` numbered block as a condition in `while` loop' do
expect_no_offenses(<<~RUBY)
while (foo do
_1
end)
end
RUBY
end
it 'does not register an offense when using a method call with `do`...`end` numbered block as a condition in `until` loop' do
expect_no_offenses(<<~RUBY)
until (foo do
_1
end)
end
RUBY
end
it 'registers an offense when using method call with `{`...`}` block as a `while` condition' do
expect_offense(<<~RUBY)
while (foo {
^^^^^^ Don't use parentheses around the condition of a `while`.
})
end
RUBY
expect_correction(<<~RUBY)
while foo {
}
end
RUBY
end
it 'registers an offense when using method call with `{`...`}` block as a `until` condition' do
expect_offense(<<~RUBY)
until (foo {
^^^^^^ Don't use parentheses around the condition of an `until`.
})
end
RUBY
expect_correction(<<~RUBY)
until foo {
}
end
RUBY
end
it 'registers an offense when using method call with `do`...`end` block as a `if` condition' do
expect_offense(<<~RUBY)
if (foo do
^^^^^^^ Don't use parentheses around the condition of an `if`.
end)
end
RUBY
expect_correction(<<~RUBY)
if foo do
end
end
RUBY
end
it 'registers an offense when using method call with `{`...`}` block as a `if` condition' do
expect_offense(<<~RUBY)
if (foo {
^^^^^^ Don't use parentheses around the condition of an `if`.
})
end
RUBY
expect_correction(<<~RUBY)
if foo {
}
end
RUBY
end
it 'does not register an offense when parentheses in multiple expressions separated by semicolon' do
expect_no_offenses(<<~RUBY)
if (foo; bar)
do_something
end
RUBY
end
context 'safe assignment is allowed' do
it 'accepts variable assignment in condition surrounded with parentheses' do
expect_no_offenses(<<~RUBY)
if (test = 10)
end
RUBY
end
it 'accepts element assignment in condition surrounded with parentheses' do
expect_no_offenses(<<~RUBY)
if (test[0] = 10)
end
RUBY
end
it 'accepts setter in condition surrounded with parentheses' do
expect_no_offenses(<<~RUBY)
if (self.test = 10)
end
RUBY
end
end
context 'safe assignment is not allowed' do
let(:cop_config) { { 'AllowSafeAssignment' => false } }
it 'does not accept variable assignment in condition surrounded with parentheses' do
expect_offense(<<~RUBY)
if (test = 10)
^^^^^^^^^^^ Don't use parentheses around the condition of an `if`.
end
RUBY
expect_correction(<<~RUBY)
if test = 10
end
RUBY
end
it 'does not accept element assignment in condition surrounded with parentheses' do
expect_offense(<<~RUBY)
if (test[0] = 10)
^^^^^^^^^^^^^^ Don't use parentheses around the condition of an `if`.
end
RUBY
expect_correction(<<~RUBY)
if test[0] = 10
end
RUBY
end
end
context 'parentheses in multiline conditions are allowed' do
let(:cop_config) { { 'AllowInMultilineConditions' => true } }
it 'accepts parentheses around multiline condition' do
expect_no_offenses(<<~RUBY)
if (
x > 3 &&
x < 10
)
return true
end
RUBY
end
it 'registers an offense for parentheses in single line condition' do
expect_offense(<<~RUBY)
if (x > 3 && x < 10)
^^^^^^^^^^^^^^^^^ Don't use parentheses around the condition of an `if`.
return true
end
RUBY
expect_correction(<<~RUBY)
if x > 3 && x < 10
return true
end
RUBY
end
end
context 'parentheses in multiline conditions are not allowed' do
let(:cop_config) { { 'AllowInMultilineConditions' => false } }
it 'registers an offense for parentheses around multiline condition' do
expect_offense(<<~RUBY)
if (
^ Don't use parentheses around the condition of an `if`.
x > 3 &&
x < 10
)
return true
end
RUBY
expect_correction(<<~RUBY)
if x > 3 &&
x < 10
return true
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/combinable_loops_spec.rb | spec/rubocop/cop/style/combinable_loops_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CombinableLoops, :config do
context 'when looping method' do
it 'registers an offense when looping over the same data as previous loop' do
expect_offense(<<~RUBY)
items.each { |item| do_something(item) }
items.each { |item| do_something_else(item, arg) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.each_with_index { |item| do_something(item) }
items.each_with_index { |item| do_something_else(item, arg) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.reverse_each { |item| do_something(item) }
items.reverse_each { |item| do_something_else(item, arg) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
items.each { |item| do_something(item)
do_something_else(item, arg) }
items.each_with_index { |item| do_something(item)
do_something_else(item, arg) }
items.reverse_each { |item| do_something(item)
do_something_else(item, arg) }
RUBY
end
it 'registers an offense when looping over the same data for the second consecutive time' do
expect_offense(<<~RUBY)
items.each do |item| foo(item) end
items.each { |item| bar(item) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
do_something
RUBY
expect_correction(<<~RUBY)
items.each do |item| foo(item)
bar(item) end
do_something
RUBY
end
it 'registers an offense when looping over the same data for the third consecutive time' do
expect_offense(<<~RUBY)
items.each { |item| foo(item) }
items.each { |item| bar(item) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.each { |item| baz(item) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
items.each { |item| foo(item)
bar(item)
baz(item) }
RUBY
end
it 'registers an offense and does not correct when looping over the same data with different block variable names' do
expect_offense(<<~RUBY)
items.each { |item| foo(item) }
items.each { |x| bar(x) }
^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_no_corrections
end
it 'registers an offense when looping over the same data for the third consecutive time with numbered blocks' do
expect_offense(<<~RUBY)
items.each { foo(_1) }
items.each { bar(_1) }
^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.each { baz(_1) }
^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
items.each { foo(_1)
bar(_1)
baz(_1) }
RUBY
end
it 'registers an offense when looping over the same data for the third consecutive time with `it` blocks', :ruby34 do
expect_offense(<<~RUBY)
items.each { foo(it) }
items.each { bar(it) }
^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.each { baz(it) }
^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
items.each { foo(it)
bar(it)
baz(it) }
RUBY
end
it 'registers an offense when looping over the same data as previous loop in `do`...`end` and `{`...`}` blocks' do
expect_offense(<<~RUBY)
items.each do |item| do_something(item) end
items.each { |item| do_something_else item, arg}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
items.each do |item| do_something(item)
do_something_else item, arg end
RUBY
end
it 'registers an offense when looping over the same data as previous loop in `{`...`}` and `do`...`end` blocks' do
expect_offense(<<~RUBY)
items.each { |item| do_something(item) }
items.each do |item| do_something_else(item, arg) end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
items.each { |item| do_something(item)
do_something_else(item, arg) }
RUBY
end
context 'Ruby 2.7' do
it 'registers an offense when looping over the same data as previous loop in numblocks' do
expect_offense(<<~RUBY)
items.each { do_something(_1) }
items.each { do_something_else(_1, arg) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.each_with_index { do_something(_1) }
items.each_with_index { do_something_else(_1, arg) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.reverse_each { do_something(_1) }
items.reverse_each { do_something_else(_1, arg) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
items.each { do_something(_1)
do_something_else(_1, arg) }
items.each_with_index { do_something(_1)
do_something_else(_1, arg) }
items.reverse_each { do_something(_1)
do_something_else(_1, arg) }
RUBY
end
end
it 'does not register an offense when the same loops are interleaved with some code' do
expect_no_offenses(<<~RUBY)
items.each { |item| do_something(item) }
some_code
items.each { |item| do_something_else(item, arg) }
RUBY
end
it 'does not register an offense when the same loop method is used over different collections' do
expect_no_offenses(<<~RUBY)
items.each { |item| do_something(item) }
bars.each { |bar| do_something(bar) }
RUBY
end
it 'does not register an offense when different loop methods are used over the same collection' do
expect_no_offenses(<<~RUBY)
items.reverse_each { |item| do_something(item) }
items.each { |item| do_something(item) }
RUBY
end
it 'does not register an offense when each branch contains the same single loop over the same collection' do
expect_no_offenses(<<~RUBY)
if condition
items.each { |item| do_something(item) }
else
items.each { |item| do_something_else(item, arg) }
end
RUBY
end
it 'does not register an offense for when the same method with different arguments' do
expect_no_offenses(<<~RUBY)
each_slice(2) { |slice| do_something(slice) }
each_slice(3) { |slice| do_something(slice) }
RUBY
end
it 'does not register an offense for when the same method with different arguments and safe navigation' do
expect_no_offenses(<<~RUBY)
foo(:bar)&.each { |item| do_something(item) }
foo(:baz)&.each { |item| do_something(item) }
RUBY
end
end
context 'when for loop' do
it 'registers an offense when looping over the same data as previous loop' do
expect_offense(<<~RUBY)
for item in items do do_something(item) end
for item in items do do_something_else(item, arg) end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY
expect_correction(<<~RUBY)
for item in items do do_something(item)
do_something_else(item, arg) end
RUBY
end
it 'does not register an offense when the same loops are interleaved with some code' do
expect_no_offenses(<<~RUBY)
for item in items do do_something(item) end
some_code
for item in items do do_something_else(item, arg) end
RUBY
end
it 'does not register an offense when the same loop method is used over different collections' do
expect_no_offenses(<<~RUBY)
for item in items do do_something(item) end
for foo in foos do do_something(foo) end
RUBY
end
it 'does not register an offense when each branch contains the same single loop over the same collection' do
expect_no_offenses(<<~RUBY)
if condition
for item in items do do_something(item) end
else
for item in items do do_something_else(item, arg) end
end
RUBY
end
it 'does not register an offense when one of the loops is empty' do
expect_no_offenses(<<~RUBY)
items.each {}
items.each {}
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/identical_conditional_branches_spec.rb | spec/rubocop/cop/style/identical_conditional_branches_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::IdenticalConditionalBranches, :config do
context 'on if..else with identical bodies' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
if something
do_x
^^^^ Move `do_x` out of the conditional.
else
do_x
^^^^ Move `do_x` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
if something
else
end
do_x
RUBY
end
end
context 'on if..else with identical trailing lines' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
if something
method_call_here(1, 2, 3)
do_x
^^^^ Move `do_x` out of the conditional.
else
1 + 2 + 3
do_x
^^^^ Move `do_x` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
if something
method_call_here(1, 2, 3)
else
1 + 2 + 3
end
do_x
RUBY
end
end
context 'on if..else with identical leading lines' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
if something
do_x
^^^^ Move `do_x` out of the conditional.
method_call_here(1, 2, 3)
else
do_x
^^^^ Move `do_x` out of the conditional.
1 + 2 + 3
end
RUBY
expect_correction(<<~RUBY)
do_x
if something
method_call_here(1, 2, 3)
else
1 + 2 + 3
end
RUBY
end
end
context 'on if...else with identical leading lines and using index assign' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
if condition
h[:key] = foo
^^^^^^^^^^^^^ Move `h[:key] = foo` out of the conditional.
bar
else
h[:key] = foo
^^^^^^^^^^^^^ Move `h[:key] = foo` out of the conditional.
baz
end
RUBY
expect_correction(<<~RUBY)
h[:key] = foo
if condition
bar
else
baz
end
RUBY
end
end
context 'on if...else with identical leading lines and index assign to condition value' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
if h[:key]
h[:key] = foo
bar
else
h[:key] = foo
baz
end
RUBY
end
end
context 'on if...else with identical leading lines and assign to `self.foo`' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
if something
self.foo ||= default
^^^^^^^^^^^^^^^^^^^^ Move `self.foo ||= default` out of the conditional.
do_x
else
self.foo ||= default
^^^^^^^^^^^^^^^^^^^^ Move `self.foo ||= default` out of the conditional.
do_y
end
RUBY
expect_correction(<<~RUBY)
self.foo ||= default
if something
do_x
else
do_y
end
RUBY
end
end
context 'on if..else with identical leading lines and assign to condition value of method call receiver' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if x.condition
x = do_something
foo
else
x = do_something
bar
end
RUBY
end
end
context 'on if..else with identical leading lines and assign to condition value of safe navigation call receiver' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if x&.condition
x = do_something
foo
else
x = do_something
bar
end
RUBY
end
end
context 'on if..else with identical leading lines and assign to condition value of method call' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if x
x = do_something
foo
else
x = do_something
bar
end
RUBY
end
end
context 'on if..else with identical leading lines and assign to condition local variable' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
x = 42
if x
x = do_something
foo
else
x = do_something
bar
end
RUBY
end
end
context 'on if..else with identical leading lines and assign to condition instance variable' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if @x
@x = do_something
foo
else
@x = do_something
bar
end
RUBY
end
end
context 'on if..else with identical trailing lines and assign to condition value' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
if x.condition
foo
x = do_something
^^^^^^^^^^^^^^^^ Move `x = do_something` out of the conditional.
else
bar
x = do_something
^^^^^^^^^^^^^^^^ Move `x = do_something` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
if x.condition
foo
else
bar
end
x = do_something
RUBY
end
end
context 'on if..else with identical leading lines, single child branch and last node of the parent' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
def foo
if something
do_x
else
do_x
1 + 2 + 3
end
end
def bar
y = if something
do_x
else
do_x
1 + 2 + 3
end
do_something_else
end
RUBY
end
end
context 'on if..elsif with no else' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if something
do_x
elsif something_else
do_x
end
RUBY
end
end
context 'on if..else with slightly different trailing lines' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if something
do_x(1)
else
do_x(2)
end
RUBY
end
end
context 'on if..else with identical bodies and assigning to a variable used in `if` condition' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
x = 0
if x == 0
x += 1
foo
else
x += 1
bar
end
RUBY
end
end
context 'on case with identical bodies' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
case something
when :a
do_x
^^^^ Move `do_x` out of the conditional.
when :b
do_x
^^^^ Move `do_x` out of the conditional.
else
do_x
^^^^ Move `do_x` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
case something
when :a
when :b
else
end
do_x
RUBY
end
end
# Regression: https://github.com/rubocop/rubocop/issues/3868
context 'when one of the case branches is empty' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
case value
when cond1
else
if cond2
else
end
end
RUBY
end
end
context 'on case with identical trailing lines' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
case something
when :a
x1
do_x
^^^^ Move `do_x` out of the conditional.
when :b
x2
do_x
^^^^ Move `do_x` out of the conditional.
else
x3
do_x
^^^^ Move `do_x` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
case something
when :a
x1
when :b
x2
else
x3
end
do_x
RUBY
end
end
context 'on case with identical leading lines' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
case something
when :a
do_x
^^^^ Move `do_x` out of the conditional.
x1
when :b
do_x
^^^^ Move `do_x` out of the conditional.
x2
else
do_x
^^^^ Move `do_x` out of the conditional.
x3
end
RUBY
expect_correction(<<~RUBY)
do_x
case something
when :a
x1
when :b
x2
else
x3
end
RUBY
end
end
context 'on case with identical leading lines when handling nil case branches' do
it 'registers and corrects an offense' do
expect_no_offenses(<<~RUBY)
case something
when :a
nil
when :b
do_x
x1
else
do_x
x2
end
RUBY
end
end
context 'on case with identical leading lines when handling empty case branches' do
it 'registers and corrects an offense' do
expect_no_offenses(<<~RUBY)
case something
when :a
()
when :b
do_x
x1
else
do_x
x2
end
RUBY
end
end
context 'on case with identical leading lines, single child branch and last node of the parent' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
def foo
case something
when :a
do_x
when :b
do_x
x2
else
do_x
x3
end
end
def bar
x = case something
when :a
do_x
when :b
do_x
x2
else
do_x
x3
end
do_something
end
RUBY
end
end
context 'on case without else' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
case something
when :a
do_x
when :b
do_x
end
RUBY
end
end
context 'on case with empty when' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
case something
when :a
do_x
do_y
when :b
else
do_x
do_z
end
RUBY
end
end
context 'on case..when with identical bodies and assigning to a variable used in `case` condition' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
x = 0
case x
when 1
x += 1
foo
when 42
x += 1
bar
end
RUBY
end
end
context 'when using pattern matching', :ruby27 do
context 'on case-match with identical bodies' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
case something
in :a
do_x
^^^^ Move `do_x` out of the conditional.
in :b
do_x
^^^^ Move `do_x` out of the conditional.
else
do_x
^^^^ Move `do_x` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
case something
in :a
in :b
else
end
do_x
RUBY
end
context 'on case..in with identical bodies and assigning to a variable used in `case` condition' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
x = 0
case x
in 1
x += 1
foo
in 42
x += 1
bar
end
RUBY
end
end
end
context 'when one of the case-match branches is empty' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
case value
in cond1
else
if cond2
else
end
end
RUBY
end
end
context 'on case-match with identical trailing lines' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
case something
in :a
x1
do_x
^^^^ Move `do_x` out of the conditional.
in :b
x2
do_x
^^^^ Move `do_x` out of the conditional.
else
x3
do_x
^^^^ Move `do_x` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
case something
in :a
x1
in :b
x2
else
x3
end
do_x
RUBY
end
end
context 'on case-match with identical leading lines' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
case something
in :a
do_x
^^^^ Move `do_x` out of the conditional.
x1
in :b
do_x
^^^^ Move `do_x` out of the conditional.
x2
else
do_x
^^^^ Move `do_x` out of the conditional.
x3
end
RUBY
expect_correction(<<~RUBY)
do_x
case something
in :a
x1
in :b
x2
else
x3
end
RUBY
end
end
context 'on case-match with identical leading lines, single child branch and last node of the parent' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
def foo
case something
in :a
do_x
in :b
do_x
x2
else
do_x
x3
end
end
def bar
y = case something
in :a
do_x
in :b
do_x
x2
else
do_x
x3
end
do_something
end
RUBY
end
end
context 'on case-match without else' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
case something
in :a
do_x
in :b
do_x
end
RUBY
end
end
context 'on case-match with empty when' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
case something
in :a
do_x
do_y
in :b
else
do_x
do_z
end
RUBY
end
end
end
context 'with empty parentheses' do
it 'does not raise any error when using empty brace in the both parentheses' do
expect_no_offenses(<<~RUBY)
if condition
()
else
()
end
RUBY
end
it 'does not raise any error when using empty parentheses in the `if` branch' do
expect_no_offenses(<<~RUBY)
if condition
()
else
foo
end
RUBY
end
it 'does not raise any error when using empty parentheses in the `else` branch' do
expect_no_offenses(<<~RUBY)
if condition
foo
else
()
end
RUBY
end
end
context 'with a ternary' do
it 'registers an offense' do
expect_offense(<<~RUBY)
x ? y : y
^ Move `y` out of the conditional.
^ Move `y` out of the conditional.
RUBY
expect_no_corrections
end
end
context 'when the result of the conditional is assigned' do
context 'with identical trailing lines' do
context 'with `if`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
x = if foo
bar
^^^ Move `bar` out of the conditional.
else
bar
^^^ Move `bar` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
if foo
else
end
x = bar
RUBY
end
end
context 'with a ternary' do
it 'registers an offense but does not correct' do
expect_offense(<<~RUBY)
x = foo ? bar : bar
^^^ Move `bar` out of the conditional.
^^^ Move `bar` out of the conditional.
RUBY
expect_no_corrections
end
end
context 'with `case`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
x = case something
when :a
bar
^^^ Move `bar` out of the conditional.
when :b
bar
^^^ Move `bar` out of the conditional.
else
bar
^^^ Move `bar` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
case something
when :a
when :b
else
end
x = bar
RUBY
end
end
context 'with pattern matching', :ruby27 do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
x = case something
in :a
bar
^^^ Move `bar` out of the conditional.
in :b
bar
^^^ Move `bar` out of the conditional.
else
bar
^^^ Move `bar` out of the conditional.
end
RUBY
expect_correction(<<~RUBY)
case something
in :a
in :b
else
end
x = bar
RUBY
end
end
end
context 'with identical leading lines' do
context 'with `if`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
x = if foo
bar
^^^ Move `bar` out of the conditional.
do_x(1)
else
bar
^^^ Move `bar` out of the conditional.
do_x(2)
end
RUBY
expect_correction(<<~RUBY)
bar
x = if foo
do_x(1)
else
do_x(2)
end
RUBY
end
end
context 'with `case`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
x = case something
when :a
bar
^^^ Move `bar` out of the conditional.
do_x(1)
when :b
bar
^^^ Move `bar` out of the conditional.
do_x(2)
else
bar
^^^ Move `bar` out of the conditional.
do_x(3)
end
RUBY
expect_correction(<<~RUBY)
bar
x = case something
when :a
do_x(1)
when :b
do_x(2)
else
do_x(3)
end
RUBY
end
end
context 'with pattern matching', :ruby27 do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
x = case something
in :a
bar
^^^ Move `bar` out of the conditional.
do_x(1)
in :b
bar
^^^ Move `bar` out of the conditional.
do_x(2)
else
bar
^^^ Move `bar` out of the conditional.
do_x(3)
end
RUBY
expect_correction(<<~RUBY)
bar
x = case something
in :a
do_x(1)
in :b
do_x(2)
else
do_x(3)
end
RUBY
end
end
end
context 'with `if` in non-modifier form with `then`' do
context 'when expression is on the same line as `then`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def fixed_point(value)
if value then value
^^^^^ Move `value` out of the conditional.
else value
^^^^^ Move `value` out of the conditional.
end
end
RUBY
expect_no_corrections
end
it 'registers an offense when `else` branch is not inlined' do
expect_offense(<<~RUBY)
def fixed_point(value)
if value then value
^^^^^ Move `value` out of the conditional.
else
value
^^^^^ Move `value` out of the conditional.
end
end
RUBY
expect_no_corrections
end
end
context 'when expression is on the next line' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def fixed_point(value)
if value then
value
^^^^^ Move `value` out of the conditional.
else value
^^^^^ Move `value` out of the conditional.
end
end
RUBY
expect_no_corrections
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.