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/redundant_array_flatten_spec.rb | spec/rubocop/cop/style/redundant_array_flatten_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantArrayFlatten, :config do
it 'registers an offense for `x.flatten.join`' do
expect_offense(<<~RUBY)
x.flatten.join
^^^^^^^^ Remove the redundant `flatten`.
RUBY
expect_correction(<<~RUBY)
x.join
RUBY
end
it 'registers an offense for `x.flatten.join(nil)`' do
expect_offense(<<~RUBY)
x.flatten.join(nil)
^^^^^^^^ Remove the redundant `flatten`.
RUBY
expect_correction(<<~RUBY)
x.join(nil)
RUBY
end
it 'registers an offense for `x.flatten(depth).join`' do
expect_offense(<<~RUBY)
x.flatten(depth).join
^^^^^^^^^^^^^^^ Remove the redundant `flatten`.
RUBY
expect_correction(<<~RUBY)
x.join
RUBY
end
it 'registers an offense for `x&.flatten&.join`' do
expect_offense(<<~RUBY)
x&.flatten&.join
^^^^^^^^^ Remove the redundant `flatten`.
RUBY
expect_correction(<<~RUBY)
x&.join
RUBY
end
it 'does not register an offense for `x.flatten.foo`' do
expect_no_offenses(<<~RUBY)
x.flatten.foo
RUBY
end
it 'does not register an offense for `x.flatten`' do
expect_no_offenses(<<~RUBY)
x.flatten
RUBY
end
it 'does not register an offense for `x.flatten.join(separator)`' do
expect_no_offenses(<<~RUBY)
x.flatten.join(separator)
RUBY
end
it 'does not register an offense for `flatten.join` without an explicit receiver' do
expect_no_offenses(<<~RUBY)
flatten.join
RUBY
end
it 'does not register an offense for `x.flatten(depth, extra_arg).join`' do
expect_no_offenses(<<~RUBY)
x.flatten(depth, extra_arg).join
RUBY
end
it 'does not register an offense for `x.flatten.join(separator, extra_arg)`' do
expect_no_offenses(<<~RUBY)
x.flatten.join(separator, extra_arg)
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/nil_lambda_spec.rb | spec/rubocop/cop/style/nil_lambda_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NilLambda, :config do
context 'block lambda' do
it 'registers an offense when returning nil implicitly' do
expect_offense(<<~RUBY)
lambda do
^^^^^^^^^ Use an empty lambda instead of always returning nil.
nil
end
RUBY
expect_correction(<<~RUBY)
lambda do
end
RUBY
end
it 'registers an offense when returning nil with `return`' do
expect_offense(<<~RUBY)
lambda do
^^^^^^^^^ Use an empty lambda instead of always returning nil.
return nil
end
RUBY
expect_correction(<<~RUBY)
lambda do
end
RUBY
end
it 'registers an offense when returning nil with `break`' do
expect_offense(<<~RUBY)
lambda do
^^^^^^^^^ Use an empty lambda instead of always returning nil.
break nil
end
RUBY
expect_correction(<<~RUBY)
lambda do
end
RUBY
end
it 'registers an offense when returning nil with `next`' do
expect_offense(<<~RUBY)
lambda do
^^^^^^^^^ Use an empty lambda instead of always returning nil.
next nil
end
RUBY
expect_correction(<<~RUBY)
lambda do
end
RUBY
end
it 'does not register an offense when not returning nil' do
expect_no_offenses(<<~RUBY)
lambda do
6
end
RUBY
end
it 'does not register an offense when doing more than returning nil' do
expect_no_offenses(<<~RUBY)
lambda do |x|
x ? x.method : nil
end
RUBY
end
it 'does not remove block params or change spacing' do
expect_offense(<<~RUBY)
fn = lambda do |x|
^^^^^^^^^^^^^ Use an empty lambda instead of always returning nil.
nil
end
RUBY
expect_correction(<<~RUBY)
fn = lambda do |x|
end
RUBY
end
it 'properly corrects single line' do
expect_offense(<<~RUBY)
lambda { nil }
^^^^^^^^^^^^^^ Use an empty lambda instead of always returning nil.
RUBY
expect_correction(<<~RUBY)
lambda {}
RUBY
end
end
context 'stabby lambda' do
it 'registers an offense when returning nil implicitly' do
expect_offense(<<~RUBY)
-> { nil }
^^^^^^^^^^ Use an empty lambda instead of always returning nil.
RUBY
expect_correction(<<~RUBY)
-> {}
RUBY
end
it 'registers an offense when returning nil with `return`' do
expect_offense(<<~RUBY)
-> { return nil }
^^^^^^^^^^^^^^^^^ Use an empty lambda instead of always returning nil.
RUBY
expect_correction(<<~RUBY)
-> {}
RUBY
end
it 'registers an offense when returning nil with `break`' do
expect_offense(<<~RUBY)
-> { break nil }
^^^^^^^^^^^^^^^^ Use an empty lambda instead of always returning nil.
RUBY
expect_correction(<<~RUBY)
-> {}
RUBY
end
it 'registers an offense when returning nil with `next`' do
expect_offense(<<~RUBY)
-> { next nil }
^^^^^^^^^^^^^^^ Use an empty lambda instead of always returning nil.
RUBY
expect_correction(<<~RUBY)
-> {}
RUBY
end
it 'does not register an offense when not returning nil' do
expect_no_offenses(<<~RUBY)
-> { 6 }
RUBY
end
it 'does not register an offense when doing more than returning nil' do
expect_no_offenses(<<~RUBY)
->(x) { x ? x.method : nil }
RUBY
end
it 'properly corrects multiline' do
expect_offense(<<~RUBY)
-> do
^^^^^ Use an empty lambda instead of always returning nil.
nil
end
RUBY
expect_correction(<<~RUBY)
-> do
end
RUBY
end
end
context 'proc' do
it 'registers an offense when returning nil implicitly' do
expect_offense(<<~RUBY)
proc do
^^^^^^^ Use an empty proc instead of always returning nil.
nil
end
RUBY
expect_correction(<<~RUBY)
proc do
end
RUBY
end
it 'registers an offense when returning nil with `return`' do
expect_offense(<<~RUBY)
proc do
^^^^^^^ Use an empty proc instead of always returning nil.
return nil
end
RUBY
expect_correction(<<~RUBY)
proc do
end
RUBY
end
it 'registers an offense when returning nil with `break`' do
expect_offense(<<~RUBY)
proc do
^^^^^^^ Use an empty proc instead of always returning nil.
break nil
end
RUBY
expect_correction(<<~RUBY)
proc do
end
RUBY
end
it 'registers an offense when returning nil with `next`' do
expect_offense(<<~RUBY)
proc do
^^^^^^^ Use an empty proc instead of always returning nil.
next nil
end
RUBY
expect_correction(<<~RUBY)
proc do
end
RUBY
end
it 'does not register an offense when not returning nil' do
expect_no_offenses(<<~RUBY)
proc do
6
end
RUBY
end
it 'does not register an offense when doing more than returning nil' do
expect_no_offenses(<<~RUBY)
proc do |x|
x ? x.method : nil
end
RUBY
end
it 'does not remove block params or change spacing' do
expect_offense(<<~RUBY)
fn = proc do |x|
^^^^^^^^^^^ Use an empty proc instead of always returning nil.
nil
end
RUBY
expect_correction(<<~RUBY)
fn = proc do |x|
end
RUBY
end
it 'properly corrects single line' do
expect_offense(<<~RUBY)
proc { nil }
^^^^^^^^^^^^ Use an empty proc instead of always returning nil.
RUBY
expect_correction(<<~RUBY)
proc {}
RUBY
end
end
context 'Proc.new' do
it 'registers an offense when returning nil implicitly' do
expect_offense(<<~RUBY)
Proc.new do
^^^^^^^^^^^ Use an empty proc instead of always returning nil.
nil
end
RUBY
expect_correction(<<~RUBY)
Proc.new do
end
RUBY
end
it 'registers an offense when returning nil with `return`' do
expect_offense(<<~RUBY)
Proc.new do
^^^^^^^^^^^ Use an empty proc instead of always returning nil.
return nil
end
RUBY
expect_correction(<<~RUBY)
Proc.new do
end
RUBY
end
it 'registers an offense when returning nil with `break`' do
expect_offense(<<~RUBY)
Proc.new do
^^^^^^^^^^^ Use an empty proc instead of always returning nil.
break nil
end
RUBY
expect_correction(<<~RUBY)
Proc.new do
end
RUBY
end
it 'registers an offense when returning nil with `next`' do
expect_offense(<<~RUBY)
Proc.new do
^^^^^^^^^^^ Use an empty proc instead of always returning nil.
next nil
end
RUBY
expect_correction(<<~RUBY)
Proc.new do
end
RUBY
end
it 'does not register an offense when not returning nil' do
expect_no_offenses(<<~RUBY)
Proc.new do
6
end
RUBY
end
it 'does not register an offense when doing more than returning nil' do
expect_no_offenses(<<~RUBY)
Proc.new do |x|
x ? x.method : nil
end
RUBY
end
it 'does not remove block params or change spacing' do
expect_offense(<<~RUBY)
fn = Proc.new do |x|
^^^^^^^^^^^^^^^ Use an empty proc instead of always returning nil.
nil
end
RUBY
expect_correction(<<~RUBY)
fn = Proc.new do |x|
end
RUBY
end
it 'properly corrects single line' do
expect_offense(<<~RUBY)
Proc.new { nil }
^^^^^^^^^^^^^^^^ Use an empty proc instead of always returning nil.
RUBY
expect_correction(<<~RUBY)
Proc.new {}
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/explicit_block_argument_spec.rb | spec/rubocop/cop/style/explicit_block_argument_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ExplicitBlockArgument, :config do
it 'registers an offense and corrects when block just yields its arguments' do
expect_offense(<<~RUBY)
def m
items.something(first_arg) { |i| yield i }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def m(&block)
items.something(first_arg, &block)
end
RUBY
end
it 'registers an offense and corrects when multiple arguments are yielded' do
expect_offense(<<~RUBY)
def m
items.something(first_arg) { |i, j| yield i, j }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def m(&block)
items.something(first_arg, &block)
end
RUBY
end
it 'does not register an offense when arguments are yielded in a different order' do
expect_no_offenses(<<~RUBY)
def m
items.something(first_arg) { |i, j| yield j, i }
end
RUBY
end
it 'correctly corrects when method already has an explicit block argument' do
expect_offense(<<~RUBY)
def m(&blk)
items.something { |i| yield i }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def m(&blk)
items.something(&blk)
end
RUBY
end
it 'correctly corrects when the method call has a trailing comma in its argument list' do
expect_offense(<<~RUBY)
def m
items.something(a, b,) { |i| yield i }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def m(&block)
items.something(a, b, &block)
end
RUBY
end
it 'correctly corrects when using safe navigation method call' do
expect_offense(<<~RUBY)
def do_something
array&.each do |row|
^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
yield row
end
end
RUBY
expect_correction(<<~RUBY)
def do_something(&block)
array&.each(&block)
end
RUBY
end
it 'registers an offense and corrects when method contains multiple `yield`s' do
expect_offense(<<~RUBY)
def m
items.something { |i| yield i }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
if condition
yield 2
elsif other_condition
3.times { yield }
^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
else
other_items.something { |i, j| yield i, j }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
end
RUBY
expect_correction(<<~RUBY)
def m(&block)
items.something(&block)
if condition
yield 2
elsif other_condition
3.times(&block)
else
other_items.something(&block)
end
end
RUBY
end
it 'does not register an offense when `yield` is not inside block' do
expect_no_offenses(<<~RUBY)
def m
yield i
end
RUBY
end
it 'registers an offense and corrects when `yield` inside block has no arguments' do
expect_offense(<<~RUBY)
def m
3.times { yield }
^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def m(&block)
3.times(&block)
end
RUBY
end
it 'registers an offense and corrects when `yield` is inside block of `super`' do
expect_offense(<<~RUBY)
def do_something
super { yield }
^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def do_something(&block)
super(&block)
end
RUBY
end
it 'does not register an offense when `yield` is the sole block body' do
expect_no_offenses(<<~RUBY)
def m
items.something do |i|
do_something
yield i
end
end
RUBY
end
it 'does not register an offense when `yield` arguments is not a prefix of block arguments' do
expect_no_offenses(<<~RUBY)
def m
items.something { |i, j, k| yield j, k }
end
RUBY
end
it 'does not register an offense when there is more than one block argument and not all are yielded' do
expect_no_offenses(<<~RUBY)
def m
items.something { |i, j| yield i }
end
RUBY
end
it 'does not register an offense when code is called outside of a method' do
expect_no_offenses(<<~RUBY)
render("partial") do
yield
end
RUBY
end
it 'does not add extra parens when correcting' do
expect_offense(<<~RUBY)
def my_method()
foo() { yield }
^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY, loop: false)
def my_method(&block)
foo(&block)
end
RUBY
end
it 'does not add extra parens to `super` when correcting' do
expect_offense(<<~RUBY)
def my_method
super() { yield }
^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY, loop: false)
def my_method(&block)
super(&block)
end
RUBY
end
it 'adds to the existing arguments when correcting' do
expect_offense(<<~RUBY)
def my_method(x)
foo(x) { yield }
^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def my_method(x, &block)
foo(x, &block)
end
RUBY
end
it 'registers an offense when using arguments with zsuper in a method definition' do
expect_offense(<<~RUBY)
def my_method(x, y = 42, *args, **options)
super { yield }
^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def my_method(x, y = 42, *args, **options, &block)
super(x, y, *args, **options, &block)
end
RUBY
end
it 'registers an offense when using arguments with zsuper in a singleton method definition' do
expect_offense(<<~RUBY)
def self.my_method(x, y = 42, *args, **options)
super { yield }
^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def self.my_method(x, y = 42, *args, **options, &block)
super(x, y, *args, **options, &block)
end
RUBY
end
it 'registers an offense and corrects when there are two methods with the same implementation and name' do
expect_offense(<<~RUBY)
def foo
bar { |baz| yield baz }
^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
def foo
bar { |baz| yield baz }
^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
RUBY
expect_correction(<<~RUBY)
def foo(&block)
bar(&block)
end
def foo(&block)
bar(&block)
end
RUBY
end
it 'registers an offense when there are nested method definitions' do
expect_offense(<<~RUBY)
def foo
def bar.baz
qux { |quux| yield quux }
^^^^^^^^^^^^^^^^^^^^^^^^^ Consider using explicit block argument in the surrounding method's signature over `yield`.
end
end
RUBY
expect_correction(<<~RUBY)
def foo
def bar.baz(&block)
qux(&block)
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/command_literal_spec.rb | spec/rubocop/cop/style/command_literal_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CommandLiteral, :config do
let(:config) do
supported_styles = { 'SupportedStyles' => %w[backticks percent_x mixed] }
RuboCop::Config.new('Style/PercentLiteralDelimiters' =>
percent_literal_delimiters_config,
'Style/CommandLiteral' =>
cop_config.merge(supported_styles))
end
let(:percent_literal_delimiters_config) { { 'PreferredDelimiters' => { '%x' => '()' } } }
describe '%x commands with other delimiters than parentheses' do
let(:cop_config) { { 'EnforcedStyle' => 'backticks' } }
it 'registers an offense' do
expect_offense(<<~RUBY)
%x$ls$
^^^^^^ Use backticks around command string.
RUBY
end
end
describe 'when PercentLiteralDelimiters is configured with curly braces' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
let(:percent_literal_delimiters_config) { { 'PreferredDelimiters' => { '%x' => '[]' } } }
it 'respects the configuration when autocorrecting' do
expect_offense(<<~RUBY)
`ls`
^^^^ Use `%x` around command string.
RUBY
expect_correction(<<~RUBY)
%x[ls]
RUBY
end
end
describe 'when PercentLiteralDelimiters only has a default' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
let(:percent_literal_delimiters_config) do
{ 'PreferredDelimiters' => { 'default' => '()' } }
end
it 'respects the configuration when autocorrecting' do
expect_offense(<<~RUBY)
`ls`
^^^^ Use `%x` around command string.
RUBY
expect_correction(<<~RUBY)
%x(ls)
RUBY
end
end
describe 'when PercentLiteralDelimiters is configured and a default exists' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
let(:percent_literal_delimiters_config) do
{ 'PreferredDelimiters' => { '%x' => '[]', 'default' => '()' } }
end
it 'ignores the default when autocorrecting' do
expect_offense(<<~RUBY)
`ls`
^^^^ Use `%x` around command string.
RUBY
expect_correction(<<~RUBY)
%x[ls]
RUBY
end
end
describe 'heredoc commands' do
let(:cop_config) { { 'EnforcedStyle' => 'backticks' } }
it 'is ignored' do
expect_no_offenses(<<~RUBY)
<<`COMMAND`
ls
COMMAND
RUBY
end
end
context 'when EnforcedStyle is set to backticks' do
let(:cop_config) { { 'EnforcedStyle' => 'backticks' } }
describe 'a single-line ` string without backticks' do
it 'is accepted' do
expect_no_offenses('foo = `ls`')
end
end
describe 'a single-line ` string with backticks' do
it 'registers an offense without autocorrection' do
expect_offense(<<~'RUBY')
foo = `echo \`ls\``
^^^^^^^^^^^^^ Use `%x` around command string.
RUBY
expect_no_corrections
end
describe 'when configured to allow inner backticks' do
before { cop_config['AllowInnerBackticks'] = true }
it 'is accepted' do
expect_no_offenses('foo = `echo \\`ls\\``')
end
end
end
describe 'a multi-line ` string without backticks' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = `
ls
ls -l
`
RUBY
end
end
describe 'a multi-line ` string with backticks' do
it 'registers an offense without autocorrection' do
expect_offense(<<~'RUBY')
foo = `
^ Use `%x` around command string.
echo \`ls\`
echo \`ls -l\`
`
RUBY
expect_no_corrections
end
describe 'when configured to allow inner backticks' do
before { cop_config['AllowInnerBackticks'] = true }
it 'is accepted' do
expect_no_offenses(<<~'RUBY')
foo = `
echo \`ls\`
echo \`ls -l\`
`
RUBY
end
end
end
describe 'a single-line %x string without backticks' do
it 'registers an offense and corrects to backticks' do
expect_offense(<<~RUBY)
foo = %x(ls)
^^^^^^ Use backticks around command string.
RUBY
expect_correction(<<~RUBY)
foo = `ls`
RUBY
end
end
describe 'a single-line %x string with backticks' do
it 'is accepted' do
expect_no_offenses('foo = %x(echo `ls`)')
end
describe 'when configured to allow inner backticks' do
before { cop_config['AllowInnerBackticks'] = true }
it 'registers an offense without autocorrection' do
expect_offense(<<~RUBY)
foo = %x(echo `ls`)
^^^^^^^^^^^^^ Use backticks around command string.
RUBY
expect_no_corrections
end
end
end
describe 'a multi-line %x string without backticks' do
it 'registers an offense and corrects to backticks' do
expect_offense(<<~RUBY)
foo = %x(
^^^ Use backticks around command string.
ls
ls -l
)
RUBY
expect_correction(<<~RUBY)
foo = `
ls
ls -l
`
RUBY
end
end
describe 'a multi-line %x string with backticks' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = %x(
echo `ls`
echo `ls -l`
)
RUBY
end
describe 'when configured to allow inner backticks' do
before { cop_config['AllowInnerBackticks'] = true }
it 'registers an offense without autocorrection' do
expect_offense(<<~RUBY)
foo = %x(
^^^ Use backticks around command string.
echo `ls`
echo `ls -l`
)
RUBY
expect_no_corrections
end
end
end
end
context 'when EnforcedStyle is set to percent_x' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_x' } }
describe 'a single-line ` string without backticks' do
it 'registers an offense and corrects to %x' do
expect_offense(<<~RUBY)
foo = `ls`
^^^^ Use `%x` around command string.
RUBY
expect_correction(<<~RUBY)
foo = %x(ls)
RUBY
end
end
describe 'a single-line ` string with backticks' do
it 'registers an offense without autocorrection' do
expect_offense(<<~'RUBY')
foo = `echo \`ls\``
^^^^^^^^^^^^^ Use `%x` around command string.
RUBY
expect_no_corrections
end
end
describe 'a multi-line ` string without backticks' do
it 'registers an offense and corrects to %x' do
expect_offense(<<~RUBY)
foo = `
^ Use `%x` around command string.
ls
ls -l
`
RUBY
expect_correction(<<~RUBY)
foo = %x(
ls
ls -l
)
RUBY
end
end
describe 'a multi-line ` string with backticks' do
it 'registers an offense without autocorrection' do
expect_offense(<<~'RUBY')
foo = `
^ Use `%x` around command string.
echo \`ls\`
echo \`ls -l\`
`
RUBY
expect_no_corrections
end
end
describe 'a single-line %x string without backticks' do
it 'is accepted' do
expect_no_offenses('foo = %x(ls)')
end
end
describe 'a single-line %x string with backticks' do
it 'is accepted' do
expect_no_offenses('foo = %x(echo `ls`)')
end
end
describe 'a multi-line %x string without backticks' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = %x(
ls
ls -l
)
RUBY
end
end
describe 'a multi-line %x string with backticks' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = %x(
echo `ls`
echo `ls -l`
)
RUBY
end
end
end
context 'when EnforcedStyle is set to mixed' do
let(:cop_config) { { 'EnforcedStyle' => 'mixed' } }
describe 'a single-line ` string without backticks' do
it 'is accepted' do
expect_no_offenses('foo = `ls`')
end
end
describe 'a single-line ` string with backticks' do
it 'registers an offense without autocorrection' do
expect_offense(<<~'RUBY')
foo = `echo \`ls\``
^^^^^^^^^^^^^ Use `%x` around command string.
RUBY
expect_no_corrections
end
describe 'when configured to allow inner backticks' do
before { cop_config['AllowInnerBackticks'] = true }
it 'is accepted' do
expect_no_offenses('foo = `echo \\`ls\\``')
end
end
end
describe 'a multi-line ` string without backticks' do
it 'registers an offense and corrects to %x' do
expect_offense(<<~RUBY)
foo = `
^ Use `%x` around command string.
ls
ls -l
`
RUBY
expect_correction(<<~RUBY)
foo = %x(
ls
ls -l
)
RUBY
end
end
describe 'a multi-line ` string with backticks' do
it 'registers an offense without autocorrection' do
expect_offense(<<~'RUBY')
foo = `
^ Use `%x` around command string.
echo \`ls\`
echo \`ls -l\`
`
RUBY
expect_no_corrections
end
end
describe 'a single-line %x string without backticks' do
it 'registers an offense and corrects to backticks' do
expect_offense(<<~RUBY)
foo = %x(ls)
^^^^^^ Use backticks around command string.
RUBY
expect_correction(<<~RUBY)
foo = `ls`
RUBY
end
end
describe 'a single-line %x string with backticks' do
it 'is accepted' do
expect_no_offenses('foo = %x(echo `ls`)')
end
describe 'when configured to allow inner backticks' do
before { cop_config['AllowInnerBackticks'] = true }
it 'registers an offense without autocorrection' do
expect_offense(<<~RUBY)
foo = %x(echo `ls`)
^^^^^^^^^^^^^ Use backticks around command string.
RUBY
expect_no_corrections
end
end
end
describe 'a multi-line %x string without backticks' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = %x(
ls
ls -l
)
RUBY
end
end
describe 'a multi-line %x string with backticks' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = %x(
echo `ls`
echo `ls -l`
)
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/exponential_notation_spec.rb | spec/rubocop/cop/style/exponential_notation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ExponentialNotation, :config do
context 'EnforcedStyle is scientific' do
let(:cop_config) { { 'EnforcedStyle' => 'scientific' } }
it 'registers an offense for mantissa equal to 10' do
expect_offense(<<~RUBY)
10e6
^^^^ Use a mantissa >= 1 and < 10.
RUBY
end
it 'registers an offense for mantissa greater than 10' do
expect_offense(<<~RUBY)
12.34e3
^^^^^^^ Use a mantissa >= 1 and < 10.
RUBY
end
it 'registers an offense for mantissa smaller than 1' do
expect_offense(<<~RUBY)
0.314e1
^^^^^^^ Use a mantissa >= 1 and < 10.
RUBY
end
it 'registers no offense for a regular float' do
expect_no_offenses('120.03')
end
it 'registers no offense for a float smaller than 1' do
expect_no_offenses('0.07390')
end
it 'registers no offense for a mantissa equal to 1' do
expect_no_offenses('1e6')
end
it 'registers no offense for a mantissa between 1 and 10' do
expect_no_offenses('3.1415e3')
end
it 'registers no offense for a negative mantissa' do
expect_no_offenses('-9.999e3')
end
it 'registers no offense for a negative exponent' do
expect_no_offenses('5.02e-3')
end
end
context 'EnforcedStyle is engineering' do
let(:cop_config) { { 'EnforcedStyle' => 'engineering' } }
it 'registers an offense for exponent equal to 4' do
expect_offense(<<~RUBY)
10e4
^^^^ Use an exponent divisible by 3 and a mantissa >= 0.1 and < 1000.
RUBY
end
it 'registers an offense for exponent equal to -2' do
expect_offense(<<~RUBY)
12.3e-2
^^^^^^^ Use an exponent divisible by 3 and a mantissa >= 0.1 and < 1000.
RUBY
end
it 'registers an offense for mantissa smaller than 0.1' do
expect_offense(<<~RUBY)
0.09e9
^^^^^^ Use an exponent divisible by 3 and a mantissa >= 0.1 and < 1000.
RUBY
end
it 'registers an offense for a mantissa greater than -0.1' do
expect_offense(<<~RUBY)
-0.09e3
^^^^^^^ Use an exponent divisible by 3 and a mantissa >= 0.1 and < 1000.
RUBY
end
it 'registers an offense for mantissa smaller than -1000' do
expect_offense(<<~RUBY)
-1012.34e6
^^^^^^^^^^ Use an exponent divisible by 3 and a mantissa >= 0.1 and < 1000.
RUBY
end
it 'registers no offense for a mantissa equal to 1' do
expect_no_offenses('1e6')
end
it 'registers no offense for a regular float' do
expect_no_offenses('120.03')
end
it 'registers no offense for a float smaller than 1' do
expect_no_offenses('0.07390')
end
it 'registers no offense for a negative exponent' do
expect_no_offenses('3.1415e-12')
end
it 'registers no offense for a negative mantissa' do
expect_no_offenses('-999.9e3')
end
it 'registers no offense for a large mantissa' do
expect_no_offenses('968.64982e12')
end
end
context 'EnforcedStyle is integral' do
let(:cop_config) { { 'EnforcedStyle' => 'integral' } }
it 'registers an offense for decimal mantissa' do
expect_offense(<<~RUBY)
1.2e3
^^^^^ Use an integer as mantissa, without trailing zero.
RUBY
end
it 'registers an offense for mantissa divisible by 10' do
expect_offense(<<~RUBY)
120e-4
^^^^^^ Use an integer as mantissa, without trailing zero.
RUBY
end
it 'registers no offense for a regular float' do
expect_no_offenses('120.03')
end
it 'registers no offense for a float smaller than 1' do
expect_no_offenses('0.07390')
end
it 'registers no offense for an integral mantissa' do
expect_no_offenses('7652e7')
end
it 'registers no offense for negative mantissa' do
expect_no_offenses('-84e7')
end
it 'registers no offense for negative exponent' do
expect_no_offenses('84e-7')
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/comparable_between_spec.rb | spec/rubocop/cop/style/comparable_between_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ComparableBetween, :config do
[
'x >= min && x <= max',
'x >= min && max >= x',
'min <= x && x <= max',
'min <= x && max >= x',
'x <= max && x >= min',
'x <= max && min <= x',
'max >= x && x >= min',
'max >= x && min <= x'
].each do |logical_comparison|
it "registers an offense with logical comparison #{logical_comparison}" do
expect_offense(<<~RUBY)
#{logical_comparison}
^^^^^^^^^^^^^^^^^^^^ Prefer `x.between?(min, max)` over logical comparison.
RUBY
expect_correction(<<~RUBY)
x.between?(min, max)
RUBY
end
end
it 'registers an offense when using logical comparison with `and`' do
expect_offense(<<~RUBY)
x >= min and x <= max
^^^^^^^^^^^^^^^^^^^^^ Prefer `x.between?(min, max)` over logical comparison.
RUBY
expect_correction(<<~RUBY)
x.between?(min, max)
RUBY
end
it 'registers an offense when comparing with itself as the min value' do
expect_offense(<<~RUBY)
x >= x and x <= max
^^^^^^^^^^^^^^^^^^^ Prefer `x.between?(x, max)` over logical comparison.
RUBY
expect_correction(<<~RUBY)
x.between?(x, max)
RUBY
end
it 'registers an offense when comparing with itself as both the min and max value' do
expect_offense(<<~RUBY)
x >= x and x <= x
^^^^^^^^^^^^^^^^^ Prefer `x.between?(x, x)` over logical comparison.
RUBY
expect_correction(<<~RUBY)
x.between?(x, x)
RUBY
end
it 'does not register an offense when logical comparison excludes max value' do
expect_no_offenses(<<~RUBY)
x >= min && x < max
RUBY
end
it 'does not register an offense when logical comparison excludes min value' do
expect_no_offenses(<<~RUBY)
x > min && x <= max
RUBY
end
it 'does not register an offense when logical comparison excludes min and max value' do
expect_no_offenses(<<~RUBY)
x > min && x < max
RUBY
end
it 'does not register an offense when logical comparison has different subjects for min and max' do
expect_no_offenses(<<~RUBY)
x >= min && y <= max
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_transform_keys_spec.rb | spec/rubocop/cop/style/hash_transform_keys_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashTransformKeys, :config do
context 'when using Ruby 2.5 or newer', :ruby25 do
context 'with inline block' do
it 'flags each_with_object when transform_keys could be used' do
expect_offense(<<~RUBY)
x.each_with_object({}) {|(k, v), h| h[foo(k)] = v}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `each_with_object`.
RUBY
expect_correction(<<~RUBY)
x.transform_keys {|k| foo(k)}
RUBY
end
end
context 'with multiline block' do
it 'flags each_with_object when transform_keys could be used' do
expect_offense(<<~RUBY)
some_hash.each_with_object({}) do |(key, val), memo|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `each_with_object`.
memo[key.to_sym] = val
end
RUBY
expect_correction(<<~RUBY)
some_hash.transform_keys do |key|
key.to_sym
end
RUBY
end
end
context 'with safe navigation operator' do
it 'flags each_with_object when transform_keys could be used' do
expect_offense(<<~RUBY)
x&.each_with_object({}) {|(k, v), h| h[foo(k)] = v}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `each_with_object`.
RUBY
expect_correction(<<~RUBY)
x&.transform_keys {|k| foo(k)}
RUBY
end
end
it 'does not flag each_with_object when both key & value are transformed' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) {|(k, v), h| h[k.to_sym] = foo(v)}
RUBY
end
it 'does not flag each_with_object when key transformation uses value' do
expect_no_offenses('x.each_with_object({}) {|(k, v), h| h[foo(v)] = v}')
end
it 'does not flag each_with_object when no transformation occurs' do
expect_no_offenses('x.each_with_object({}) {|(k, v), h| h[k] = v}')
end
it 'does not flag each_with_object when its argument is not modified' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) {|(k, v), h| other_h[k.to_sym] = v}
RUBY
end
it 'does not flag `each_with_object` when its argument is used in the key' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) { |(k, v), h| h[h[k.to_sym]] = v }
RUBY
end
it 'does not flag each_with_object when its receiver is array literal' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_object({}) {|(k, v), h| h[foo(k)] = v}
RUBY
end
it 'does not flag `each_with_object` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_index.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
RUBY
end
it 'does not flag `each_with_object` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each.with_index.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
RUBY
end
it 'does not flag `each_with_object` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
%i[a b c].zip([1, 2, 3]).each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
RUBY
end
it 'flags _.map{...}.to_h when transform_keys could be used' do
expect_offense(<<~RUBY)
x.map {|k, v| [k.to_sym, v]}.to_h
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `map {...}.to_h`.
RUBY
expect_correction(<<~RUBY)
x.transform_keys {|k| k.to_sym}
RUBY
end
it 'flags _.map{...}.to_h when transform_keys could be used when line break before `to_h`' do
expect_offense(<<~RUBY)
x.map {|k, v| [k.to_sym, v]}.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `map {...}.to_h`.
to_h
RUBY
expect_correction(<<~RUBY)
x.transform_keys {|k| k.to_sym}
RUBY
end
it 'flags _.map {...}.to_h when transform_keys could be used when wrapped in another block' do
expect_offense(<<~RUBY)
wrapping do
x.map do |k, v|
^^^^^^^^^^^^^^^ Prefer `transform_keys` over `map {...}.to_h`.
[k.to_sym, v]
end.to_h
end
RUBY
expect_correction(<<~RUBY)
wrapping do
x.transform_keys do |k|
k.to_sym
end
end
RUBY
end
it 'does not flag _.map{...}.to_h when both key & value are transformed' do
expect_no_offenses('x.map {|k, v| [k.to_sym, foo(v)]}.to_h')
end
it 'flags Hash[_.map{...}] when transform_keys could be used' do
expect_offense(<<~RUBY)
Hash[x.map {|k, v| [k.to_sym, v]}]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `Hash[_.map {...}]`.
RUBY
expect_correction(<<~RUBY)
x.transform_keys {|k| k.to_sym}
RUBY
end
it 'does not flag Hash[_.map{...}] when both key & value are transformed' do
expect_no_offenses('Hash[x.map {|k, v| [k.to_sym, foo(v)]}]')
end
it 'does not flag _.map {...}.to_h when key block argument is unused' do
expect_no_offenses(<<~RUBY)
x.map {|_k, v| [v, v]}.to_h
RUBY
end
it 'does not flag key transformation in the absence of to_h' do
expect_no_offenses('x.map {|k, v| [k.to_sym, v]}')
end
it 'does not flag key transformation when receiver is array literal' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].map {|k, v| [k.to_sym, v]}.to_h
RUBY
end
it 'does not flag `_.map{...}.to_h` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_index.map { |k, v| [k.to_sym, v] }.to_h
RUBY
end
it 'does not flag `_.map{...}.to_h` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each.with_index.map { |k, v| [k.to_sym, v] }.to_h
RUBY
end
it 'does not flag `_.map{...}.to_h` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
%i[a b c].zip([1, 2, 3]).map { |k, v| [k.to_sym, v] }.to_h
RUBY
end
it 'correctly autocorrects _.map{...}.to_h without block' do
expect_offense(<<~RUBY)
{a: 1, b: 2}.map do |k, v|
^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `map {...}.to_h`.
[k.to_s, v]
end.to_h
RUBY
expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_keys do |k|
k.to_s
end
RUBY
end
it 'correctly autocorrects _.map{...}.to_h with block' do
expect_offense(<<~RUBY)
{a: 1, b: 2}.map {|k, v| [k.to_s, v]}.to_h {|k, v| [v, k]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `map {...}.to_h`.
RUBY
expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_keys {|k| k.to_s}.to_h {|k, v| [v, k]}
RUBY
end
it 'correctly autocorrects Hash[_.map{...}]' do
expect_offense(<<~RUBY)
Hash[{a: 1, b: 2}.map do |k, v|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `Hash[_.map {...}]`.
[k.to_s, v]
end]
RUBY
expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_keys do |k|
k.to_s
end
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is an array literal' do
expect_no_offenses(<<~RUBY)
Hash[[1, 2, 3].map { |k, v| [k.to_sym, v] }]
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
Hash[[1, 2, 3].each_with_index.map { |k, v| [k.to_sym, v] }]
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
Hash[[1, 2, 3].each.with_index.map { |k, v| [k.to_sym, v] }]
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
Hash[%i[a b c].zip([1, 2, 3]).map { |k, v| [k.to_sym, v] }]
RUBY
end
end
context 'below Ruby 2.5', :ruby24, unsupported_on: :prism do
it 'does not flag even if transform_keys could be used' do
expect_no_offenses('x.each_with_object({}) {|(k, v), h| h[foo(k)] = v}')
end
end
context 'when using Ruby 2.6 or newer', :ruby26 do
it 'flags _.to_h{...} when transform_keys could be used' do
expect_offense(<<~RUBY)
x.to_h {|k, v| [k.to_sym, v]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_keys` over `to_h {...}`.
RUBY
expect_correction(<<~RUBY)
x.transform_keys {|k| k.to_sym}
RUBY
end
it 'does not flag `_.to_h{...}` when both key & value are transformed' do
expect_no_offenses(<<~RUBY)
x.to_h { |k, v| [k.to_sym, foo(v)] }
RUBY
end
it 'does not flag _.to_h {...} when key block argument is unused' do
expect_no_offenses(<<~RUBY)
x.to_h {|_k, v| [v, v]}
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is an array literal' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].to_h { |k, v| [k.to_sym, v] }
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_index.to_h { |k, v| [k.to_sym, v] }
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each.with_index.to_h { |k, v| [k.to_sym, v] }
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
%i[a b c].zip([1, 2, 3]).to_h { |k, v| [k.to_sym, v] }
RUBY
end
end
context 'below Ruby 2.6', :ruby25, unsupported_on: :prism do
it 'does not flag _.to_h{...}' do
expect_no_offenses(<<~RUBY)
x.to_h {|k, v| [k.to_sym, v]}
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_memoization_spec.rb | spec/rubocop/cop/style/multiline_memoization_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineMemoization, :config do
shared_examples 'with all enforced styles' do
context 'with a single line memoization' do
it 'allows expression on first line' do
expect_no_offenses('foo ||= bar')
end
it 'allows expression on the following line' do
expect_no_offenses(<<~RUBY)
foo ||=
bar
RUBY
end
end
context 'with a multiline memoization' do
context 'without a `begin` and `end` block' do
it 'allows with another block on the first line' do
expect_no_offenses(<<~RUBY)
foo ||= bar.each do |b|
b.baz
bb.ax
end
RUBY
end
it 'allows with another block on the following line' do
expect_no_offenses(<<~RUBY)
foo ||=
bar.each do |b|
b.baz
b.bax
end
RUBY
end
it 'allows with a conditional on the first line' do
expect_no_offenses(<<~RUBY)
foo ||= if bar
baz
else
bax
end
RUBY
end
it 'allows with a conditional on the following line' do
expect_no_offenses(<<~RUBY)
foo ||=
if bar
baz
else
bax
end
RUBY
end
end
end
end
context 'EnforcedStyle: keyword' do
let(:cop_config) { { 'EnforcedStyle' => 'keyword' } }
it_behaves_like 'with all enforced styles'
context 'with a multiline memoization' do
context 'without a `begin` and `end` block' do
context 'when the expression is wrapped in parentheses' do
it 'registers an offense when expression starts on first line' do
expect_offense(<<~RUBY)
foo ||= (
^^^^^^^^^ Wrap multiline memoization blocks in `begin` and `end`.
bar
baz
)
RUBY
expect_correction(<<~RUBY)
foo ||= begin
bar
baz
end
RUBY
end
it 'registers an offense when expression starts on following line' do
expect_offense(<<~RUBY)
foo ||=
^^^^^^^ Wrap multiline memoization blocks in `begin` and `end`.
(
bar
baz
)
RUBY
expect_correction(<<~RUBY)
foo ||=
begin
bar
baz
end
RUBY
end
it 'registers an offense with multiline expression' do
expect_offense(<<~RUBY)
foo ||= (bar ||
^^^^^^^^^^^^^^^ Wrap multiline memoization blocks in `begin` and `end`.
baz)
RUBY
expect_correction(<<~RUBY)
foo ||= begin
bar ||
baz
end
RUBY
end
end
end
end
end
context 'EnforcedStyle: braces' do
let(:cop_config) { { 'EnforcedStyle' => 'braces' } }
it_behaves_like 'with all enforced styles'
context 'with a multiline memoization' do
context 'without braces' do
context 'when the expression is wrapped in `begin` and `end` keywords' do
it 'registers an offense for begin...end block on first line' do
expect_offense(<<~RUBY)
foo ||= begin
^^^^^^^^^^^^^ Wrap multiline memoization blocks in `(` and `)`.
bar
baz
end
RUBY
expect_correction(<<~RUBY)
foo ||= (
bar
baz
)
RUBY
end
it 'registers an offense for begin...end block on following line' do
expect_offense(<<~RUBY)
foo ||=
^^^^^^^ Wrap multiline memoization blocks in `(` and `)`.
begin
bar
baz
end
RUBY
expect_correction(<<~RUBY)
foo ||=
(
bar
baz
)
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/file_write_spec.rb | spec/rubocop/cop/style/file_write_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FileWrite, :config do
it 'does not register an offense for the `File.open` with multiline write block when not writing to the block variable' do
expect_no_offenses(<<~RUBY)
File.open(filename, 'w') do |f|
something.write(content)
end
RUBY
end
it 'does not register an offense when a splat argument is passed to `f.write`' do
expect_no_offenses(<<~RUBY)
File.open(filename, 'w') do |f|
f.write(*objects)
end
RUBY
end
described_class::TRUNCATING_WRITE_MODES.each do |mode|
it "registers an offense for and corrects `File.open(filename, '#{mode}').write(content)`" do
write_method = mode.end_with?('b') ? :binwrite : :write
expect_offense(<<~RUBY)
File.open(filename, '#{mode}').write(content)
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^^^^^^^^^ Use `File.#{write_method}`.
RUBY
expect_correction(<<~RUBY)
File.#{write_method}(filename, content)
RUBY
end
it "registers an offense for and corrects `::File.open(filename, '#{mode}').write(content)`" do
write_method = mode.end_with?('b') ? :binwrite : :write
expect_offense(<<~RUBY)
::File.open(filename, '#{mode}').write(content)
^^^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^^^^^^^^^ Use `File.#{write_method}`.
RUBY
expect_correction(<<~RUBY)
::File.#{write_method}(filename, content)
RUBY
end
it "registers an offense for and corrects the `File.open` with inline write block (mode '#{mode}')" do
write_method = mode.end_with?('b') ? :binwrite : :write
expect_offense(<<~RUBY)
File.open(filename, '#{mode}') { |f| f.write(content) }
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.#{write_method}`.
RUBY
expect_correction(<<~RUBY)
File.#{write_method}(filename, content)
RUBY
end
it "registers an offense for and corrects the `File.open` with multiline write block (mode '#{mode}')" do
write_method = mode.end_with?('b') ? :binwrite : :write
expect_offense(<<~RUBY)
File.open(filename, '#{mode}') do |f|
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^ Use `File.#{write_method}`.
f.write(content)
end
RUBY
expect_correction(<<~RUBY)
File.#{write_method}(filename, content)
RUBY
end
it "registers an offense for and corrects the `File.open` with multiline write block (mode '#{mode}') with heredoc" do
write_method = mode.end_with?('b') ? :binwrite : :write
expect_offense(<<~RUBY)
File.open(filename, '#{mode}') do |f|
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^ Use `File.#{write_method}`.
f.write(<<~EOS)
content
EOS
end
RUBY
expect_correction(<<~RUBY)
File.#{write_method}(filename, <<~EOS)
content
EOS
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_capital_w_spec.rb | spec/rubocop/cop/style/redundant_capital_w_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantCapitalW, :config do
it 'registers no offense for normal arrays of strings' do
expect_no_offenses('["one", "two", "three"]')
end
it 'registers no offense for normal arrays of strings with interpolation' do
expect_no_offenses('["one", "two", "th#{?r}ee"]')
end
it 'registers an offense for misused %W' do
expect_offense(<<~RUBY)
%W(cat dog)
^^^^^^^^^^^ Do not use `%W` unless interpolation is needed. If not, use `%w`.
RUBY
expect_correction(<<~RUBY)
%w(cat dog)
RUBY
end
it 'registers an offense for misused %W with different bracket' do
expect_offense(<<~RUBY)
%W[cat dog]
^^^^^^^^^^^ Do not use `%W` unless interpolation is needed. If not, use `%w`.
RUBY
expect_correction(<<~RUBY)
%w[cat dog]
RUBY
end
it 'registers no offense for %W with interpolation' do
expect_no_offenses('%W(c#{?a}t dog)')
end
it 'registers no offense for %W with special characters' do
expect_no_offenses(<<~'RUBY')
def dangerous_characters
%W(\000) +
%W(\001) +
%W(\027) +
%W(\002) +
%W(\003) +
%W(\004) +
%W(\005) +
%W(\006) +
%W(\007) +
%W(\00) +
%W(\a)
%W(\s)
%W(\n)
%W(\!)
end
RUBY
end
it 'registers no offense for %w without interpolation' do
expect_no_offenses('%w(cat dog)')
end
it 'registers no offense for %w with interpolation-like syntax' do
expect_no_offenses('%w(c#{?a}t dog)')
end
it 'registers no offense for arrays with character constants' do
expect_no_offenses('["one", ?\n]')
end
it 'does not register an offense for array of non-words' do
expect_no_offenses('["one space", "two", "three"]')
end
it 'does not register an offense for array containing non-string' do
expect_no_offenses('["one", "two", 3]')
end
it 'does not register an offense for array with one element' do
expect_no_offenses('["three"]')
end
it 'does not register an offense for array with empty strings' do
expect_no_offenses('["", "two", "three"]')
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_method_end_statement_spec.rb | spec/rubocop/cop/style/trailing_method_end_statement_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrailingMethodEndStatement, :config do
let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 2 }) }
it 'registers an offense with trailing end on 2 line method' do
expect_offense(<<~RUBY)
def some_method
foo; end
^^^ Place the end statement of a multi-line method on its own line.
RUBY
expect_correction(<<~RUBY)
def some_method
foo;#{trailing_whitespace}
end
RUBY
end
it 'registers an offense with trailing end on 3 line method' do
expect_offense(<<~RUBY)
def a
b
{ foo: bar }; end
^^^ Place the end statement of a multi-line method on its own line.
RUBY
expect_correction(<<~RUBY)
def a
b
{ foo: bar };#{trailing_whitespace}
end
RUBY
end
it 'registers an offense with trailing end on method with comment' do
expect_offense(<<~RUBY)
def c
b = calculation
[b] end # because b
^^^ Place the end statement of a multi-line method on its own line.
RUBY
expect_correction(<<~RUBY)
def c
b = calculation
[b]#{trailing_whitespace}
end # because b
RUBY
end
it 'registers an offense with trailing end on method with block' do
expect_offense(<<~RUBY)
def d
block do
foo
end end
^^^ Place the end statement of a multi-line method on its own line.
RUBY
expect_correction(<<~RUBY)
def d
block do
foo
end#{trailing_whitespace}
end
RUBY
end
it 'registers an offense with trailing end inside class' do
expect_offense(<<~RUBY)
class Foo
def some_method
foo; end
^^^ Place the end statement of a multi-line method on its own line.
end
RUBY
expect_correction(<<~RUBY)
class Foo
def some_method
foo;#{trailing_whitespace}
end
end
RUBY
end
it 'does not register on single line no op' do
expect_no_offenses(<<~RUBY)
def no_op; end
RUBY
end
it 'does not register on single line method' do
expect_no_offenses(<<~RUBY)
def something; do_stuff; end
RUBY
end
it 'autocorrects all trailing ends for larger example' do
expect_offense(<<~RUBY)
class Foo
def some_method
[] end
^^^ Place the end statement of a multi-line method on its own line.
def another_method
{} end
^^^ Place the end statement of a multi-line method on its own line.
end
RUBY
expect_correction(<<~RUBY)
class Foo
def some_method
[]#{trailing_whitespace}
end
def another_method
{}#{trailing_whitespace}
end
end
RUBY
end
context 'when Ruby 3.0 or higher', :ruby30 do
it 'does not register an offense when using endless method definition' do
expect_no_offenses(<<~RUBY)
def foo = bar
RUBY
end
it 'does not register an offense when endless method definition signature and body are ' \
'on different lines' do
expect_no_offenses(<<~RUBY)
def 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/super_arguments_spec.rb | spec/rubocop/cop/style/super_arguments_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SuperArguments, :config do
shared_examples 'offense' do |description, args, forwarded_args = args|
it "registers and corrects an offense when using def`#{description} (#{args}) => (#{forwarded_args})`" do
expect_offense(<<~RUBY, forwarded_args: forwarded_args)
def method(#{args})
super(#{forwarded_args})
^^^^^^^{forwarded_args}^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
expect_correction(<<~RUBY)
def method(#{args})
super
end
RUBY
end
it "registers and corrects an offense when using defs`#{description} (#{args}) => (#{forwarded_args})`" do
expect_offense(<<~RUBY, forwarded_args: forwarded_args)
def self.method(#{args})
super(#{forwarded_args})
^^^^^^^{forwarded_args}^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
expect_correction(<<~RUBY)
def self.method(#{args})
super
end
RUBY
end
end
shared_examples 'no offense' do |description, args, forwarded_args = args|
it "registers no offense when using def `#{description} (#{args}) => (#{forwarded_args})`" do
expect_no_offenses(<<~RUBY)
def method(#{args})
super(#{forwarded_args})
end
RUBY
end
it "registers no offense when using defs `#{description} (#{args}) => (#{forwarded_args})`" do
expect_no_offenses(<<~RUBY)
def self.method(#{args})
super(#{forwarded_args})
end
RUBY
end
end
it_behaves_like 'offense', 'no arguments', ''
it_behaves_like 'offense', 'single positional argument', 'a'
it_behaves_like 'offense', 'multiple positional arguments', 'a, b'
it_behaves_like 'offense', 'multiple positional arguments with default', 'a, b, c = 1', 'a, b, c'
it_behaves_like 'offense', 'positional/keyword argument', 'a, b:', 'a, b: b'
it_behaves_like 'offense', 'positional/keyword argument with default', 'a, b: 1', 'a, b: b'
it_behaves_like 'offense', 'positional/keyword argument both with default', 'a = 1, b: 2', 'a, b: b'
it_behaves_like 'offense', 'named block argument', '&blk'
it_behaves_like 'offense', 'positional splat arguments', '*args'
it_behaves_like 'offense', 'keyword splat arguments', '**kwargs'
it_behaves_like 'offense', 'positional/keyword splat arguments', '*args, **kwargs'
it_behaves_like 'offense', 'positional/keyword splat arguments with block', '*args, **kwargs, &blk'
it_behaves_like 'offense', 'keyword arguments mixed with forwarding', 'a:, **kwargs', 'a: a, **kwargs'
it_behaves_like 'offense', 'triple dot forwarding', '...'
it_behaves_like 'offense', 'triple dot forwarding with extra arg', 'a, ...'
it_behaves_like 'no offense', 'different amount of positional arguments', 'a, b', 'a'
it_behaves_like 'no offense', 'positional arguments in different order', 'a, b', 'b, a'
it_behaves_like 'no offense', 'keyword arguments in different order', 'a:, b:', 'b: b, a: a'
it_behaves_like 'no offense', 'positional/keyword argument mixing', 'a, b', 'a, b: b'
it_behaves_like 'no offense', 'positional/keyword argument mixing reversed', 'a, b:', 'a, b'
it_behaves_like 'no offense', 'block argument with different name', '&blk', '&other_blk'
it_behaves_like 'no offense', 'keyword arguments and hash', 'a:', '{ a: a }'
it_behaves_like 'no offense', 'keyword arguments with send node', 'a:, b:', 'a: a, b: c'
it_behaves_like 'no offense', 'triple dot forwarding with extra param', '...', 'a, ...'
it_behaves_like 'no offense', 'triple dot forwarding with different param', 'a, ...', 'b, ...'
it_behaves_like 'no offense', 'keyword forwarding with extra keyword', 'a, **kwargs', 'a: a, **kwargs'
context 'Ruby >= 3.1', :ruby31 do
it_behaves_like 'offense', 'hash value omission', 'a:'
it_behaves_like 'offense', 'anonymous block forwarding', '&'
end
context 'Ruby >= 3.2', :ruby32 do
it_behaves_like 'offense', 'anonymous positional forwarding', '*'
it_behaves_like 'offense', 'anonymous keyword forwarding', '**'
it_behaves_like 'no offense', 'mixed anonymous forwarding', '*, **', '*'
it_behaves_like 'no offense', 'mixed anonymous forwarding', '*, **', '**'
end
it 'registers no offense when explicitly passing no arguments' do
expect_no_offenses(<<~RUBY)
def foo(a)
super()
end
RUBY
end
it 'registers an offense when passing along no arguments' do
expect_offense(<<~RUBY)
def foo
super()
^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
end
it 'registers an offense for nested declarations' do
expect_offense(<<~RUBY)
def foo(a)
def bar(b:)
super(b: b)
^^^^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
super(a)
^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
end
it 'registers an offense when the hash argument is or-assigned' do
expect_offense(<<~RUBY)
def foo(options, &block)
options[:key] ||= default
super(options, &block)
^^^^^^^^^^^^^^^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
expect_correction(<<~RUBY)
def foo(options, &block)
options[:key] ||= default
super
end
RUBY
end
it 'registers no offense when calling super in a dsl method' do
expect_no_offenses(<<~RUBY)
describe 'example' do
subject { super() }
end
RUBY
end
context 'block argument' do
it 'does not register an offense for a block parameter that is not passed to super' do
expect_no_offenses(<<~RUBY)
def bar(a, b, &blk)
super(a, b)
end
RUBY
end
it 'does not register an offense for an anonymous block parameter that is not passed to super', :ruby31 do
expect_no_offenses(<<~RUBY)
def bar(a, b, &)
super(a, b)
end
RUBY
end
end
context 'when calling super with a block literal' do
it 'registers no offense when calling super with no arguments' do
expect_no_offenses(<<~RUBY)
def test
super { x }
end
RUBY
end
it 'registers no offense when calling super with implicit positional arguments' do
expect_no_offenses(<<~RUBY)
def test(a)
super { x }
end
RUBY
end
it 'registers an offense if the arguments match' do
expect_offense(<<~RUBY)
def test(a, b)
super(a, b) { x }
^^^^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
expect_correction(<<~RUBY)
def test(a, b)
super { x }
end
RUBY
end
it 'registers an offense when there is a non-forwarded block arg and positional arguments match' do
expect_offense(<<~RUBY)
def test(a, &blk)
super(a) { x }
^^^^^^^^ Call `super` without arguments and parentheses when all positional and keyword arguments are forwarded.
end
RUBY
expect_correction(<<~RUBY)
def test(a, &blk)
super { x }
end
RUBY
end
it 'does not register an offense if the arguments do not match' do
expect_no_offenses(<<~RUBY)
def test(a, b)
super(a) { x }
end
RUBY
end
context 'numblocks', :ruby27 do
it 'registers no offense when calling super with no arguments' do
expect_no_offenses(<<~RUBY)
def test
super { _1 }
end
RUBY
end
it 'registers no offense when calling super with implicit positional arguments' do
expect_no_offenses(<<~RUBY)
def test(a)
super { _1 }
end
RUBY
end
it 'registers an offense if the arguments match' do
expect_offense(<<~RUBY)
def test(a, b)
super(a, b) { _1 }
^^^^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
expect_correction(<<~RUBY)
def test(a, b)
super { _1 }
end
RUBY
end
it 'registers an offense when there is a non-forwarded block arg and positional arguments match' do
expect_offense(<<~RUBY)
def test(a, &blk)
super(a) { _1 }
^^^^^^^^ Call `super` without arguments and parentheses when all positional and keyword arguments are forwarded.
end
RUBY
expect_correction(<<~RUBY)
def test(a, &blk)
super { _1 }
end
RUBY
end
it 'does not register an offense if the arguments do not match' do
expect_no_offenses(<<~RUBY)
def test(a, b)
super(a) { _1 }
end
RUBY
end
end
end
context 'method call on super' do
it 'registers an offense for unneeded arguments' do
expect_offense(<<~RUBY)
def foo(a)
super(a).foo
^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
end
it 'registers an offense for unneeded arguments when the method has a block' do
expect_offense(<<~RUBY)
def foo(a)
super(a).foo { x }
^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
end
it 'registers an offense for unneeded arguments when the method has a numblock', :ruby27 do
expect_offense(<<~RUBY)
def foo(a)
super(a).foo { _1 }
^^^^^^^^ Call `super` without arguments and parentheses when the signature is identical.
end
RUBY
end
end
context 'scope changes' do
it 'registers no offense when the scope changes because of a class definition with block' do
expect_no_offenses(<<~RUBY)
def foo(a)
Class.new do
def foo(a, b)
super(a)
end
end
end
RUBY
end
end
it 'does not register offense when calling super in a block' do
expect_no_offenses(<<~RUBY)
def foo(a)
delegate_to_define_method do
super(a)
end
end
RUBY
end
it 'does not register an offense when calling super in a numblock' do
expect_no_offenses(<<~RUBY)
def foo(a)
delegate_to_define_method do
bar(_1)
super(a)
end
end
RUBY
end
it 'registers no offense when the scope changes because of sclass' do
expect_no_offenses(<<~RUBY)
def foo(a)
class << self
def foo(b)
super(a)
end
end
end
RUBY
end
it 'registers no offense when calling super in define_singleton_method' do
expect_no_offenses(<<~RUBY)
def test(a)
define_singleton_method(:test2) do |a|
super(a)
end
b.define_singleton_method(:test2) do |a|
super(a)
end
end
RUBY
end
context 'block reassignment' do
it 'registers no offense when the block argument is reassigned' do
expect_no_offenses(<<~RUBY)
def test(&blk)
blk = proc {}
super(&blk)
end
RUBY
end
it 'registers no offense when the block argument is reassigned in a nested block' do
expect_no_offenses(<<~RUBY)
def test(&blk)
if foo
blk = proc {} if bar
end
super(&blk)
end
RUBY
end
it 'registers no offense when the block argument is or-assigned' do
expect_no_offenses(<<~RUBY)
def test(&blk)
blk ||= proc {}
super(&blk)
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/unless_else_spec.rb | spec/rubocop/cop/style/unless_else_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::UnlessElse, :config do
context 'unless with else' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless x # negative 1
^^^^^^^^^^^^^^^^^^^^^ Do not use `unless` with `else`. Rewrite these with the positive case first.
a = 1 # negative 2
else # positive 1
a = 0 # positive 2
end
RUBY
expect_correction(<<~RUBY)
if x # positive 1
a = 0 # positive 2
else # negative 1
a = 1 # negative 2
end
RUBY
end
context 'and nested unless with else' do
it 'registers offenses for both but corrects only the outer unless/else' do
expect_offense(<<~RUBY)
unless abc
^^^^^^^^^^ Do not use `unless` with `else`. Rewrite these with the positive case first.
a
else
unless cde
^^^^^^^^^^ Do not use `unless` with `else`. Rewrite these with the positive case first.
b
else
c
end
end
RUBY
expect_correction(<<~RUBY)
if abc
unless cde
b
else
c
end
else
a
end
RUBY
end
end
end
context 'unless with nested if-else' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless(x)
^^^^^^^^^ Do not use `unless` with `else`. Rewrite these with the positive case first.
if(y == 0)
a = 0
elsif(z == 0)
a = 1
else
a = 2
end
else
a = 3
end
RUBY
expect_correction(<<~RUBY)
if(x)
a = 3
else
if(y == 0)
a = 0
elsif(z == 0)
a = 1
else
a = 2
end
end
RUBY
end
end
context 'when using `unless` with `then`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless x then
^^^^^^^^^^^^^ Do not use `unless` with `else`. Rewrite these with the positive case first.
a = 1
else
a = 0
end
RUBY
expect_correction(<<~RUBY)
if x then
a = 0
else
a = 1
end
RUBY
end
end
context 'unless without else' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
unless x
a = 1
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/encoding_spec.rb | spec/rubocop/cop/style/encoding_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Encoding, :config do
it 'does not register an offense when no encoding present' do
expect_no_offenses(<<~RUBY)
def foo() end
RUBY
end
it 'does not register an offense when encoding present but not UTF-8' do
expect_no_offenses(<<~RUBY)
# encoding: us-ascii
def foo() end
RUBY
end
it 'does not register an offense on a different magic comment type' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
def foo() end
RUBY
end
it 'registers an offense when encoding present and UTF-8' do
expect_offense(<<~RUBY)
# encoding: utf-8
^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
def foo() end
RUBY
expect_correction(<<~RUBY)
def foo() end
RUBY
end
it 'registers an offense when magic encoding with mixed case present' do
expect_offense(<<~RUBY)
# Encoding: UTF-8
^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
RUBY
expect_correction('')
end
it 'registers an offense when encoding present on 2nd line after shebang' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
def foo() end
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
def foo() end
RUBY
end
it 'registers an offense and corrects if there are multiple encoding magic comments' do
expect_offense(<<~RUBY)
# encoding: utf-8
^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
# coding: utf-8
^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
def foo() end
RUBY
expect_correction(<<~RUBY)
def foo() end
RUBY
end
it 'registers an offense and corrects the magic comment follows another magic comment' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
# encoding: utf-8
^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
def foo() end
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
def foo() end
RUBY
end
it 'does not register an offense when encoding is not at the top of the file' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
# encoding: utf-8
def foo() end
RUBY
end
it 'does not register an offense when encoding is in the wrong place' do
expect_no_offenses(<<~RUBY)
def foo() end
# encoding: utf-8
RUBY
end
context 'vim comments' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
# vim:filetype=ruby, fileencoding=utf-8
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
def foo() end
RUBY
expect_correction(<<~RUBY)
# vim: filetype=ruby
def foo() end
RUBY
end
end
context 'emacs comment' do
it 'registers an offense for encoding' do
expect_offense(<<~RUBY)
# -*- encoding : utf-8 -*-
^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
def foo() 'ä' end
RUBY
expect_correction(<<~RUBY)
def foo() 'ä' end
RUBY
end
it 'only removes encoding if there are other editor comments' do
expect_offense(<<~RUBY)
# -*- encoding : utf-8; mode: enh-ruby -*-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary utf-8 encoding comment.
def foo() 'ä' end
RUBY
expect_correction(<<~RUBY)
# -*- mode: enh-ruby -*-
def foo() 'ä' 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/perl_backrefs_spec.rb | spec/rubocop/cop/style/perl_backrefs_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::PerlBackrefs, :config do
it 'autocorrects puts $1 to puts Regexp.last_match(1)' do
expect_offense(<<~RUBY)
puts $1
^^ Prefer `Regexp.last_match(1)` over `$1`.
RUBY
expect_correction(<<~RUBY)
puts Regexp.last_match(1)
RUBY
end
it 'autocorrects $9 to Regexp.last_match(9)' do
expect_offense(<<~RUBY)
$9
^^ Prefer `Regexp.last_match(9)` over `$9`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match(9)
RUBY
end
it 'autocorrects $& to Regexp.last_match(0)' do
expect_offense(<<~RUBY)
$&
^^ Prefer `Regexp.last_match(0)` over `$&`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match(0)
RUBY
end
it 'autocorrects $` to Regexp.last_match.pre_match' do
expect_offense(<<~RUBY)
$`
^^ Prefer `Regexp.last_match.pre_match` over `$``.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match.pre_match
RUBY
end
it 'autocorrects $\' to Regexp.last_match.post_match' do
expect_offense(<<~RUBY)
$'
^^ Prefer `Regexp.last_match.post_match` over `$'`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match.post_match
RUBY
end
it 'autocorrects $+ to Regexp.last_match(-1)' do
expect_offense(<<~RUBY)
$+
^^ Prefer `Regexp.last_match(-1)` over `$+`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match(-1)
RUBY
end
it 'autocorrects $MATCH to Regexp.last_match(0)' do
expect_offense(<<~RUBY)
$MATCH
^^^^^^ Prefer `Regexp.last_match(0)` over `$MATCH`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match(0)
RUBY
end
it 'autocorrects $PREMATCH to Regexp.last_match.pre_match' do
expect_offense(<<~RUBY)
$PREMATCH
^^^^^^^^^ Prefer `Regexp.last_match.pre_match` over `$PREMATCH`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match.pre_match
RUBY
end
it 'autocorrects $POSTMATCH to Regexp.last_match.post_match' do
expect_offense(<<~RUBY)
$POSTMATCH
^^^^^^^^^^ Prefer `Regexp.last_match.post_match` over `$POSTMATCH`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match.post_match
RUBY
end
it 'autocorrects $LAST_PAREN_MATCH to Regexp.last_match(-1)' do
expect_offense(<<~RUBY)
$LAST_PAREN_MATCH
^^^^^^^^^^^^^^^^^ Prefer `Regexp.last_match(-1)` over `$LAST_PAREN_MATCH`.
RUBY
expect_correction(<<~RUBY)
Regexp.last_match(-1)
RUBY
end
it 'autocorrects "#$1" to "#{Regexp.last_match(1)}"' do
expect_offense(<<~'RUBY')
"#$1"
^^ Prefer `Regexp.last_match(1)` over `$1`.
RUBY
expect_correction(<<~'RUBY')
"#{Regexp.last_match(1)}"
RUBY
end
it 'autocorrects `#$1` to `#{Regexp.last_match(1)}`' do
expect_offense(<<~'RUBY')
`#$1`
^^ Prefer `Regexp.last_match(1)` over `$1`.
RUBY
expect_correction(<<~'RUBY')
`#{Regexp.last_match(1)}`
RUBY
end
it 'autocorrects /#$1/ to /#{Regexp.last_match(1)}/' do
expect_offense(<<~'RUBY')
/#$1/
^^ Prefer `Regexp.last_match(1)` over `$1`.
RUBY
expect_correction(<<~'RUBY')
/#{Regexp.last_match(1)}/
RUBY
end
it 'autocorrects $1 to ::Regexp.last_match(1) in namespace' do
expect_offense(<<~RUBY)
module Foo
class Regexp
end
puts $1
^^ Prefer `::Regexp.last_match(1)` over `$1`.
end
RUBY
expect_correction(<<~RUBY)
module Foo
class Regexp
end
puts ::Regexp.last_match(1)
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/unpack_first_spec.rb | spec/rubocop/cop/style/unpack_first_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::UnpackFirst, :config do
context 'ruby version >= 2.4', :ruby24 do
context 'registers an offense' do
it 'when using `#unpack` with `#first`' do
expect_offense(<<~RUBY)
x.unpack('h*').first
^^^^^^^^^^^^^^^^^^ Use `unpack1('h*')` instead of `unpack('h*').first`.
RUBY
expect_correction(<<~RUBY)
x.unpack1('h*')
RUBY
end
it 'when using `&.unpack` with `.first`' do
expect_offense(<<~RUBY)
x&.unpack('h*').first
^^^^^^^^^^^^^^^^^^ Use `unpack1('h*')` instead of `unpack('h*').first`.
RUBY
expect_correction(<<~RUBY)
x&.unpack1('h*')
RUBY
end
it 'when using `&.unpack` with `&.first`' do
expect_offense(<<~RUBY)
x&.unpack('h*')&.first
^^^^^^^^^^^^^^^^^^^ Use `unpack1('h*')` instead of `unpack('h*')&.first`.
RUBY
expect_correction(<<~RUBY)
x&.unpack1('h*')
RUBY
end
it 'when using `#unpack` with square brackets' do
expect_offense(<<~RUBY)
''.unpack(y)[0]
^^^^^^^^^^^^ Use `unpack1(y)` instead of `unpack(y)[0]`.
RUBY
expect_correction(<<~RUBY)
''.unpack1(y)
RUBY
end
it 'when using `#unpack` with dot and square brackets' do
expect_offense(<<~RUBY)
''.unpack(y).[](0)
^^^^^^^^^^^^^^^ Use `unpack1(y)` instead of `unpack(y).[](0)`.
RUBY
expect_correction(<<~RUBY)
''.unpack1(y)
RUBY
end
it 'when using `#unpack` with `#slice`' do
expect_offense(<<~RUBY)
''.unpack(y).slice(0)
^^^^^^^^^^^^^^^^^^ Use `unpack1(y)` instead of `unpack(y).slice(0)`.
RUBY
expect_correction(<<~RUBY)
''.unpack1(y)
RUBY
end
it 'when using `&.unpack` with `.slice`' do
expect_offense(<<~RUBY)
''&.unpack(y).slice(0)
^^^^^^^^^^^^^^^^^^ Use `unpack1(y)` instead of `unpack(y).slice(0)`.
RUBY
expect_correction(<<~RUBY)
''&.unpack1(y)
RUBY
end
it 'when using `&.unpack` with `&.slice`' do
expect_offense(<<~RUBY)
''&.unpack(y)&.slice(0)
^^^^^^^^^^^^^^^^^^^ Use `unpack1(y)` instead of `unpack(y)&.slice(0)`.
RUBY
expect_correction(<<~RUBY)
''&.unpack1(y)
RUBY
end
it 'when using `#unpack` with `#at`' do
expect_offense(<<~RUBY)
''.unpack(y).at(0)
^^^^^^^^^^^^^^^ Use `unpack1(y)` instead of `unpack(y).at(0)`.
RUBY
expect_correction(<<~RUBY)
''.unpack1(y)
RUBY
end
end
context 'does not register offense' do
it 'when using `#unpack1`' do
expect_no_offenses(<<~RUBY)
x.unpack1(y)
RUBY
end
it 'when using `#unpack` accessing second element' do
expect_no_offenses(<<~RUBY)
''.unpack('h*')[1]
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_double_splat_hash_braces_spec.rb | spec/rubocop/cop/style/redundant_double_splat_hash_braces_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantDoubleSplatHashBraces, :config do
it 'registers an offense when using double splat hash braces' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux})
^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux)
RUBY
end
it 'registers an offense when using nested double splat hash braces' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, **{baz: qux}})
^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux)
RUBY
end
it 'registers an offense when using double splat in double splat hash braces' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, **options})
^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, **options)
RUBY
end
it 'registers an offense when using double splat hash braces with `merge` method call' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux}.merge(options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux, **options)
RUBY
end
it 'registers an offense when using double splat hash braces with `merge!` method call' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux}.merge!(options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux, **options)
RUBY
end
it 'registers an offense when using double splat hash braces with `merge` pair arguments method call' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux}.merge(x: y))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux, x: y)
RUBY
end
it 'registers an offense when using double splat hash braces with `merge` safe navigation method call' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux}&.merge(options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux, **options)
RUBY
end
it 'registers an offense when using double splat hash braces with `merge` method call twice' do
expect_offense(<<~RUBY)
do_something(**{ foo: bar }.merge(options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
do_something(**{ baz: qux }.merge(options))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, **options)
do_something(baz: qux, **options)
RUBY
end
it 'registers an offense when using double splat hash braces with `merge` multiple arguments method call' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux}.merge(options1, options2))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux, **options1, **options2)
RUBY
end
it 'registers an offense when using double splat hash braces with `merge` method chain' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux}.merge(options1, options2).merge(options3))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux, **options1, **options2, **options3)
RUBY
end
it 'registers an offense when using double splat hash braces with complex `merge` method chain' do
expect_offense(<<~RUBY)
do_something(**{foo: bar, baz: qux}.merge(options1, options2)&.merge!(options3))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
RUBY
expect_correction(<<~RUBY)
do_something(foo: bar, baz: qux, **options1, **options2, **options3)
RUBY
end
it 'registers an offense when using double splat hash braces inside block' do
expect_offense(<<~RUBY)
block do
do_something(**{foo: bar, baz: qux})
^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant double splat and braces, use keyword arguments directly.
end
RUBY
expect_correction(<<~RUBY)
block do
do_something(foo: bar, baz: qux)
end
RUBY
end
it 'does not register an offense when using keyword arguments' do
expect_no_offenses(<<~RUBY)
do_something(foo: bar, baz: qux)
RUBY
end
it 'does not register an offense when using no hash brace' do
expect_no_offenses(<<~RUBY)
do_something(**options.merge(foo: bar, baz: qux))
RUBY
end
it 'does not register an offense when method call for no hash braced double splat receiver' do
expect_no_offenses(<<~RUBY)
do_something(**options.merge({foo: bar}))
RUBY
end
it 'does not register an offense when safe navigation method call for no hash braced double splat receiver' do
expect_no_offenses(<<~RUBY)
do_something(**options&.merge({foo: bar}))
RUBY
end
it 'does not register an offense when method call for parenthesized no hash double double splat' do
expect_no_offenses(<<~RUBY)
do_something(**(options.merge(foo: bar)))
RUBY
end
it 'does not register an offense when using empty double splat hash braces arguments' do
expect_no_offenses(<<~RUBY)
do_something(**{})
RUBY
end
it 'does not register an offense when using empty hash braces arguments' do
expect_no_offenses(<<~RUBY)
do_something({})
RUBY
end
it 'does not register an offense when using hash rocket double splat hash braces arguments' do
expect_no_offenses(<<~RUBY)
do_something(**{foo => bar})
RUBY
end
it 'does not register an offense when using method call that is not `merge` for double splat hash braces arguments' do
expect_no_offenses(<<~RUBY)
do_something(**{foo: bar}.invert)
RUBY
end
it 'does not register an offense when using double splat hash braces with `merge` and method chain' do
expect_no_offenses(<<~RUBY)
do_something(**{foo: bar, baz: qux}.merge(options).compact_blank)
RUBY
end
it 'does not register an offense when using hash braces arguments' do
expect_no_offenses(<<~RUBY)
do_something({foo: bar, baz: qux})
RUBY
end
it 'does not register an offense when using double splat variable' do
expect_no_offenses(<<~RUBY)
do_something(**h)
RUBY
end
it 'does not register an offense when using hash literal' do
expect_no_offenses(<<~RUBY)
{ a: a }
RUBY
end
it 'does not register an offense when using double splat within block argument containing a hash literal in an array literal' do
expect_no_offenses(<<~RUBY)
do_something(**x.do_something { [foo: bar] })
RUBY
end
it 'does not register an offense when using double splat within block argument containing a nested hash literal' do
expect_no_offenses(<<~RUBY)
do_something(**x.do_something { {foo: {bar: baz}} })
RUBY
end
it 'does not register an offense when using double splat within numbered block argument containing a nested hash literal' do
expect_no_offenses(<<~RUBY)
do_something(**x.do_something { {foo: {bar: _1}} })
RUBY
end
it 'does not register an offense when using double splat with a hash literal enclosed in parenthesized ternary operator' do
expect_no_offenses(<<~RUBY)
do_something(**(foo ? {bar: bar} : baz))
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_heredoc_delimiter_quotes_spec.rb | spec/rubocop/cop/style/redundant_heredoc_delimiter_quotes_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantHeredocDelimiterQuotes, :config do
it 'registers an offense when using the redundant heredoc delimiter single quotes with `<<~`' do
expect_offense(<<~RUBY)
do_something(<<~'EOS')
^^^^^^^^ Remove the redundant heredoc delimiter quotes, use `<<~EOS` instead.
no string interpolation style text
EOS
RUBY
expect_correction(<<~RUBY)
do_something(<<~EOS)
no string interpolation style text
EOS
RUBY
end
it 'registers an offense when using the redundant heredoc delimiter single quotes with `<<-`' do
expect_offense(<<~RUBY)
do_something(<<-'EOS')
^^^^^^^^ Remove the redundant heredoc delimiter quotes, use `<<-EOS` instead.
no string interpolation style text
EOS
RUBY
expect_correction(<<~RUBY)
do_something(<<-EOS)
no string interpolation style text
EOS
RUBY
end
it 'registers an offense when using the redundant heredoc delimiter single quotes with `<<`' do
expect_offense(<<~RUBY)
do_something(<<'EOS')
^^^^^^^ Remove the redundant heredoc delimiter quotes, use `<<EOS` instead.
no string interpolation style text
EOS
RUBY
expect_correction(<<~RUBY)
do_something(<<EOS)
no string interpolation style text
EOS
RUBY
end
it 'registers an offense when using the redundant heredoc delimiter double quotes' do
expect_offense(<<~RUBY)
do_something(<<~"EOS")
^^^^^^^^ Remove the redundant heredoc delimiter quotes, use `<<~EOS` instead.
no string interpolation style text
EOS
RUBY
expect_correction(<<~RUBY)
do_something(<<~EOS)
no string interpolation style text
EOS
RUBY
end
it 'does not register an offense when using the redundant heredoc delimiter backquotes' do
expect_no_offenses(<<~RUBY)
do_something(<<~`EOS`)
command
EOS
RUBY
end
it 'does not register an offense when not using the redundant heredoc delimiter quotes' do
expect_no_offenses(<<~RUBY)
do_something(<<~EOS)
no string interpolation style text
EOS
RUBY
end
it 'does not register an offense when using the quoted heredoc with string interpolation style text' do
expect_no_offenses(<<~'RUBY')
do_something(<<~'EOS')
#{string} #{interpolation}
EOS
RUBY
end
it 'does not register an offense when using the quoted heredoc with multiline string interpolation style text' do
expect_no_offenses(<<~'RUBY')
do_something(<<~'EOS')
#{
string
} #{
interpolation
}
EOS
RUBY
end
it 'does not register an offense when using the quoted heredoc with instance variable string interpolation' do
expect_no_offenses(<<~'RUBY')
do_something(<<~'EOS')
#@foo
EOS
RUBY
end
it 'does not register an offense when using the quoted heredoc with class variable string interpolation' do
expect_no_offenses(<<~'RUBY')
do_something(<<~'EOS')
#@@foo
EOS
RUBY
end
it 'does not register an offense when using the quoted heredoc with global variable string interpolation' do
expect_no_offenses(<<~'RUBY')
do_something(<<~'EOS')
#$foo
EOS
RUBY
end
it 'does not register an offense when using the heredoc delimiter with double quote' do
expect_no_offenses(<<~RUBY)
do_something(<<~'EDGE"CASE')
no string interpolation style text
EDGE"CASE
RUBY
end
it 'does not register an offense when using the heredoc delimiter with single quote' do
expect_no_offenses(<<~RUBY)
do_something(<<~"EDGE'CASE")
no string interpolation style text
EDGE'CASE
RUBY
end
it 'does not register an offense when using the heredoc delimiter with space' do
expect_no_offenses(<<~RUBY)
do_something(<<~'EDGE CASE')
no string interpolation style text
EDGE CASE
RUBY
end
it 'does not register an offense when using the heredoc delimiter with multibyte space' do
expect_no_offenses(<<~RUBY)
do_something(<<~'EDGE CASE')
no string interpolation style text
EDGE CASE
RUBY
end
it 'does not register an offense when using the heredoc delimiter with backslash' do
expect_no_offenses(<<~'RUBY')
do_something(<<~'EOS')
Preserve \
newlines
EOS
RUBY
end
# FIXME: `<<''` is a syntax error in Ruby. This test was added because Parser gem can parse it,
# but this will be removed after https://github.com/whitequark/parser/issues/996 is resolved.
it 'does not register an offense when using the blank heredoc delimiter', unsupported_on: :prism do
expect_no_offenses(<<~RUBY)
<<''
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/collection_compact_spec.rb | spec/rubocop/cop/style/collection_compact_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CollectionCompact, :config, :ruby24 do
it 'registers an offense and corrects when using `reject` on array to reject nils' do
expect_offense(<<~RUBY)
array.reject { |e| e.nil? }
^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |e| e.nil? }`.
array.reject! { |e| e.nil? }
^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `reject! { |e| e.nil? }`.
RUBY
expect_correction(<<~RUBY)
array.compact
array.compact!
RUBY
end
it 'registers an offense and corrects when using safe navigation `reject` call on array to reject nils' do
expect_offense(<<~RUBY)
array&.reject { |e| e&.nil? }
^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |e| e&.nil? }`.
array&.reject! { |e| e&.nil? }
^^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `reject! { |e| e&.nil? }`.
RUBY
expect_correction(<<~RUBY)
array&.compact
array&.compact!
RUBY
end
it 'registers an offense and corrects when using `reject` with block pass arg on array to reject nils' do
expect_offense(<<~RUBY)
array.reject(&:nil?)
^^^^^^^^^^^^^^ Use `compact` instead of `reject(&:nil?)`.
array.reject!(&:nil?)
^^^^^^^^^^^^^^^ Use `compact!` instead of `reject!(&:nil?)`.
RUBY
expect_correction(<<~RUBY)
array.compact
array.compact!
RUBY
end
it 'registers an offense and corrects when using safe navigation `reject` call with block pass arg on array to reject nils' do
expect_offense(<<~RUBY)
array&.reject(&:nil?)
^^^^^^^^^^^^^^ Use `compact` instead of `reject(&:nil?)`.
array&.reject!(&:nil?)
^^^^^^^^^^^^^^^ Use `compact!` instead of `reject!(&:nil?)`.
RUBY
expect_correction(<<~RUBY)
array&.compact
array&.compact!
RUBY
end
it 'registers an offense and corrects when using `reject` with block pass arg and no parentheses' do
expect_offense(<<~RUBY)
array.reject &:nil?
^^^^^^^^^^^^^ Use `compact` instead of `reject &:nil?`.
RUBY
expect_correction(<<~RUBY)
array.compact
RUBY
end
it 'registers an offense and corrects when using `reject` on hash to reject nils' do
expect_offense(<<~RUBY)
hash.reject { |k, v| v.nil? }
^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |k, v| v.nil? }`.
hash.reject! { |k, v| v.nil? }
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `reject! { |k, v| v.nil? }`.
RUBY
expect_correction(<<~RUBY)
hash.compact
hash.compact!
RUBY
end
it 'registers an offense and corrects when using `select/select!` to reject nils' do
expect_offense(<<~RUBY)
array.select { |e| !e.nil? }
^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `select { |e| !e.nil? }`.
hash.select! { |k, v| !v.nil? }
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `select! { |k, v| !v.nil? }`.
RUBY
expect_correction(<<~RUBY)
array.compact
hash.compact!
RUBY
end
it 'registers an offense and corrects when using safe navigation `select/select!` call to reject nils' do
expect_offense(<<~RUBY)
array&.select { |e| e&.nil?&.! }
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `select { |e| e&.nil?&.! }`.
hash&.select! { |k, v| v&.nil?&.! }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `select! { |k, v| v&.nil?&.! }`.
RUBY
expect_correction(<<~RUBY)
array&.compact
hash&.compact!
RUBY
end
it 'registers an offense and corrects when using `reject` and receiver is a variable' do
expect_offense(<<~RUBY)
def foo(params)
params.reject { |_k, v| v.nil? }
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |_k, v| v.nil? }`.
end
RUBY
expect_correction(<<~RUBY)
def foo(params)
params.compact
end
RUBY
end
it 'registers an offense and corrects when using `grep_v(nil)`' do
expect_offense(<<~RUBY)
array.grep_v(nil)
^^^^^^^^^^^ Use `compact` instead of `grep_v(nil)`.
RUBY
expect_correction(<<~RUBY)
array.compact
RUBY
end
it 'registers an offense and corrects when using `grep_v(NilClass)`' do
expect_offense(<<~RUBY)
array.grep_v(NilClass)
^^^^^^^^^^^^^^^^ Use `compact` instead of `grep_v(NilClass)`.
RUBY
expect_correction(<<~RUBY)
array.compact
RUBY
end
it 'registers an offense and corrects when using `grep_v(::NilClass)`' do
expect_offense(<<~RUBY)
array.grep_v(::NilClass)
^^^^^^^^^^^^^^^^^^ Use `compact` instead of `grep_v(::NilClass)`.
RUBY
expect_correction(<<~RUBY)
array.compact
RUBY
end
it 'does not register an offense when using `grep_v(pattern)`' do
expect_no_offenses(<<~RUBY)
array.grep_v(pattern)
RUBY
end
it 'does not register an offense when using `reject` to not to rejecting nils' do
expect_no_offenses(<<~RUBY)
array.reject { |e| e.odd? }
RUBY
end
it 'does not register an offense when using `compact/compact!`' do
expect_no_offenses(<<~RUBY)
array.compact
array.compact!
RUBY
end
# NOTE: Unlike `reject` or `compact` which return a new collection object,
# `delete_if` always returns its own object `self` making them incompatible.
# Additionally, `compact!` returns `nil` if no changes are made.
it 'does not register an offense when using `delete_if`' do
expect_no_offenses(<<~RUBY)
array.delete_if(&:nil?)
array.delete_if { |e| e.nil? }
RUBY
end
context 'when without receiver' do
it 'does not register an offense when using `reject` on array to reject nils' do
expect_no_offenses(<<~RUBY)
reject { |e| e.nil? }
reject! { |e| e.nil? }
RUBY
end
it 'does not register an offense when using `select/select!` to reject nils' do
expect_no_offenses(<<~RUBY)
select { |e| !e.nil? }
select! { |k, v| !v.nil? }
RUBY
end
end
context 'Ruby >= 3.1', :ruby31 do
it 'registers an offense and corrects when using `to_enum.reject` on array to reject nils' do
expect_offense(<<~RUBY)
array.to_enum.reject { |e| e.nil? }
^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |e| e.nil? }`.
array.to_enum.reject! { |e| e.nil? }
^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `reject! { |e| e.nil? }`.
RUBY
expect_correction(<<~RUBY)
array.to_enum.compact
array.to_enum.compact!
RUBY
end
it 'registers an offense and corrects when using `lazy.reject` on array to reject nils' do
expect_offense(<<~RUBY)
array.lazy.reject { |e| e.nil? }
^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |e| e.nil? }`.
array.lazy.reject! { |e| e.nil? }
^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `reject! { |e| e.nil? }`.
RUBY
expect_correction(<<~RUBY)
array.lazy.compact
array.lazy.compact!
RUBY
end
end
context 'Ruby <= 3.0', :ruby30, unsupported_on: :prism do
it 'does not register an offense when using `to_enum.reject` on array to reject nils' do
expect_no_offenses(<<~RUBY)
array.to_enum.reject { |e| e.nil? }
array.to_enum.reject! { |e| e.nil? }
RUBY
end
it 'does not register an offense when using `lazy.reject` on array to reject nils' do
expect_no_offenses(<<~RUBY)
array.lazy.reject { |e| e.nil? }
array.lazy.reject! { |e| e.nil? }
RUBY
end
end
context 'Ruby >= 2.6', :ruby26, unsupported_on: :prism do
it 'registers an offense and corrects when using `filter/filter!` to reject nils' do
expect_offense(<<~RUBY)
array.filter { |e| !e.nil? }
^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `filter { |e| !e.nil? }`.
hash.filter! { |k, v| !v.nil? }
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `filter! { |k, v| !v.nil? }`.
RUBY
expect_correction(<<~RUBY)
array.compact
hash.compact!
RUBY
end
it 'registers an offense and corrects when using safe navigation `filter/filter!` call to reject nils' do
expect_offense(<<~RUBY)
array&.filter { |e| e&.nil?&.! }
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `filter { |e| e&.nil?&.! }`.
hash&.filter! { |k, v| v&.nil?&.! }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact!` instead of `filter! { |k, v| v&.nil?&.! }`.
RUBY
expect_correction(<<~RUBY)
array&.compact
hash&.compact!
RUBY
end
it 'does not register an offense when using `filter/filter!` to reject nils without a receiver' do
expect_no_offenses(<<~RUBY)
filter { |e| !e.nil? }
filter! { |k, v| !v.nil? }
RUBY
end
end
context 'Ruby <= 2.5', :ruby25, unsupported_on: :prism do
it 'does not register an offense when using `filter/filter!`' do
expect_no_offenses(<<~RUBY)
array.filter { |e| !e.nil? }
hash.filter! { |k, v| !v.nil? }
RUBY
end
end
context 'when Ruby <= 2.3', :ruby23, unsupported_on: :prism do
it 'does not register an offense when using `reject` on hash to reject nils' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| v.nil? }
hash.reject! { |k, v| v.nil? }
RUBY
end
end
context "when `AllowedReceivers: ['params']`" do
let(:cop_config) { { 'AllowedReceivers' => ['params'] } }
it 'does not register an offense when receiver is `params` method' do
expect_no_offenses(<<~RUBY)
params.reject { |param| param.nil? }
RUBY
end
it 'does not register an offense when method chained receiver is `params` method' do
expect_no_offenses(<<~RUBY)
params.merge(key: value).reject { |_k, v| v.nil? }
RUBY
end
it 'registers an offense when receiver is not allowed name' do
expect_offense(<<~RUBY)
foo.reject { |param| param.nil? }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |param| param.nil? }`.
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_percent_q_spec.rb | spec/rubocop/cop/style/redundant_percent_q_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantPercentQ, :config do
context 'with %q strings' do
it 'registers an offense for only single quotes' do
expect_offense(<<~RUBY)
%q('hi')
^^^^^^^^ Use `%q` only for strings that contain both single quotes and double quotes.
RUBY
expect_correction(<<~RUBY)
"'hi'"
RUBY
end
it 'registers an offense for only double quotes' do
expect_offense(<<~RUBY)
%q("hi")
^^^^^^^^ Use `%q` only for strings that contain both single quotes and double quotes.
RUBY
expect_correction(<<~RUBY)
'"hi"'
RUBY
end
it 'registers an offense for no quotes' do
expect_offense(<<~RUBY)
%q(hi)
^^^^^^ Use `%q` only for strings that contain both single quotes and double quotes.
RUBY
expect_correction(<<~RUBY)
'hi'
RUBY
end
it 'accepts a string with single quotes and double quotes' do
expect_no_offenses("%q('\"hi\"')")
end
it 'registers an offense for a string containing escaped backslashes' do
expect_offense(<<~'RUBY')
%q(\\\\foo\\\\)
^^^^^^^^^^^^^^^ Use `%q` only for strings that contain both single quotes and double quotes.
RUBY
expect_correction(<<~'RUBY')
'\\\\foo\\\\'
RUBY
end
it 'accepts a string with escaped non-backslash characters' do
expect_no_offenses("%q(\\'foo\\')")
end
it 'accepts a string with escaped backslash and non-backslash characters' do
expect_no_offenses("%q(\\\\ \\'foo\\' \\\\)")
end
it 'accepts regular expressions starting with %q' do
expect_no_offenses('/%q?/')
end
it 'autocorrects for strings that are concatenated with backslash' do
expect_offense(<<~'RUBY')
%q(foo bar baz) \
^^^^^^^^^^^^^^^ Use `%q` only for strings that contain both single quotes and double quotes.
'boogers'
RUBY
expect_correction(<<~'RUBY')
'foo bar baz' \
'boogers'
RUBY
end
end
context 'with %Q strings' do
it 'registers an offense for static string without quotes' do
expect_offense(<<~RUBY)
%Q(hi)
^^^^^^ Use `%Q` only for strings that contain both single quotes and double quotes, or for dynamic strings that contain double quotes.
RUBY
expect_correction(<<~RUBY)
"hi"
RUBY
end
it 'registers an offense for static string with only double quotes' do
expect_offense(<<~RUBY)
%Q("hi")
^^^^^^^^ Use `%Q` only for strings that contain both single quotes and double quotes, or for dynamic strings that contain double quotes.
RUBY
expect_correction(<<~RUBY)
'"hi"'
RUBY
end
it 'registers an offense for dynamic string without quotes' do
expect_offense(<<~'RUBY')
%Q(hi#{4})
^^^^^^^^^^ Use `%Q` only for strings that contain both single quotes and double quotes, or for dynamic strings that contain double quotes.
RUBY
expect_correction(<<~'RUBY')
"hi#{4}"
RUBY
end
it 'accepts a string with single quotes and double quotes' do
expect_no_offenses("%Q('\"hi\"')")
end
it 'accepts a string with double quotes and an escaped special character' do
expect_no_offenses('%Q("\\thi")')
end
it 'accepts a string with double quotes and an escaped normal character' do
expect_no_offenses('%Q("\\!thi")')
end
it 'accepts a dynamic %Q string with double quotes' do
expect_no_offenses("%Q(\"hi\#{4}\")")
end
it 'accepts regular expressions starting with %Q' do
expect_no_offenses('/%Q?/')
end
it 'autocorrects for strings that are concatenated with backslash' do
expect_offense(<<~'RUBY')
%Q(foo bar baz) \
^^^^^^^^^^^^^^^ Use `%Q` only for strings that contain both single [...]
'boogers'
RUBY
expect_correction(<<~'RUBY')
"foo bar baz" \
'boogers'
RUBY
end
it 'autocorrects safely for multiline strings containing double quotes' do
expect_offense(<<~RUBY)
%Q(
^^^ Use `%Q` only for strings that contain both single [...]
Quoth the Raven "Nevermore."
)
RUBY
expect_correction(<<~RUBY)
'
Quoth the Raven "Nevermore."
'
RUBY
end
end
it 'accepts a heredoc string that contains %q' do
expect_no_offenses(<<~RUBY)
s = <<CODE
%q('hi') # line 1
%q("hi")
CODE
RUBY
end
it 'accepts %q at the beginning of a double quoted string with interpolation' do
expect_no_offenses("\"%q(a)\#{b}\"")
end
it 'accepts %Q at the beginning of a double quoted string with interpolation' do
expect_no_offenses("\"%Q(a)\#{b}\"")
end
it 'accepts %q at the beginning of a section of a double quoted string with interpolation' do
expect_no_offenses(%("%\#{b}%q(a)"))
end
it 'accepts %Q at the beginning of a section of a double quoted string with interpolation' do
expect_no_offenses(%("%\#{b}%Q(a)"))
end
it 'accepts %q containing string interpolation' do
expect_no_offenses("%q(foo \#{'bar'} baz)")
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_spec.rb | spec/rubocop/cop/style/redundant_self_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantSelf, :config do
it 'reports an offense a self receiver on an rvalue' do
expect_offense(<<~RUBY)
a = self.b
^^^^ Redundant `self` detected.
RUBY
expect_correction(<<~RUBY)
a = b
RUBY
end
it 'does not report an offense when receiver and lvalue have the same name' do
expect_no_offenses('a = self.a')
end
it 'does not report an offense when receiver and lvalue have the same name in or-assignment' do
expect_no_offenses('foo ||= self.foo')
end
it 'does not report an offense when receiver and lvalue have the same name in and-assignment' do
expect_no_offenses('foo &&= self.foo')
end
it 'accepts when nested receiver and lvalue have the same name' do
expect_no_offenses('a = self.a || b || c')
end
it 'does not report an offense when receiver and multiple assigned lvalue have the same name' do
expect_no_offenses('a, b = self.a')
end
it 'does not report an offense when lvasgn name is used in `if`' do
expect_no_offenses('a = self.a if self.a')
end
it 'does not report an offense when masgn name is used in `if`' do
expect_no_offenses('a, b = self.a if self.a')
end
it 'does not report an offense when lvasgn name is used in nested `if`' do
expect_no_offenses(<<~RUBY)
if self.a
a = self.a
end if self.a
RUBY
end
it 'does not report an offense when masgn name is used in nested `if`' do
expect_no_offenses(<<~RUBY)
if self.a
a, b = self.a
end if self.a
RUBY
end
it 'does not report an offense when lvasgn name is used in `unless`' do
expect_no_offenses('a = self.a unless self.a')
end
it 'does not report an offense when masgn name is used in `unless`' do
expect_no_offenses('a, b = self.a unless self.a')
end
it 'does not report an offense when lvasgn name is used in `while`' do
expect_no_offenses('a = self.a while self.a')
end
it 'does not report an offense when masgn name is used in `while`' do
expect_no_offenses('a, b = self.a while self.a')
end
it 'does not report an offense when lvasgn name is used in `until`' do
expect_no_offenses('a = self.a until self.a')
end
it 'does not report an offense when masgn name is used in `until`' do
expect_no_offenses('a, b = self.a until self.a')
end
it 'does not report an offense when lvasgn name is nested below `if`' do
expect_no_offenses('a = self.a if foo(self.a)')
end
it 'reports an offense when a different lvasgn name is used in `if`' do
expect_offense(<<~RUBY)
a = x if self.b
^^^^ Redundant `self` detected.
RUBY
end
it 'reports an offense when a different masgn name is used in `if`' do
expect_offense(<<~RUBY)
a, b, c = x if self.d
^^^^ Redundant `self` detected.
RUBY
end
it 'does not report an offense when self receiver in a method argument and ' \
'lvalue have the same name' do
expect_no_offenses('a = do_something(self.a)')
end
it 'does not report an offense when self receiver in a method argument and ' \
'multiple assigned lvalue have the same name' do
expect_no_offenses('a, b = do_something(self.a)')
end
it 'accepts a self receiver on an lvalue of an assignment' do
expect_no_offenses('self.a = b')
end
it 'accepts a self receiver on an lvalue of a parallel assignment' do
expect_no_offenses('a, self.b = c, d')
end
it 'accepts a self receiver on an lvalue of an or-assignment' do
expect_no_offenses('self.logger ||= Rails.logger')
end
it 'accepts a self receiver on an lvalue of an and-assignment' do
expect_no_offenses('self.flag &&= value')
end
it 'accepts a self receiver on an lvalue of a plus-assignment' do
expect_no_offenses('self.sum += 10')
end
it 'accepts a self receiver with the square bracket operator' do
expect_no_offenses('self[a]')
end
it 'accepts a self receiver with the double less-than operator' do
expect_no_offenses('self << a')
end
it 'accepts a self receiver for methods named like ruby keywords' do
expect_no_offenses(<<~RUBY)
a = self.class
self.for(deps, [], true)
self.and(other)
self.or(other)
self.alias
self.begin
self.break
self.case
self.def
self.defined?
self.do
self.else
self.elsif
self.end
self.ensure
self.false
self.if
self.in
self.module
self.next
self.nil
self.not
self.redo
self.rescue
self.retry
self.return
self.self
self.super
self.then
self.true
self.undef
self.unless
self.until
self.when
self.while
self.yield
self.__FILE__
self.__LINE__
self.__ENCODING__
RUBY
end
it 'accepts a self receiver used to distinguish from argument of block' do
expect_no_offenses(<<~RUBY)
%w[draft preview moderation approved rejected].each do |state|
self.state == state
define_method "\#{state}?" do
self.state == state
end
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for self usage in numblocks' do
expect_offense(<<~RUBY)
%w[x y z].select do
self.axis == _1
^^^^ Redundant `self` detected.
end
RUBY
expect_correction(<<~RUBY)
%w[x y z].select do
axis == _1
end
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for self usage in itblocks' do
expect_offense(<<~RUBY)
%w[x y z].select do
self.axis == it
^^^^ Redundant `self` detected.
end
RUBY
expect_correction(<<~RUBY)
%w[x y z].select do
axis == it
end
RUBY
end
end
describe 'instance methods' do
it 'accepts a self receiver used to distinguish from blockarg' do
expect_no_offenses(<<~RUBY)
def requested_specs(&groups)
some_method(self.groups)
end
RUBY
end
it 'accepts a self receiver used to distinguish from argument' do
expect_no_offenses(<<~RUBY)
def requested_specs(groups)
some_method(self.groups)
end
RUBY
end
it 'accepts a self receiver used to distinguish from optional argument' do
expect_no_offenses(<<~RUBY)
def requested_specs(final = true)
something if self.final != final
end
RUBY
end
it 'accepts a self receiver used to distinguish from local variable' do
expect_no_offenses(<<~RUBY)
def requested_specs
@requested_specs ||= begin
groups = self.groups - Bundler.settings.without
groups.map! { |g| g.to_sym }
specs_for(groups)
end
end
RUBY
end
it 'accepts a self receiver used to distinguish from an argument' do
expect_no_offenses(<<~RUBY)
def foo(bar)
puts bar, self.bar
end
RUBY
end
it 'accepts a self receiver used to distinguish from an argument ' \
'when an inner method is defined' do
expect_no_offenses(<<~RUBY)
def foo(bar)
def inner_method(); end
puts bar, self.bar
end
RUBY
end
it 'accepts `kwnilarg` argument node type' do
expect_no_offenses(<<~RUBY)
def requested_specs(groups, **nil)
some_method(self.groups)
end
RUBY
end
end
describe 'class methods' do
it 'accepts a self receiver used to distinguish from blockarg' do
expect_no_offenses(<<~RUBY)
def self.requested_specs(&groups)
some_method(self.groups)
end
RUBY
end
it 'accepts a self receiver used to distinguish from argument' do
expect_no_offenses(<<~RUBY)
def self.requested_specs(groups)
some_method(self.groups)
end
RUBY
end
it 'accepts a self receiver used to distinguish from optional argument' do
expect_no_offenses(<<~RUBY)
def self.requested_specs(final = true)
something if self.final != final
end
RUBY
end
it 'accepts a self receiver used to distinguish from local variable' do
expect_no_offenses(<<~RUBY)
def self.requested_specs
@requested_specs ||= begin
groups = self.groups - Bundler.settings.without
groups.map! { |g| g.to_sym }
specs_for(groups)
end
end
RUBY
end
end
it 'accepts a self receiver used to distinguish from constant' do
expect_no_offenses('self.Foo')
end
it 'accepts a self receiver of .()' do
expect_no_offenses('self.()')
end
it 'reports an offense a self receiver of .call' do
expect_offense(<<~RUBY)
self.call
^^^^ Redundant `self` detected.
RUBY
expect_correction(<<~RUBY)
call
RUBY
end
it 'accepts a self receiver of methods also defined on `Kernel`' do
expect_no_offenses('self.open')
end
it 'accepts a self receiver on an lvalue of mlhs arguments' do
expect_no_offenses(<<~RUBY)
def do_something((a, b)) # This method expects Array that has 2 elements as argument.
self.a = a
self.b.some_method_call b
end
RUBY
end
it 'does not register an offense when using `self.it` in the single line block' do
# `Lint/ItWithoutArgumentsInBlock` respects for this syntax.
expect_no_offenses(<<~RUBY)
0.times { self.it }
RUBY
end
it 'does not register an offense when using `self.it` in the multiline block' do
# `Lint/ItWithoutArgumentsInBlock` respects for this syntax.
expect_no_offenses(<<~RUBY)
0.times do
self.it
it = 1
it
end
RUBY
end
it 'registers an offense when using `it` without arguments in `def` body' do
expect_offense(<<~RUBY)
def foo
self.it
^^^^ Redundant `self` detected.
end
RUBY
end
it 'registers an offense when using `it` without arguments in the block with empty block parameter' do
expect_offense(<<~RUBY)
0.times { ||
self.it
^^^^ Redundant `self` detected.
}
RUBY
end
it 'registers an offense when using `it` without arguments in the block with useless block parameter' do
expect_offense(<<~RUBY)
0.times { |_n|
self.it
^^^^ Redundant `self` detected.
}
RUBY
end
context 'with ruby >= 2.7', :ruby27 do
context 'with pattern matching' do
it 'accepts a self receiver on an `match-var`' do
expect_no_offenses(<<~RUBY)
case foo
in Integer => bar
self.bar + bar
end
RUBY
end
it 'accepts a self receiver on a `hash-pattern`' do
expect_no_offenses(<<~RUBY)
case pattern
in {x: foo}
self.foo + foo
end
RUBY
end
it 'accepts a self receiver on a `array-pattern`' do
expect_no_offenses(<<~RUBY)
case pattern
in [foo, bar]
self.foo + foo
end
RUBY
end
it 'accepts a self receiver with a `match-alt`' do
expect_no_offenses(<<~RUBY)
case pattern
in _foo | _bar
self._foo + self._bar + _foo + _bar
end
RUBY
end
it 'accepts a self receiver in a nested pattern`' do
expect_no_offenses(<<~RUBY)
case pattern
in { foo: [bar, baz] }
self.bar + self.baz
end
RUBY
end
it 'accepts a self receiver in a conditional pattern' do
expect_no_offenses(<<~RUBY)
case pattern
in a, b if b == a * 2
self.a + b
end
RUBY
end
it 'accepts a self receiver in a `if-guard`' do
expect_no_offenses(<<~RUBY)
case pattern
in a, b if b == self.a * 2
a + b
end
RUBY
end
it 'registers an offense when using a self receiver with a pin' do
expect_offense(<<~RUBY)
foo = 17
case pattern
in ^foo, *bar
self.foo + self.bar + foo + bar
^^^^ Redundant `self` detected.
end
RUBY
end
it 'registers an offense when using self with a different match var' do
expect_offense(<<~RUBY)
case foo
in Integer => bar
self.bar + bar
in Float => baz
self.bar + baz
^^^^ Redundant `self` detected.
end
RUBY
expect_correction(<<~RUBY)
case foo
in Integer => bar
self.bar + bar
in Float => baz
bar + baz
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/hash_transform_values_spec.rb | spec/rubocop/cop/style/hash_transform_values_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashTransformValues, :config do
context 'when using Ruby 2.4 or newer', :ruby24 do
context 'with inline block' do
it 'flags each_with_object when transform_values could be used' do
expect_offense(<<~RUBY)
x.each_with_object({}) {|(k, v), h| h[k] = foo(v)}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `each_with_object`.
RUBY
expect_correction(<<~RUBY)
x.transform_values {|v| foo(v)}
RUBY
end
end
context 'with multiline block' do
it 'flags each_with_object when transform_values could be used' do
expect_offense(<<~RUBY)
some_hash.each_with_object({}) do |(key, val), memo|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `each_with_object`.
memo[key] = val * val
end
RUBY
expect_correction(<<~RUBY)
some_hash.transform_values do |val|
val * val
end
RUBY
end
end
context 'with safe navigation operator' do
it 'flags each_with_object when transform_values could be used' do
expect_offense(<<~RUBY)
x&.each_with_object({}) {|(k, v), h| h[k] = foo(v)}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `each_with_object`.
RUBY
expect_correction(<<~RUBY)
x&.transform_values {|v| foo(v)}
RUBY
end
end
it 'does not flag each_with_object when both key & value are transformed' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) {|(k, v), h| h[k.to_sym] = foo(v)}
RUBY
end
it 'does not flag each_with_object when value transformation uses key' do
expect_no_offenses('x.each_with_object({}) {|(k, v), h| h[k] = k.to_s}')
end
it 'does not flag each_with_object when no transformation occurs' do
expect_no_offenses('x.each_with_object({}) {|(k, v), h| h[k] = v}')
end
it 'does not flag each_with_object when its argument is not modified' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) {|(k, v), h| other_h[k] = v * v}
RUBY
end
it 'does not flag `each_with_object` when its argument is used in the value' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) { |(k, v), h| h[k] = h.count }
RUBY
end
it 'does not flag each_with_object when receiver is array literal' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_object({}) {|(k, v), h| h[k] = foo(v)}
RUBY
end
it 'does not flag `each_with_object` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_index.each_with_object({}) { |(k, v), h| h[k] = foo(v) }
RUBY
end
it 'does not flag `each_with_object` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each.with_index.each_with_object({}) { |(k, v), h| h[k] = foo(v) }
RUBY
end
it 'does not flag `each_with_object` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
%i[a b c].zip([1, 2, 3]).each_with_object({}) { |(k, v), h| h[k] = foo(v) }
RUBY
end
it 'flags _.map {...}.to_h when transform_values could be used' do
expect_offense(<<~RUBY)
x.map {|k, v| [k, foo(v)]}.to_h
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `map {...}.to_h`.
RUBY
expect_correction(<<~RUBY)
x.transform_values {|v| foo(v)}
RUBY
end
it 'flags _.map {...}.to_h when transform_values could be used when line break before `to_h`' do
expect_offense(<<~RUBY)
x.map {|k, v| [k, foo(v)]}.
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `map {...}.to_h`.
to_h
RUBY
expect_correction(<<~RUBY)
x.transform_values {|v| foo(v)}
RUBY
end
it 'flags _.map {...}.to_h when transform_values could be used when wrapped in another block' do
expect_offense(<<~RUBY)
wrapping do
x.map do |k, v|
^^^^^^^^^^^^^^^ Prefer `transform_values` over `map {...}.to_h`.
[k, v.to_s]
end.to_h
end
RUBY
expect_correction(<<~RUBY)
wrapping do
x.transform_values do |v|
v.to_s
end
end
RUBY
end
it 'does not flag _.map{...}.to_h when both key & value are transformed' do
expect_no_offenses('x.map {|k, v| [k.to_sym, foo(v)]}.to_h')
end
it 'flags Hash[_.map{...}] when transform_values could be used' do
expect_offense(<<~RUBY)
Hash[x.map {|k, v| [k, foo(v)]}]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `Hash[_.map {...}]`.
RUBY
expect_correction(<<~RUBY)
x.transform_values {|v| foo(v)}
RUBY
end
it 'does not flag Hash[_.map{...}] when both key & value are transformed' do
expect_no_offenses('Hash[x.map {|k, v| [k.to_sym, foo(v)]}]')
end
it 'does not flag _.map {...}.to_h when value block argument is unused' do
expect_no_offenses(<<~RUBY)
x.map {|k, _v| [k, k]}.to_h
RUBY
end
it 'does not flag value transformation in the absence of to_h' do
expect_no_offenses('x.map {|k, v| [k, foo(v)]}')
end
it 'does not flag value transformation when receiver is array literal' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].map {|k, v| [k, foo(v)]}.to_h
RUBY
end
it 'does not flag `_.map{...}.to_h` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_index.map { |k, v| [k, foo(v)] }.to_h
RUBY
end
it 'does not flag `_.map{...}.to_h` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each.with_index.map { |k, v| [k, foo(v)] }.to_h
RUBY
end
it 'does not flag `_.map{...}.to_h` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
%i[a b c].zip([1, 2, 3]).map { |k, v| [k, foo(v)] }.to_h
RUBY
end
it 'correctly autocorrects _.map{...}.to_h with block' do
expect_offense(<<~RUBY)
{a: 1, b: 2}.map {|k, v| [k, foo(v)]}.to_h {|k, v| [v, k]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `map {...}.to_h`.
RUBY
expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_values {|v| foo(v)}.to_h {|k, v| [v, k]}
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is an array literal' do
expect_no_offenses(<<~RUBY)
Hash[[1, 2, 3].map { |k, v| [k, foo(v)] }]
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
Hash[[1, 2, 3].each_with_index.map { |k, v| [k, foo(v)] }]
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
Hash[[1, 2, 3].each.with_index.map { |k, v| [k, foo(v)] }]
RUBY
end
it 'does not flag `Hash[_.map{...}]` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
Hash[%i[a b c].zip([1, 2, 3]).map { |k, v| [k, foo(v)] }]
RUBY
end
end
context 'when using Ruby 2.6 or newer', :ruby26 do
it 'flags _.to_h{...} when transform_values could be used' do
expect_offense(<<~RUBY)
x.to_h {|k, v| [k, foo(v)]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `to_h {...}`.
RUBY
expect_correction(<<~RUBY)
x.transform_values {|v| foo(v)}
RUBY
end
it 'registers and corrects an offense _.to_h{...} when value is a hash literal and is enclosed in braces' do
expect_offense(<<~RUBY)
{a: 1, b: 2}.to_h { |key, val| [key, { value: val }] }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `to_h {...}`.
RUBY
expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_values { |val| { value: val } }
RUBY
end
it 'registers and corrects an offense _.to_h{...} when value is a hash literal and is not enclosed in braces' do
expect_offense(<<~RUBY)
{a: 1, b: 2}.to_h { |key, val| [key, value: val] }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `to_h {...}`.
RUBY
expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_values { |val| { value: val } }
RUBY
end
it 'does not flag `_.to_h{...}` when both key & value are transformed' do
expect_no_offenses(<<~RUBY)
x.to_h { |k, v| [k.to_sym, foo(v)] }
RUBY
end
it 'does not flag _.to_h {...} when value block argument is unused' do
expect_no_offenses(<<~RUBY)
x.to_h {|k, _v| [k, k]}
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is an array literal' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].to_h { |k, v| [k, foo(v)] }
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is `each_with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_index.to_h { |k, v| [k, foo(v)] }
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is `with_index`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each.with_index.to_h { |k, v| [k, foo(v)] }
RUBY
end
it 'does not flag `_.to_h{...}` when its receiver is `zip`' do
expect_no_offenses(<<~RUBY)
%i[a b c].zip([1, 2, 3]).to_h { |k, v| [k, foo(v)] }
RUBY
end
end
context 'below Ruby 2.4', :ruby23, unsupported_on: :prism do
it 'does not flag even if transform_values could be used' do
expect_no_offenses('x.each_with_object({}) {|(k, v), h| h[k] = foo(v)}')
end
end
context 'below Ruby 2.6', :ruby25, unsupported_on: :prism do
it 'does not flag _.to_h{...}' do
expect_no_offenses(<<~RUBY)
x.to_h {|k, v| [k, foo(v)]}
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_function_spec.rb | spec/rubocop/cop/style/module_function_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ModuleFunction, :config do
context 'when enforced style is `module_function`' do
let(:cop_config) { { 'EnforcedStyle' => 'module_function' } }
it 'registers an offense for `extend self` in a module' do
expect_offense(<<~RUBY)
module Test
extend self
^^^^^^^^^^^ Use `module_function` instead of `extend self`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
module_function
def test; end
end
RUBY
end
it 'accepts for `extend self` in a module with private methods' do
expect_no_offenses(<<~RUBY)
module Test
extend self
def test; end
private
def test_private;end
end
RUBY
end
it 'accepts for `extend self` in a module with declarative private' do
expect_no_offenses(<<~RUBY)
module Test
extend self
def test; end
private :test
end
RUBY
end
it 'accepts `extend self` in a class' do
expect_no_offenses(<<~RUBY)
class Test
extend self
end
RUBY
end
end
context 'when enforced style is `extend_self`' do
let(:cop_config) { { 'EnforcedStyle' => 'extend_self' } }
it 'registers an offense for `module_function` without an argument' do
expect_offense(<<~RUBY)
module Test
module_function
^^^^^^^^^^^^^^^ Use `extend self` instead of `module_function`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
extend self
def test; end
end
RUBY
end
it 'accepts module_function with an argument' do
expect_no_offenses(<<~RUBY)
module Test
def test; end
module_function :test
end
RUBY
end
end
context 'when enforced style is `forbidden`' do
let(:cop_config) { { 'EnforcedStyle' => 'forbidden' } }
context 'registers an offense for `extend self`' do
it 'in a module' do
expect_offense(<<~RUBY)
module Test
extend self
^^^^^^^^^^^ Do not use `module_function` or `extend self`.
def test; end
end
RUBY
expect_no_corrections
end
it 'in a module with private methods' do
expect_offense(<<~RUBY)
module Test
extend self
^^^^^^^^^^^ Do not use `module_function` or `extend self`.
def test; end
private
def test_private;end
end
RUBY
expect_no_corrections
end
it 'in a module with declarative private' do
expect_offense(<<~RUBY)
module Test
extend self
^^^^^^^^^^^ Do not use `module_function` or `extend self`.
def test; end
private :test
end
RUBY
expect_no_corrections
end
end
it 'accepts `extend self` in a class' do
expect_no_offenses(<<~RUBY)
class Test
extend self
end
RUBY
end
it 'registers an offense for `module_function` without an argument' do
expect_offense(<<~RUBY)
module Test
module_function
^^^^^^^^^^^^^^^ Do not use `module_function` or `extend self`.
def test; end
end
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/if_with_semicolon_spec.rb | spec/rubocop/cop/style/if_with_semicolon_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::IfWithSemicolon, :config do
it 'registers an offense and corrects for one line if/;/end' do
expect_offense(<<~RUBY)
if cond; run else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? run : dont
RUBY
end
it 'registers an offense and corrects for one line if/;/end without then body' do
expect_offense(<<~RUBY)
if cond; else dont end
^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? nil : dont
RUBY
end
it 'registers an offense when not using `else` branch' do
expect_offense(<<~RUBY)
if cond; run end
^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? run : nil
RUBY
end
it 'registers an offense and corrects a single-line `if/;/end` when the then body contains a parenthesized method call with an argument' do
expect_offense(<<~RUBY)
if cond;do_something(arg) end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? do_something(arg) : nil
RUBY
end
it 'registers an offense and corrects a single-line `if/;/end` when the then body contains an array literal with an argument' do
expect_offense(<<~RUBY)
if cond;[] end
^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? [] : nil
RUBY
end
it 'registers an offense and corrects a single-line `if/;/end` when the then body contains a method call with an argument' do
expect_offense(<<~RUBY)
if cond;do_something arg end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? do_something(arg) : nil
RUBY
end
it 'registers an offense and corrects a single-line `if/;/end` when the then body contains a safe navigation method call with an argument' do
expect_offense(<<~RUBY)
if cond;obj&.do_something arg end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? obj&.do_something(arg) : nil
RUBY
end
it 'registers an offense and corrects a single-line `if/;/else/end` when the then body contains a method call with an argument' do
expect_offense(<<~RUBY)
if cond;foo foo_arg else bar bar_arg end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? foo(foo_arg) : bar(bar_arg)
RUBY
end
it 'registers an offense and corrects a single-line `if/;/else/end` when the then body contains a safe navigation method call with an argument' do
expect_offense(<<~RUBY)
if cond;foo obj&.foo_arg else bar obj&.bar_arg end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? foo(obj&.foo_arg) : bar(obj&.bar_arg)
RUBY
end
it 'registers an offense and corrects a single-line `if/;/end` when the then body contains an arithmetic operator method call' do
expect_offense(<<~RUBY)
if cond;do_something - arg end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? do_something - arg : nil
RUBY
end
it 'registers an offense and corrects a single-line `if/;/end` when the then body contains a method call with `[]`' do
expect_offense(<<~RUBY)
if cond; foo[key] else bar end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? foo[key] : bar
RUBY
end
it 'registers an offense and corrects a single-line `if/;/end` when the then body contains a method call with `[]=`' do
expect_offense(<<~RUBY)
if cond; foo[key] = value else bar end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? foo[key] = value : bar
RUBY
end
it 'registers an offense when using multiple expressions in the `else` branch' do
expect_offense(<<~RUBY)
if cond; foo else bar'arg'; baz end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a newline instead.
RUBY
expect_correction(<<~RUBY)
if cond
foo else bar'arg'; baz end
RUBY
end
it 'can handle modifier conditionals' do
expect_no_offenses(<<~RUBY)
class Hash
end if RUBY_VERSION < "1.8.7"
RUBY
end
context 'when elsif is present' do
it 'registers an offense when without branch bodies' do
expect_offense(<<~RUBY)
if cond; elsif cond2; end
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if cond
#{' ' * 2}
elsif cond2
#{' ' * 2}
end
RUBY
end
it 'registers an offense when without `else` branch' do
expect_offense(<<~RUBY)
if cond; run elsif cond2; run2 end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if cond
run
elsif cond2
run2
end
RUBY
end
it 'registers an offense when second elsif block' do
expect_offense(<<~RUBY)
if cond; run elsif cond2; run2 elsif cond3; run3 else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if cond
run
elsif cond2
run2
elsif cond3
run3
else
dont
end
RUBY
end
it 'registers an offense when with `else` branch' do
expect_offense(<<~RUBY)
if cond; run elsif cond2; run2 else dont end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if cond
run
elsif cond2
run2
else
dont
end
RUBY
end
it 'registers an offense when a nested `if` with a semicolon is used' do
expect_offense(<<~RUBY)
if cond; run
^^^^^^^^^^^^ Do not use `if cond;` - use a newline instead.
if cond; run
end
end
RUBY
expect_correction(<<~RUBY)
if cond
run
if cond; run
end
end
RUBY
end
it 'registers an offense and corrects when using nested single-line if/;/end in block of if body' do
expect_offense(<<~RUBY)
if foo?; bar { if qux?; quux else end } end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if foo?;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if foo?
bar { if qux?; quux else end } end
RUBY
end
it 'registers an offense and corrects when using nested single-line if/;/end in the block of else body' do
expect_offense(<<~RUBY)
if foo?; bar else baz { if qux?; quux else end } end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if foo?;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if foo?
bar else baz { if qux?; quux else end } end
RUBY
end
it 'registers an offense and corrects when using nested single-line if/;/end in numblock of if body' do
expect_offense(<<~RUBY)
if foo?; bar { if _1; quux else end } end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if foo?;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if foo?
bar { if _1; quux else end } end
RUBY
end
it 'registers an offense and corrects when using nested single-line if/;/end in the numblock of else body' do
expect_offense(<<~RUBY)
if foo?; bar else baz { if _1; quux else end } end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if foo?;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if foo?
bar else baz { if _1; quux else end } end
RUBY
end
it 'registers an offense when using multi value assignment in `if` with a semicolon is used' do
expect_offense(<<~RUBY)
if foo; bar, baz = qux else quux end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if foo;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if foo
bar, baz = qux else quux end
RUBY
end
it 'registers an offense when using multi value assignment in `else` with a semicolon is used' do
expect_offense(<<~RUBY)
if foo; bar else baz, qux = quux end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if foo;` - use `if/else` instead.
RUBY
expect_correction(<<~RUBY)
if foo
bar else baz, qux = quux end
RUBY
end
it 'registers an offense when using `return` with value in `if` with a semicolon is used' do
expect_offense(<<~RUBY)
if cond; return value end
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a newline instead.
RUBY
expect_correction(<<~RUBY)
if cond
return value end
RUBY
end
it 'registers an offense when using `return` without value in `if` with a semicolon is used' do
expect_offense(<<~RUBY)
if cond; return end
^^^^^^^^^^^^^^^^^^^ Do not use `if cond;` - use a ternary operator instead.
RUBY
expect_correction(<<~RUBY)
cond ? return : nil
RUBY
end
it 'registers an offense and corrects when using nested if/;/end in if body' do
expect_offense(<<~RUBY)
if cond1; foo + if cond2; bar
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `if cond1;` - use a ternary operator instead.
else
end
end
RUBY
expect_correction(<<~RUBY)
cond1 ? foo + if cond2; bar
else
end : nil
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/percent_literal_delimiters_spec.rb | spec/rubocop/cop/style/percent_literal_delimiters_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::PercentLiteralDelimiters, :config do
let(:cop_config) { { 'PreferredDelimiters' => { 'default' => '[]' } } }
context '`default` override' do
let(:cop_config) { { 'PreferredDelimiters' => { 'default' => '[]', '%' => '()' } } }
it 'allows all preferred delimiters to be set with one key' do
expect_no_offenses('%w[string] + %i[string]')
end
it 'allows individual preferred delimiters to override `default`' do
expect_no_offenses('%w[string] + [%(string)]')
end
end
context 'invalid cop config' do
let(:cop_config) { { 'PreferredDelimiters' => { 'foobar' => '()' } } }
it 'raises an error when invalid configuration is specified' do
expect { expect_no_offenses('%w[string]') }.to raise_error(ArgumentError)
end
end
context '`%` interpolated string' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%[string]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%(string)
^^^^^^^^^ `%`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%[string]
RUBY
end
it 'registers an offense for a string with no content' do
expect_offense(<<~RUBY)
%()
^^^ `%`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%[]
RUBY
end
it 'does not register an offense for other delimiters ' \
'when containing preferred delimiter characters' do
expect_no_offenses(<<~RUBY)
%([string])
RUBY
end
it 'registers an offense for other delimiters ' \
'when containing preferred delimiter characters in interpolation' do
expect_offense(<<~'RUBY')
%(#{[1].first})
^^^^^^^^^^^^^^^ `%`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~'RUBY')
%[#{[1].first}]
RUBY
end
it 'registers an offense when the source contains invalid characters' do
expect_offense(<<~'RUBY')
%{\x80}
^^^^^^^ `%`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~'RUBY')
%[\x80]
RUBY
end
end
context '`%q` string' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%q[string]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%q(string)
^^^^^^^^^^ `%q`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%q[string]
RUBY
end
it 'does not register an offense for other delimiters ' \
'when containing preferred delimiter characters' do
expect_no_offenses(<<~RUBY)
%q([string])
RUBY
end
end
context '`%Q` interpolated string' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%Q[string]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%Q(string)
^^^^^^^^^^ `%Q`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%Q[string]
RUBY
end
it 'does not register an offense for other delimiters ' \
'when containing preferred delimiter characters' do
expect_no_offenses(<<~RUBY)
%Q([string])
RUBY
end
it 'registers an offense for other delimiters ' \
'when containing preferred delimiter characters in interpolation' do
expect_offense(<<~'RUBY')
%Q(#{[1].first})
^^^^^^^^^^^^^^^^ `%Q`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~'RUBY')
%Q[#{[1].first}]
RUBY
end
end
context '`%w` string array' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%w[some words]')
end
it 'does not register an offense for preferred delimiters with a pairing delimiters' do
expect_no_offenses('%w(\(some words\))')
end
it 'does not register an offense for preferred delimiters with only a closing delimiter' do
expect_no_offenses('%w(only closing delimiter character\))')
end
it 'does not register an offense for preferred delimiters with not a pairing delimiter' do
expect_no_offenses('%w|\|not pairing delimiter|')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%w(some words)
^^^^^^^^^^^^^^ `%w`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%w[some words]
RUBY
end
it 'does not register an offense for other delimiters ' \
'when containing preferred delimiter characters' do
expect_no_offenses('%w([some] [words])')
end
end
context '`%W` interpolated string array' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%W[some words]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%W(some words)
^^^^^^^^^^^^^^ `%W`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%W[some words]
RUBY
end
it 'does not register an offense for other delimiters ' \
'when containing preferred delimiter characters' do
expect_no_offenses('%W([some] [words])')
end
it 'registers an offense for other delimiters ' \
'when containing preferred delimiter characters in interpolation' do
expect_offense(<<~'RUBY')
%W(#{[1].first})
^^^^^^^^^^^^^^^^ `%W`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~'RUBY')
%W[#{[1].first}]
RUBY
end
end
context '`%r` interpolated regular expression' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%r[regexp]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%r(regexp)
^^^^^^^^^^ `%r`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%r[regexp]
RUBY
end
it 'does not register an offense for other delimiters ' \
'when containing preferred delimiter characters' do
expect_no_offenses('%r([regexp])')
end
it 'registers an offense for other delimiters ' \
'when containing preferred delimiter characters in interpolation' do
expect_offense(<<~'RUBY')
%r(#{[1].first})
^^^^^^^^^^^^^^^^ `%r`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~'RUBY')
%r[#{[1].first}]
RUBY
end
it 'registers an offense for a regular expression with option' do
expect_offense(<<~RUBY)
%r(.*)i
^^^^^^^ `%r`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%r[.*]i
RUBY
end
end
context '`%i` symbol array' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%i[some symbols]')
end
it 'does not register an offense for non-preferred delimiters enclosing escaped delimiters' do
expect_no_offenses('%i(\(\) each)')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%i(some symbols)
^^^^^^^^^^^^^^^^ `%i`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%i[some symbols]
RUBY
end
end
context '`%I` interpolated symbol array' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%I[some words]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%I(some words)
^^^^^^^^^^^^^^ `%I`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%I[some words]
RUBY
end
it 'registers an offense for other delimiters ' \
'when containing preferred delimiter characters in interpolation' do
expect_offense(<<~'RUBY')
%I(#{[1].first})
^^^^^^^^^^^^^^^^ `%I`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~'RUBY')
%I[#{[1].first}]
RUBY
end
end
context '`%s` symbol' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%s[symbol]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%s(symbol)
^^^^^^^^^^ `%s`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%s[symbol]
RUBY
end
end
context '`%x` interpolated system call' do
it 'does not register an offense for preferred delimiters' do
expect_no_offenses('%x[command]')
end
it 'registers an offense for other delimiters' do
expect_offense(<<~RUBY)
%x(command)
^^^^^^^^^^^ `%x`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
%x[command]
RUBY
end
it 'does not register an offense for other delimiters ' \
'when containing preferred delimiter characters' do
expect_no_offenses('%x([command])')
end
it 'registers an offense for other delimiters ' \
'when containing preferred delimiter characters in interpolation' do
expect_offense(<<~'RUBY')
%x(#{[1].first})
^^^^^^^^^^^^^^^^ `%x`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~'RUBY')
%x[#{[1].first}]
RUBY
end
end
context 'autocorrect' do
it 'fixes a string array in a scope' do
expect_offense(<<~RUBY)
module Foo
class Bar
def baz
%(one two)
^^^^^^^^^^ `%`-literals should be delimited by `[` and `]`.
end
end
end
RUBY
expect_correction(<<~RUBY)
module Foo
class Bar
def baz
%[one two]
end
end
end
RUBY
end
it 'preserves line breaks when fixing a multiline array' do
expect_offense(<<~RUBY)
%w(
^^^ `%w`-literals should be delimited by `[` and `]`.
some
words
)
RUBY
expect_correction(<<~RUBY)
%w[
some
words
]
RUBY
end
it 'preserves indentation when correcting a multiline array' do
expect_offense(<<-RUBY.strip_margin('|'))
| array = %w(
| ^^^ `%w`-literals should be delimited by `[` and `]`.
| first
| second
| )
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| array = %w[
| first
| second
| ]
RUBY
end
it 'preserves irregular indentation when correcting a multiline array' do
expect_offense(<<~RUBY)
array = %w(
^^^ `%w`-literals should be delimited by `[` and `]`.
first
second
)
RUBY
expect_correction(<<~RUBY)
array = %w[
first
second
]
RUBY
end
shared_examples 'escape characters' do |percent_literal|
let(:tab) { "\t" }
it "corrects #{percent_literal} with \\n in it" do
expect_offense(<<~RUBY, percent_literal: percent_literal)
%{percent_literal}{
^{percent_literal}^ `#{percent_literal}`-literals should be delimited by `[` and `]`.
}
RUBY
expect_correction(<<~RUBY)
#{percent_literal}[
]
RUBY
end
it "corrects #{percent_literal} with \\t in it" do
expect_offense(<<~RUBY, percent_literal: percent_literal, tab: tab)
%{percent_literal}{%{tab}}
^{percent_literal}^^{tab}^ `#{percent_literal}`-literals should be delimited by `[` and `]`.
RUBY
expect_correction(<<~RUBY)
#{percent_literal}[\t]
RUBY
end
end
it_behaves_like('escape characters', '%')
it_behaves_like('escape characters', '%q')
it_behaves_like('escape characters', '%Q')
it_behaves_like('escape characters', '%s')
it_behaves_like('escape characters', '%w')
it_behaves_like('escape characters', '%W')
it_behaves_like('escape characters', '%x')
it_behaves_like('escape characters', '%r')
it_behaves_like('escape characters', '%i')
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_parentheses_spec.rb | spec/rubocop/cop/style/redundant_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantParentheses, :config do
shared_examples 'redundant' do |expr, correct, type, options|
it "registers an offense for parentheses around #{type}", *options do
expect_offense(<<~RUBY, expr: expr)
%{expr}
^{expr} Don't use parentheses around #{type}.
RUBY
expect_correction(<<~RUBY)
#{correct}
RUBY
end
end
shared_examples 'plausible' do |expr, options|
it 'accepts parentheses when arguments are unparenthesized', *options do
expect_no_offenses(expr)
end
end
shared_examples 'keyword with return value' do |keyword, options|
it_behaves_like 'redundant', "(#{keyword})", keyword, 'a keyword', options
it_behaves_like 'redundant', "(#{keyword}())", "#{keyword}()", 'a keyword', options
it_behaves_like 'redundant', "(#{keyword}(1))", "#{keyword}(1)", 'a keyword', options
it_behaves_like 'plausible', "(#{keyword} 1, 2)", options
end
shared_examples 'keyword with arguments' do |keyword|
it_behaves_like 'redundant', "(#{keyword})", keyword, 'a keyword'
it_behaves_like 'redundant', "(#{keyword}())", "#{keyword}()", 'a keyword'
it_behaves_like 'redundant', "(#{keyword}(1, 2))", "#{keyword}(1, 2)", 'a keyword'
it_behaves_like 'plausible', "(#{keyword} 1, 2)"
end
it_behaves_like 'redundant', '("x")', '"x"', 'a literal'
it_behaves_like 'redundant', '("#{x}")', '"#{x}"', 'a literal'
it_behaves_like 'redundant', '(:x)', ':x', 'a literal'
it_behaves_like 'redundant', '(:"#{x}")', ':"#{x}"', 'a literal'
it_behaves_like 'redundant', '(1)', '1', 'a literal'
it_behaves_like 'redundant', '(1.2)', '1.2', 'a literal'
it_behaves_like 'redundant', '({})', '{}', 'a literal'
it_behaves_like 'redundant', '([])', '[]', 'a literal'
it_behaves_like 'redundant', '(nil)', 'nil', 'a literal'
it_behaves_like 'redundant', '(true)', 'true', 'a literal'
it_behaves_like 'redundant', '(false)', 'false', 'a literal'
it_behaves_like 'redundant', '(/regexp/)', '/regexp/', 'a literal'
it_behaves_like 'redundant', '("x"; "y")', '"x"; "y"', 'a literal'
it_behaves_like 'redundant', '(1; 2)', '1; 2', 'a literal'
it_behaves_like 'redundant', '(1i)', '1i', 'a literal'
it_behaves_like 'redundant', '(1r)', '1r', 'a literal'
it_behaves_like 'redundant', '((1..42))', '(1..42)', 'a literal'
it_behaves_like 'redundant', '((1...42))', '(1...42)', 'a literal'
it_behaves_like 'redundant', '((1..))', '(1..)', 'a literal'
it_behaves_like 'redundant', '((..42))', '(..42)', 'a literal'
it_behaves_like 'redundant', '(__FILE__)', '__FILE__', 'a keyword'
it_behaves_like 'redundant', '(__LINE__)', '__LINE__', 'a keyword'
it_behaves_like 'redundant', '(__ENCODING__)', '__ENCODING__', 'a keyword'
it_behaves_like 'redundant', '(redo)', 'redo', 'a keyword', [:ruby32, { unsupported_on: :prism }]
context 'Ruby <= 3.2', :ruby32, unsupported_on: :prism do
it_behaves_like 'redundant', '(retry)', 'retry', 'a keyword'
end
it_behaves_like 'redundant', '(self)', 'self', 'a keyword'
context 'ternaries' do
let(:other_cops) do
{
'Style/TernaryParentheses' => {
'Enabled' => ternary_parentheses_enabled,
'EnforcedStyle' => ternary_parentheses_enforced_style
}
}
end
let(:ternary_parentheses_enabled) { true }
let(:ternary_parentheses_enforced_style) { nil }
context 'when Style/TernaryParentheses is not enabled' do
let(:ternary_parentheses_enabled) { false }
it 'registers an offense for parens around constant ternary condition' do
expect_offense(<<~RUBY)
(X) ? Y : N
^^^ Don't use parentheses around a constant.
(X)? Y : N
^^^ Don't use parentheses around a constant.
RUBY
expect_correction(<<~RUBY)
X ? Y : N
X ? Y : N
RUBY
end
end
context 'when Style/TernaryParentheses has EnforcedStyle: require_no_parentheses' do
let(:ternary_parentheses_enforced_style) { 'require_no_parentheses' }
it 'registers an offense for parens around ternary condition' do
expect_offense(<<~RUBY)
(X) ? Y : N
^^^ Don't use parentheses around a constant.
(X)? Y : N
^^^ Don't use parentheses around a constant.
RUBY
expect_correction(<<~RUBY)
X ? Y : N
X ? Y : N
RUBY
end
end
context 'when Style/TernaryParentheses has EnforcedStyle: require_parentheses' do
let(:ternary_parentheses_enforced_style) { 'require_parentheses' }
it_behaves_like 'plausible', '(X) ? Y : N'
end
context 'when Style/TernaryParentheses has EnforcedStyle: require_parentheses_when_complex' do
let(:ternary_parentheses_enforced_style) { 'require_parentheses_when_complex' }
it_behaves_like 'plausible', '(X) ? Y : N'
end
end
it_behaves_like 'keyword with return value', 'break', [:ruby32, { unsupported_on: :prism }]
it_behaves_like 'keyword with return value', 'next', [:ruby32, { unsupported_on: :prism }]
it_behaves_like 'keyword with arguments', 'yield'
it_behaves_like 'keyword with return value', 'return'
it_behaves_like 'keyword with arguments', 'super'
it_behaves_like 'redundant', '(defined?(:A))', 'defined?(:A)', 'a keyword'
it_behaves_like 'plausible', '(defined? :A)'
it_behaves_like 'plausible', '(alias a b)'
it_behaves_like 'plausible', '(not 1)'
it_behaves_like 'plausible', '(a until b)'
it_behaves_like 'plausible', '(a while b)'
it 'registers an offense for parens around a variable after semicolon' do
expect_offense(<<~RUBY)
x = 1; (x)
^^^ Don't use parentheses around a variable.
RUBY
expect_correction(<<~RUBY)
x = 1; x
RUBY
end
it_behaves_like 'redundant', '(@x)', '@x', 'a variable'
it_behaves_like 'redundant', '(@@x)', '@@x', 'a variable'
it_behaves_like 'redundant', '($x)', '$x', 'a variable'
it_behaves_like 'redundant', '(X)', 'X', 'a constant'
it_behaves_like 'redundant', '(-> { x })', '-> { x }', 'an expression'
it_behaves_like 'redundant', '(lambda { x })', 'lambda { x }', 'an expression'
it_behaves_like 'redundant', '(proc { x })', 'proc { x }', 'an expression'
it_behaves_like 'redundant', '(x)', 'x', 'a method call'
it_behaves_like 'redundant', '(x y)', 'x y', 'a method call'
it_behaves_like 'redundant', '(x(1, 2))', 'x(1, 2)', 'a method call'
it_behaves_like 'redundant', '("x".to_sym)', '"x".to_sym', 'a method call'
it_behaves_like 'redundant', '("x"&.to_sym)', '"x"&.to_sym', 'a method call'
it_behaves_like 'redundant', '(x[:y])', 'x[:y]', 'a method call'
it_behaves_like 'redundant', '(@x[:y])', '@x[:y]', 'a method call'
it_behaves_like 'redundant', '(@@x[:y])', '@@x[:y]', 'a method call'
it_behaves_like 'redundant', '($x[:y])', '$x[:y]', 'a method call'
it_behaves_like 'redundant', '(X[:y])', 'X[:y]', 'a method call'
it_behaves_like 'redundant', '("foo"[0])', '"foo"[0]', 'a method call'
it_behaves_like 'redundant', '(foo[0][0])', 'foo[0][0]', 'a method call'
it_behaves_like 'redundant', '(["foo"][0])', '["foo"][0]', 'a method call'
it_behaves_like 'redundant', '({0 => :a}[0])', '{0 => :a}[0]', 'a method call'
it_behaves_like 'redundant', '(x; y)', 'x; y', 'a method call'
it_behaves_like 'redundant', '(x && y)', 'x && y', 'a logical expression'
it_behaves_like 'redundant', '(x || y)', 'x || y', 'a logical expression'
it_behaves_like 'redundant', '(x and y)', 'x and y', 'a logical expression'
it_behaves_like 'redundant', '(x or y)', 'x or y', 'a logical expression'
it_behaves_like 'redundant', '(x == y)', 'x == y', 'a comparison expression'
it_behaves_like 'redundant', '(x === y)', 'x === y', 'a comparison expression'
it_behaves_like 'redundant', '(x != y)', 'x != y', 'a comparison expression'
it_behaves_like 'redundant', '(x > y)', 'x > y', 'a comparison expression'
it_behaves_like 'redundant', '(x >= y)', 'x >= y', 'a comparison expression'
it_behaves_like 'redundant', '(x < y)', 'x < y', 'a comparison expression'
it_behaves_like 'redundant', '(x <= y)', 'x <= y', 'a comparison expression'
it_behaves_like 'redundant', '(var = 42)', 'var = 42', 'an assignment'
it_behaves_like 'redundant', '(@var = 42)', '@var = 42', 'an assignment'
it_behaves_like 'redundant', '(@@var = 42)', '@@var = 42', 'an assignment'
it_behaves_like 'redundant', '($var = 42)', '$var = 42', 'an assignment'
it_behaves_like 'redundant', '(CONST = 42)', 'CONST = 42', 'an assignment'
it_behaves_like 'plausible', 'if (var = 42); end'
it_behaves_like 'plausible', 'unless (var = 42); end'
it_behaves_like 'plausible', 'while (var = 42); end'
it_behaves_like 'plausible', 'until (var = 42); end'
it_behaves_like 'plausible', '(var + 42) > do_something'
it_behaves_like 'plausible', 'foo((bar rescue baz))'
it_behaves_like 'redundant', '(!x)', '!x', 'a unary operation'
it_behaves_like 'redundant', '(~x)', '~x', 'a unary operation'
it_behaves_like 'redundant', '(-x)', '-x', 'a unary operation'
it_behaves_like 'redundant', '(+x)', '+x', 'a unary operation'
# No problem removing the parens when it is the only expression.
it_behaves_like 'redundant', '(!x arg)', '!x arg', 'a unary operation'
it_behaves_like 'redundant', '(!x.m arg)', '!x.m arg', 'a unary operation'
it_behaves_like 'redundant', '(!super arg)', '!super arg', 'a unary operation'
it_behaves_like 'redundant', '(!yield arg)', '!yield arg', 'a unary operation'
it_behaves_like 'redundant', '(!defined? arg)', '!defined? arg', 'a unary operation'
# Removing the parens leads to semantic differences.
it_behaves_like 'plausible', '(!x arg) && foo'
it_behaves_like 'plausible', '(!x.m arg) && foo'
it_behaves_like 'plausible', '(!super arg) && foo'
it_behaves_like 'plausible', '(!yield arg) && foo'
it_behaves_like 'plausible', '(!defined? arg) && foo'
# Removing the parens leads to a syntax error.
it_behaves_like 'plausible', 'foo && (!x arg)'
it_behaves_like 'plausible', 'foo && (!x.m arg)'
it_behaves_like 'plausible', 'foo && (!super arg)'
it_behaves_like 'plausible', 'foo && (!yield arg)'
it_behaves_like 'plausible', 'foo && (!defined? arg)'
it_behaves_like 'plausible', '(!x).y'
it_behaves_like 'plausible', '-(1.foo)'
it_behaves_like 'plausible', '+(1.foo)'
it_behaves_like 'plausible', '-(1.foo.bar)'
it_behaves_like 'plausible', '+(1.foo.bar)'
it_behaves_like 'plausible', 'foo(*(bar & baz))'
it_behaves_like 'plausible', 'foo(*(bar + baz))'
it_behaves_like 'plausible', 'foo(**(bar + baz))'
it_behaves_like 'plausible', 'foo + (bar baz)'
it_behaves_like 'plausible', '()'
it 'registers an offense for parens around a receiver of a method call with an argument' do
expect_offense(<<~RUBY)
(x).y(z)
^^^ Don't use parentheses around a method call.
RUBY
expect_correction(<<~RUBY)
x.y(z)
RUBY
end
it 'registers an offense for parens around a method argument of a parenthesized method call' do
expect_offense(<<~RUBY)
x.y((z))
^^^ Don't use parentheses around a method argument.
RUBY
expect_correction(<<~RUBY)
x.y(z)
RUBY
end
it 'registers an offense for parens around a method argument of a parenthesized method call with safe navigation' do
expect_offense(<<~RUBY)
x&.y((z))
^^^ Don't use parentheses around a method argument.
RUBY
expect_correction(<<~RUBY)
x&.y(z)
RUBY
end
it 'registers an offense for parens around a second method argument of a parenthesized method call' do
expect_offense(<<~RUBY)
x.y(z, (w))
^^^ Don't use parentheses around a method argument.
RUBY
expect_correction(<<~RUBY)
x.y(z, w)
RUBY
end
it 'registers an offense for parens around a method call with argument and no parens around the argument' do
expect_offense(<<~RUBY)
(x y)
^^^^^ Don't use parentheses around a method call.
RUBY
expect_correction(<<~RUBY)
x y
RUBY
end
it 'does not register an offense for parens around `if` as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (2 if y?))
RUBY
end
it 'does not register an offense for parens around `unless` as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (2 unless y?))
RUBY
end
it 'does not register an offense for parens around `while` as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (2 while y?))
RUBY
end
it 'does not register an offense for parens around `until` as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (2 until y?))
RUBY
end
it 'does not register an offense for parens around unparenthesized method call as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (y arg))
RUBY
end
it 'does not register an offense for parens around unparenthesized safe navigation method call as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (y&.z arg))
RUBY
end
it 'does not register an offense for parens around unparenthesized operator dot method call as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (y.+ arg))
RUBY
end
it 'does not register an offense for parens around unparenthesized operator safe navigation method call as the second argument of a parenthesized method call' do
expect_no_offenses(<<~RUBY)
x(1, (y&.+ arg))
RUBY
end
it 'registers an offense for parens around an expression method argument of a parenthesized method call' do
expect_offense(<<~RUBY)
x.y((z + w))
^^^^^^^ Don't use parentheses around a method argument.
RUBY
expect_correction(<<~RUBY)
x.y(z + w)
RUBY
end
it 'registers an offense for parens around a range method argument of a parenthesized method call' do
expect_offense(<<~RUBY)
x.y((a..b))
^^^^^^ Don't use parentheses around a method argument.
RUBY
expect_correction(<<~RUBY)
x.y(a..b)
RUBY
end
it 'registers an offense for parens around a multiline method argument of a parenthesized method call' do
expect_offense(<<~RUBY)
x.y((foo &&
^^^^^^^ Don't use parentheses around a method argument.
bar
))
RUBY
expect_correction(<<~RUBY)
x.y(foo &&
bar)
RUBY
end
it 'registers an offense for parens around method call chained to an `&&` expression' do
# Style/MultipleComparison autocorrects:
# (
# foo == 'a' ||
# foo == 'b' ||
# foo == 'c'
# ) && bar
# to the following:
expect_offense(<<~RUBY)
(
^ Don't use parentheses around a method call.
['a', 'b', 'c'].include?(foo)
) && bar
RUBY
expect_correction(<<~RUBY)
['a', 'b', 'c'].include?(foo) && bar
RUBY
end
it 'does not register an offense for parens around an array destructuring argument in method definition' do
expect_no_offenses('def foo((bar, baz)); end')
end
it 'registers an offense for parens around parenthesized conditional assignment' do
expect_offense(<<~RUBY)
if ((var = 42))
^^^^^^^^^^ Don't use parentheses around an assignment.
end
RUBY
expect_correction(<<~RUBY)
if (var = 42)
end
RUBY
end
it 'registers an offense for parens around an interpolated expression' do
expect_offense(<<~RUBY)
"\#{(foo)}"
^^^^^ Don't use parentheses around an interpolated expression.
RUBY
expect_correction(<<~RUBY)
"\#{foo}"
RUBY
end
it 'registers an offense for parens around a literal in array' do
expect_offense(<<~RUBY)
[(1)]
^^^ Don't use parentheses around a literal.
RUBY
expect_correction(<<~RUBY)
[1]
RUBY
end
it 'registers an offense for parens around a literal in array and following newline' do
expect_offense(<<~RUBY)
[(1
^^ Don't use parentheses around a literal.
)]
RUBY
expect_correction(<<~RUBY)
[1]
RUBY
end
it 'registers an offense for parens around a binary operator in an array' do
expect_offense(<<~RUBY)
[(foo + bar)]
^^^^^^^^^^^ Don't use parentheses around a method call.
RUBY
expect_correction(<<~RUBY)
[foo + bar]
RUBY
end
context 'literals in an array' do
context 'when there is a comma on the same line as the closing parentheses' do
it 'registers an offense and corrects when there is no subsequent item' do
expect_offense(<<~RUBY)
[
(
^ Don't use parentheses around a literal.
1
)
]
RUBY
expect_correction(<<~RUBY)
[
1
]
RUBY
end
it 'registers an offense and corrects when there is a trailing comma' do
expect_offense(<<~RUBY)
[(1
^^ Don't use parentheses around a literal.
),]
RUBY
expect_correction(<<~RUBY)
[1,]
RUBY
end
it 'registers an offense and corrects when there is a subsequent item' do
expect_offense(<<~RUBY)
[
(
^ Don't use parentheses around a literal.
1
),
2
]
RUBY
expect_correction(<<~RUBY)
[
1,
2
]
RUBY
end
it 'registers an offense and corrects when there is assignment' do
expect_offense(<<~RUBY)
[
x = (
^ Don't use parentheses around a literal.
1
),
y = 2
]
RUBY
expect_correction(<<~RUBY)
[
x = 1,
y = 2
]
RUBY
end
end
end
it 'registers an offense for parens around a literal hash value' do
expect_offense(<<~RUBY)
{a: (1)}
^^^ Don't use parentheses around a literal.
RUBY
expect_correction(<<~RUBY)
{a: 1}
RUBY
end
it 'registers an offense for parens around a literal hash value and following newline' do
expect_offense(<<~RUBY)
{a: (1
^^ Don't use parentheses around a literal.
)}
RUBY
expect_correction(<<~RUBY)
{a: 1}
RUBY
end
it 'registers an offense and corrects for a parenthesized item in a hash where ' \
'the comma is on a line with the closing parens' do
expect_offense(<<~RUBY)
{ a: (1
^^ Don't use parentheses around a literal.
),}
RUBY
expect_correction(<<~RUBY)
{ a: 1,}
RUBY
end
it 'registers an offense for parens around an integer exponentiation base' do
expect_offense(<<~RUBY)
(0)**2
^^^ Don't use parentheses around a literal.
(2)**2
^^^ Don't use parentheses around a literal.
RUBY
expect_correction(<<~RUBY)
0**2
2**2
RUBY
end
it 'registers an offense for parens around a float exponentiation base' do
expect_offense(<<~RUBY)
(2.1)**2
^^^^^ Don't use parentheses around a literal.
RUBY
expect_correction(<<~RUBY)
2.1**2
RUBY
end
it 'registers an offense for parens around a negative exponent' do
expect_offense(<<~RUBY)
2**(-2)
^^^^ Don't use parentheses around a literal.
RUBY
expect_correction(<<~RUBY)
2**-2
RUBY
end
it 'registers an offense for parens around a positive exponent' do
expect_offense(<<~RUBY)
2**(2)
^^^ Don't use parentheses around a literal.
RUBY
expect_correction(<<~RUBY)
2**2
RUBY
end
it 'registers an offense for parens around `->` with `do`...`end` block' do
expect_offense(<<~RUBY)
scope :my_scope, (-> do
^^^^^^ Don't use parentheses around an expression.
where(column: :value)
end)
RUBY
expect_correction(<<~RUBY)
scope :my_scope, -> do
where(column: :value)
end
RUBY
end
it 'registers an offense for parens around `lambda` with `{`...`}` block' do
expect_offense(<<~RUBY)
scope :my_scope, (lambda {
^^^^^^^^^ Don't use parentheses around an expression.
where(column: :value)
})
RUBY
expect_correction(<<~RUBY)
scope :my_scope, lambda {
where(column: :value)
}
RUBY
end
it 'registers an offense for parens around `proc` with `{`...`}` block' do
expect_offense(<<~RUBY)
scope :my_scope, (proc {
^^^^^^^ Don't use parentheses around an expression.
where(column: :value)
})
RUBY
expect_correction(<<~RUBY)
scope :my_scope, proc {
where(column: :value)
}
RUBY
end
it 'does not register an offense for parens around `lambda` with `do`...`end` block' do
expect_no_offenses(<<~RUBY)
scope :my_scope, (lambda do
where(column: :value)
end)
RUBY
end
it 'does not register an offense for parens around `proc` with `do`...`end` block' do
expect_no_offenses(<<~RUBY)
scope :my_scope, (proc do
where(column: :value)
end)
RUBY
end
it 'registers an offense for parentheses around a method chain with `{`...`}` block in keyword argument' do
expect_offense(<<~RUBY)
foo bar: (baz {
^^^^^^ Don't use parentheses around a method call.
}.qux)
RUBY
end
it 'registers an offense for parentheses around a method chain with `{`...`}` numblock in keyword argument' do
expect_offense(<<~RUBY)
foo bar: (baz {
^^^^^^ Don't use parentheses around a method call.
do_something(_1)
}.qux)
RUBY
end
it 'does not register an offense for parentheses around a method chain with `do`...`end` block in keyword argument' do
expect_no_offenses(<<~RUBY)
foo bar: (baz do
end.qux)
RUBY
end
it 'does not register an offense for parentheses around method chains with `do`...`end` block in keyword argument' do
expect_no_offenses(<<~RUBY)
foo bar: (baz do
end.qux.quux)
RUBY
end
it 'does not register an offense for parentheses around a method chain with `do`...`end` numblock in keyword argument' do
expect_no_offenses(<<~RUBY)
foo bar: (baz do
do_something(_1)
end.qux)
RUBY
end
it 'does not register an offense for parentheses around a method chain with `do`...`end` block in keyword argument for safe navigation call' do
expect_no_offenses(<<~RUBY)
obj&.foo bar: (baz do
end.qux)
RUBY
end
it 'does not register an offense for parentheses around a method chain with `do`...`end` numblock in keyword argument for safe navigation call' do
expect_no_offenses(<<~RUBY)
obj&.foo bar: (baz do
do_something(_1)
end.qux)
RUBY
end
it 'registers an offense when braces block is wrapped in parentheses as a method argument' do
expect_offense(<<~RUBY)
foo (x.select { |item| item }).y
^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't use parentheses around a method call.
RUBY
expect_correction(<<~RUBY)
foo x.select { |item| item }.y
RUBY
end
it 'does not register an offense when `do`...`end` block is wrapped in parentheses as a method argument' do
expect_no_offenses(<<~RUBY)
foo (x.select do |item| item end).y
RUBY
end
it 'registers a multiline expression around block wrapped in parens with a chained method' do
expect_offense(<<~RUBY)
(
^ Don't use parentheses around a method call.
x.select { |item| item.foo }
).map(&:bar)
RUBY
expect_correction(<<~RUBY)
x.select { |item| item.foo }.map(&:bar)
RUBY
end
it_behaves_like 'redundant', '(x.select { |item| item })', 'x.select { |item| item }', 'a method call'
context 'when Ruby 2.7', :ruby27 do
it_behaves_like 'redundant', '(x.select { _1 })', 'x.select { _1 }', 'a method call'
end
context 'when Ruby 3.4', :ruby34 do
it_behaves_like 'redundant', '(x.select { it })', 'x.select { it }', 'a method call'
end
it_behaves_like 'plausible', '(-2)**2'
it_behaves_like 'plausible', '(-2.1)**2'
it_behaves_like 'plausible', 'x = (foo; bar)'
it_behaves_like 'plausible', 'x += (foo; bar)'
it_behaves_like 'plausible', 'x + (foo; bar)'
it_behaves_like 'plausible', 'x((foo; bar))'
it_behaves_like 'plausible', '(foo[key] & bar.baz).any?'
it 'registers an offense for parens around method body' do
expect_offense(<<~RUBY)
def x
(foo; bar)
^^^^^^^^^^ Don't use parentheses around a method call.
end
RUBY
expect_correction(<<~RUBY)
def x
foo; bar
end
RUBY
end
it 'registers an offense for parens around singleton method body' do
expect_offense(<<~RUBY)
def self.x
(foo; bar)
^^^^^^^^^^ Don't use parentheses around a method call.
end
RUBY
expect_correction(<<~RUBY)
def self.x
foo; bar
end
RUBY
end
it 'registers an offense for parens around last expressions in method body' do
expect_offense(<<~RUBY)
def x
baz
(foo; bar)
^^^^^^^^^^ Don't use parentheses around a method call.
end
RUBY
expect_correction(<<~RUBY)
def x
baz
foo; bar
end
RUBY
end
it 'registers an offense for parens around a block body' do
expect_offense(<<~RUBY)
x do
(foo; bar)
^^^^^^^^^^ Don't use parentheses around a method call.
end
RUBY
expect_correction(<<~RUBY)
x do
foo; bar
end
RUBY
end
it 'registers an offense for parens around a numblock body' do
expect_offense(<<~RUBY)
x do
(_1; bar)
^^^^^^^^^ Don't use parentheses around a variable.
end
RUBY
expect_correction(<<~RUBY)
x do
_1; bar
end
RUBY
end
it 'registers an offense for parens around last expressions in block body' do
expect_offense(<<~RUBY)
x do
baz
(foo; bar)
^^^^^^^^^^ Don't use parentheses around a method call.
end
RUBY
expect_correction(<<~RUBY)
x do
baz
foo; bar
end
RUBY
end
it 'registers an offense when the use of parentheses around `&&` expressions in assignment' do
expect_offense(<<~RUBY)
var = (foo && bar)
^^^^^^^^^^^^ Don't use parentheses around a logical expression.
RUBY
expect_correction(<<~RUBY)
var = foo && bar
RUBY
end
it 'registers an offense when the use of parentheses around `||` expressions in assignment' do
expect_offense(<<~RUBY)
var = (foo || bar)
^^^^^^^^^^^^ Don't use parentheses around a logical expression.
RUBY
expect_correction(<<~RUBY)
var = foo || bar
RUBY
end
it 'accepts the use of parentheses around `or` expressions in assignment' do
expect_no_offenses('var = (foo or bar)')
end
it 'accepts the use of parentheses around `and` expressions in assignment' do
expect_no_offenses('var = (foo and bar)')
end
it 'accepts parentheses around a method call with unparenthesized arguments' do
expect_no_offenses('(a 1, 2) && (1 + 1)')
end
it 'accepts parentheses inside an irange' do
expect_no_offenses('(a)..(b)')
end
it 'accepts parentheses inside an erange' do
expect_no_offenses('(a)...(b)')
end
it 'accepts parentheses around an irange' do
expect_no_offenses('(a..b)')
end
it 'accepts parentheses around an erange' do
expect_no_offenses('(a...b)')
end
it 'accepts parentheses around an irange when a different expression precedes it' do
expect_no_offenses(<<~RUBY)
do_something
(a..b)
RUBY
end
it 'accepts parentheses around an erange when a different expression precedes it' do
expect_no_offenses(<<~RUBY)
do_something
(a...b)
RUBY
end
it 'accepts an irange starting is a parenthesized condition' do
expect_no_offenses('(a || b)..c')
end
it 'accepts an erange starting is a parenthesized condition' do
expect_no_offenses('(a || b)...c')
end
it 'accepts an irange ending is a parenthesized condition' do
expect_no_offenses('a..(b || c)')
end
it 'accepts an erange ending is a parenthesized condition' do
expect_no_offenses('a...(b || c)')
end
it 'accepts regexp literal attempts to match against a parenthesized condition' do
expect_no_offenses('/regexp/ =~ (b || c)')
end
it 'accepts variable attempts to match against a parenthesized condition' do
expect_no_offenses('regexp =~ (b || c)')
end
it 'registers parentheses around `||` logical operator keywords in method definition' do
expect_offense(<<~RUBY)
def foo
(x || y)
^^^^^^^^ Don't use parentheses around a logical expression.
end
RUBY
expect_correction(<<~RUBY)
def foo
x || y
end
RUBY
end
it 'registers parentheses around `&&` logical operator keywords in method definition' do
expect_offense(<<~RUBY)
def foo
(x && y)
^^^^^^^^ Don't use parentheses around a logical expression.
end
RUBY
expect_correction(<<~RUBY)
def foo
x && y
end
RUBY
end
it 'registers parentheses around `&&` followed by another `&&`' do
expect_offense(<<~RUBY)
(x && y) && z
^^^^^^^^ Don't use parentheses around a logical expression.
RUBY
expect_correction(<<~RUBY)
x && y && z
RUBY
end
it 'registers parentheses around `&&` preceded by another `&&`' do
expect_offense(<<~RUBY)
x && (y && z)
^^^^^^^^ Don't use parentheses around a logical expression.
RUBY
expect_correction(<<~RUBY)
x && y && z
RUBY
end
it 'registers parentheses around `&&` preceded and followed by another `&&`' do
expect_offense(<<~RUBY)
x && (y && z) && w
^^^^^^^^ Don't use parentheses around a logical expression.
RUBY
expect_correction(<<~RUBY)
x && y && z && w
RUBY
end
it 'registers parentheses around `&&` preceded by another `&&` and followed by `||`' do
expect_offense(<<~RUBY)
x && (y && z) || w
^^^^^^^^ Don't use parentheses around a logical expression.
RUBY
expect_correction(<<~RUBY)
x && y && z || w
RUBY
end
it 'registers parentheses around `&&` preceded by `||` and followed by another `&&`' do
expect_offense(<<~RUBY)
x || (y && z) && w
^^^^^^^^ Don't use parentheses around a logical expression.
RUBY
expect_correction(<<~RUBY)
x || y && z && w
RUBY
end
it 'accepts parentheses around `&&` followed by `||`' do
expect_no_offenses(<<~RUBY)
(x && y) || z
RUBY
end
it 'accepts parentheses around `&&` preceded by `||`' do
expect_no_offenses(<<~RUBY)
x || (y && z)
RUBY
end
it 'accepts parentheses around `&&` preceded and followed by `||`' do
expect_no_offenses(<<~RUBY)
x || (y && z) || w
RUBY
end
it 'accepts parentheses around `||` followed by `&&`' do
expect_no_offenses(<<~RUBY)
(x || y) && z
RUBY
end
it 'accepts parentheses around `||` preceded by `&&`' do
expect_no_offenses(<<~RUBY)
x && (y || z)
RUBY
end
it 'accepts parentheses around `||` preceded and followed by `&&`' do
expect_no_offenses(<<~RUBY)
x && (y || z) && w
RUBY
end
it 'accepts parentheses around arithmetic operator' do
expect_no_offenses('x - (y || z)')
end
it 'accepts parentheses around logical operator keywords (`and`, `and`, `or`)' do
expect_no_offenses('(1 and 2) and (3 or 4)')
end
it 'accepts parentheses around logical operator keywords (`or`, `or`, `and`)' do
expect_no_offenses('(1 or 2) or (3 and 4)')
end
it 'accepts parentheses around comparison operator keywords' do
# Parentheses are redundant, but respect user's intentions for readability.
expect_no_offenses('x && (y == z)')
end
it 'accepts parentheses around logical operator in splat' do
# Parentheses are redundant, but respect user's intentions for readability.
expect_no_offenses('x = *(y || z)')
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/format_string_token_spec.rb | spec/rubocop/cop/style/format_string_token_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FormatStringToken, :config do
let(:enforced_style) { :annotated }
let(:allowed_methods) { [] }
let(:allowed_patterns) { [] }
let(:mode) { :aggressive }
let(:cop_config) do
{
'EnforcedStyle' => enforced_style,
'SupportedStyles' => %i[annotated template unannotated],
'MaxUnannotatedPlaceholdersAllowed' => 0,
'AllowedMethods' => allowed_methods,
'AllowedPatterns' => allowed_patterns,
'Mode' => mode
}
end
shared_examples 'maximum allowed unannotated' do |token, correctable_sequence:|
context 'when MaxUnannotatedPlaceholdersAllowed is 1' do
before { cop_config['MaxUnannotatedPlaceholdersAllowed'] = 1 }
it 'does not register offenses for single unannotated' do
expect_no_offenses("format('%#{token}', foo)")
end
if correctable_sequence
it 'registers an offense for dual unannotated' do
expect_offense(<<~RUBY)
format('%#{token} %s', foo, bar)
^^ Prefer [...]
^^ Prefer [...]
RUBY
end
else
it 'does not register offenses for dual unannotated' do
expect_no_offenses(<<~RUBY)
format('%#{token} %s', foo, bar)
RUBY
end
end
end
context 'when MaxUnannotatedPlaceholdersAllowed is 2' do
before { cop_config['MaxUnannotatedPlaceholdersAllowed'] = 2 }
it 'does not register offenses for single unannotated' do
expect_no_offenses("format('%#{token}', foo)")
end
it 'does not register offenses for dual unannotated' do
expect_no_offenses("format('%#{token} %s', foo, bar)")
end
end
end
shared_examples 'enforced styles for format string tokens' do |token, template_correction:|
template = '%{template}'
annotated = "%<named>#{token}"
template_to_annotated = '%<template>s'
annotated_to_template = '%{named}'
context 'when enforced style is unannotated' do
let(:enforced_style) { :unannotated }
specify '#correctable_sequence?' do
expect(cop.send(:correctable_sequence?, token)).to be true
end
end
context 'when enforced style is annotated' do
let(:enforced_style) { :annotated }
specify '#correctable_sequence?' do
expect(cop.send(:correctable_sequence?, token)).to be true
end
it 'registers offenses for template style' do
expect_offense(<<~RUBY, annotated: annotated, template: template)
<<-HEREDOC
foo %{annotated} + bar %{template}
_{annotated} ^{template} Prefer annotated tokens [...]
HEREDOC
RUBY
expect_correction(<<~RUBY)
<<-HEREDOC
foo #{annotated} + bar #{template_to_annotated}
HEREDOC
RUBY
end
it 'supports dynamic string with interpolation' do
expect_offense(<<~'RUBY', annotated: annotated, template: template)
"a#{b}%{annotated} c#{d}%{template} e#{f}"
_{annotated} ^{template} Prefer annotated tokens [...]
RUBY
expect_correction(<<~RUBY)
"a\#{b}#{annotated} c\#{d}#{template_to_annotated} e\#{f}"
RUBY
end
it 'sets the enforced style to annotated after inspecting "%<a>s"' do
expect_no_offenses('"%<a>s"')
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'annotated')
end
it 'detects when the cop must be disabled to avoid offenses' do
expect_offense(<<~RUBY)
"%{a}"
^^^^ Prefer annotated tokens [...]
RUBY
expect_correction(<<~RUBY)
"%<a>s"
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it_behaves_like 'maximum allowed unannotated', token, correctable_sequence: true
end
context 'when enforced style is template' do
let(:enforced_style) { :template }
specify '#correctable_sequence?' do
expect(cop.send(:correctable_sequence?, token)).to be template_correction
end
if template_correction
it 'registers offenses for annotated style' do
expect_offense(<<~RUBY, annotated: annotated, template: template)
<<-HEREDOC
foo %{template} + bar %{annotated}
_{template} ^{annotated} Prefer template tokens [...]
HEREDOC
RUBY
expect_correction(<<~RUBY)
<<-HEREDOC
foo #{template} + bar #{annotated_to_template}
HEREDOC
RUBY
end
else
it 'does not register offenses for annotated style' do
expect_no_offenses(<<~RUBY)
<<-HEREDOC
foo %{template} + bar %{annotated}
HEREDOC
RUBY
end
end
it 'supports dynamic string with interpolation' do
if template_correction
expect_offense(<<~'RUBY', annotated: annotated, template: template)
"a#{b}%{template} c#{d}%{annotated} e#{f}"
_{template} ^{annotated} Prefer template tokens [...]
RUBY
expect_correction(<<~RUBY)
"a\#{b}#{template} c\#{d}#{annotated_to_template} e\#{f}"
RUBY
else
expect_no_offenses(<<~'RUBY')
"a#{b}%{template} c#{d}%{annotated} e#{f}"
RUBY
end
end
it 'detects when the cop must be disabled to avoid offenses' do
expect_offense(<<~RUBY)
"%<a>s"
^^^^^ Prefer template tokens [...]
RUBY
expect_correction(<<~RUBY)
"%{a}"
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it 'configures the enforced style to template after inspecting "%{a}"' do
expect_no_offenses('"%{a}"')
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'template')
end
it_behaves_like 'maximum allowed unannotated', token, correctable_sequence: template_correction
end
end
it 'ignores percent escapes' do
expect_no_offenses("format('%<hit_rate>6.2f%%', hit_rate: 12.34)")
end
it 'ignores xstr' do
expect_no_offenses('`echo "%s %<annotated>s %{template}"`')
end
it 'ignores regexp' do
expect_no_offenses('/foo bar %u/')
end
it 'ignores `%r` regexp' do
expect_no_offenses('%r{foo bar %u}')
end
%i[strptime strftime].each do |method_name|
it "ignores time format (when used as argument to #{method_name})" do
expect_no_offenses(<<~RUBY)
Time.#{method_name}('2017-12-13', '%Y-%m-%d')
RUBY
end
end
it 'ignores time format when it is stored in a variable' do
expect_no_offenses(<<~RUBY)
time_format = '%Y-%m-%d'
Time.strftime('2017-12-13', time_format)
RUBY
end
it 'ignores time format and unrelated `format` method using' do
expect_no_offenses(<<~RUBY)
Time.now.strftime('%Y-%m-%d-%H-%M-%S')
format
RUBY
end
it 'handles dstrs' do
expect_offense(<<~'RUBY')
"c#{b}%{template}"
^^^^^^^^^^^ Prefer annotated tokens (like `%<foo>s`) over template tokens (like `%{foo}`).
RUBY
expect_correction(<<~'RUBY')
"c#{b}%<template>s"
RUBY
end
it 'ignores http links' do
expect_no_offenses(<<~RUBY)
'https://ru.wikipedia.org/wiki/%D0%90_'\
'(%D0%BA%D0%B8%D1%80%D0%B8%D0%BB%D0%BB%D0%B8%D1%86%D0%B0)'
RUBY
end
it 'ignores placeholder arguments' do
expect_no_offenses(<<~RUBY)
format(
'%<day>s %<start>s-%<end>s',
day: open_house.starts_at.strftime('%a'),
start: open_house.starts_at.strftime('%l'),
end: open_house.ends_at.strftime('%l %p').strip
)
RUBY
end
it 'works inside hashes' do
expect_offense(<<~RUBY)
{ bar: format('%{foo}', foo: 'foo') }
^^^^^^ Prefer annotated tokens (like `%<foo>s`) over template tokens (like `%{foo}`).
RUBY
expect_correction(<<~RUBY)
{ bar: format('%<foo>s', foo: 'foo') }
RUBY
end
it 'supports flags and modifiers' do
expect_offense(<<~RUBY)
format('%-20s %-30s', 'foo', 'bar')
^^^^^ Prefer annotated tokens (like `%<foo>s`) over unannotated tokens (like `%s`).
^^^^^ Prefer annotated tokens (like `%<foo>s`) over unannotated tokens (like `%s`).
RUBY
expect_no_corrections
end
it 'ignores __FILE__' do
expect_no_offenses('__FILE__')
end
it_behaves_like 'enforced styles for format string tokens', 'A', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'B', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'E', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'G', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'X', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'a', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'b', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'c', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'd', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'e', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'f', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'g', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'i', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'o', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'p', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 's', template_correction: true
it_behaves_like 'enforced styles for format string tokens', 'u', template_correction: false
it_behaves_like 'enforced styles for format string tokens', 'x', template_correction: false
context 'when enforced style is annotated' do
let(:enforced_style) { :annotated }
it 'gives a helpful error message' do
expect_offense(<<~RUBY)
"%{foo}"
^^^^^^ Prefer annotated tokens (like `%<foo>s`) over template tokens (like `%{foo}`).
RUBY
expect_correction(<<~RUBY)
"%<foo>s"
RUBY
end
context 'when AllowedMethods is enabled' do
let(:allowed_methods) { ['redirect'] }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
redirect("%{foo}")
RUBY
end
it 'does not register an offense for value in nested structure' do
expect_no_offenses(<<~RUBY)
redirect("%{foo}", bye: "%{foo}")
RUBY
end
it 'registers an offense for different method call within ignored method' do
expect_offense(<<~RUBY)
redirect("%{foo}", bye: foo("%{foo}"))
^^^^^^ Prefer annotated tokens (like `%<foo>s`) over template tokens (like `%{foo}`).
RUBY
end
end
context 'when AllowedMethods is disabled' do
let(:allowed_methods) { [] }
it 'registers an offense' do
expect_offense(<<~RUBY)
redirect("%{foo}")
^^^^^^ Prefer annotated tokens (like `%<foo>s`) over template tokens (like `%{foo}`).
RUBY
end
end
context 'when AllowedPatterns is enabled' do
let(:allowed_patterns) { [/redirect/] }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
redirect("%{foo}")
RUBY
end
it 'does not register an offense for value in nested structure' do
expect_no_offenses(<<~RUBY)
redirect("%{foo}", bye: "%{foo}")
RUBY
end
it 'registers an offense for different method call within ignored method' do
expect_offense(<<~RUBY)
redirect("%{foo}", bye: foo("%{foo}"))
^^^^^^ Prefer annotated tokens (like `%<foo>s`) over template tokens (like `%{foo}`).
RUBY
end
end
context 'when AllowedPatterns is disabled' do
let(:allowed_patterns) { [] }
it 'registers an offense' do
expect_offense(<<~RUBY)
redirect("%{foo}")
^^^^^^ Prefer annotated tokens (like `%<foo>s`) over template tokens (like `%{foo}`).
RUBY
end
end
end
context 'when enforced style is template' do
let(:enforced_style) { :template }
it 'gives a helpful error message' do
expect_offense(<<~RUBY)
"%<foo>s"
^^^^^^^ Prefer template tokens (like `%{foo}`) over annotated tokens (like `%<foo>s`).
RUBY
expect_correction(<<~RUBY)
"%{foo}"
RUBY
end
end
context 'when enforced style is unannotated' do
let(:enforced_style) { :unannotated }
it 'gives a helpful error message' do
expect_offense(<<~RUBY)
"%{foo}"
^^^^^^ Prefer unannotated tokens (like `%s`) over template tokens (like `%{foo}`).
RUBY
expect_no_corrections
end
end
context 'with `Mode: conservative`' do
let(:mode) { :conservative }
%i[annotated template unannotated].each do |style|
context "when enforced style is #{style}" do
let(:enforced_style) { style }
shared_examples 'conservative' do |given_style, string|
context "with `#{string}`" do
context 'with a bare string' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
'#{string}'
RUBY
end
end
if style != given_style
%i[printf sprintf format].each do |method|
context "as an argument to `#{method}`" do
it 'registers an offense' do
expect_offense(<<~RUBY, string: string, method: method)
%{method}('%{string}', *vars)
_{method} ^{string} Prefer [...]
RUBY
end
end
end
context 'as an argument to `%`' do
it 'registers an offense' do
expect_offense(<<~RUBY, string: string)
'#{string}' % vars
^{string} Prefer [...]
RUBY
end
end
end
context 'as an argument to another method' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo('#{string}')
RUBY
end
end
end
end
it_behaves_like 'conservative', :annotated, '%<greetings>s'
it_behaves_like 'conservative', :template, '%{greetings}'
it_behaves_like 'conservative', :unannotated, '%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/block_delimiters_spec.rb | spec/rubocop/cop/style/block_delimiters_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::BlockDelimiters, :config do
shared_examples 'always accepted' do
context 'with blocks that need braces to be valid ruby' do
it 'accepts a multi-line block' do
expect_no_offenses(<<~RUBY)
puts [1, 2, 3].map { |n|
n * n
}
RUBY
end
it 'accepts a multi-line block followed by another argument' do
expect_no_offenses(<<~RUBY)
puts [1, 2, 3].map { |n|
n * n
}, 1
RUBY
end
it 'accepts a multi-line block inside a nested send' do
expect_no_offenses(<<~RUBY)
puts [0] + [1,2,3].map { |n|
n * n
}, 1
RUBY
end
it 'accepts a multi-line block inside a nested send when the block is the receiver' do
expect_no_offenses(<<~RUBY)
puts [1,2,3].map { |n|
n * n
} + [0], 1
RUBY
end
it 'accepts a multi-line block with chained method as an argument to an operator method' do
expect_no_offenses(<<~RUBY)
'Some text: %s' %
%w[foo bar].map { |v|
v.upcase
}.join(', ')
RUBY
end
it 'accepts a multi-line block with chained method as an argument to an operator method' \
'inside a kwarg' do
expect_no_offenses(<<~RUBY)
foo :bar, baz: 'Some text: %s' %
%w[foo bar].map { |v|
v.upcase
}.join(', ')
RUBY
end
context 'Ruby >= 2.7', :ruby27 do
it 'accepts a multi-line numblock' do
expect_no_offenses(<<~RUBY)
puts [1, 2, 3].map {
_1 * _1
}, 1
RUBY
end
it 'accepts a multi-line numblock inside a nested send' do
expect_no_offenses(<<~RUBY)
puts [0] + [1,2,3].map {
_1 * _1
}, 1
RUBY
end
it 'accepts a multi-line numblock inside a nested send when the block is the receiver' do
expect_no_offenses(<<~RUBY)
puts [1,2,3].map {
_1 * _1
} + [0], 1
RUBY
end
it 'accepts a multi-line numblock with chained method as an argument to an operator method' do
expect_no_offenses(<<~RUBY)
foo %
%w[bar baz].map {
_1.upcase
}.join(', ')
RUBY
end
it 'accepts a multi-line numblock with chained method as an argument to an operator method' \
'inside a kwarg' do
expect_no_offenses(<<~RUBY)
foo :bar, baz: 'Some text: %s' %
%w[foo bar].map {
_1.upcase
}.join(', ')
RUBY
end
end
context 'Ruby >= 3.4', :ruby34 do
it 'accepts a multi-line itblock' do
expect_no_offenses(<<~RUBY)
puts [1, 2, 3].map {
it * it
}, 1
RUBY
end
it 'accepts a multi-line itblock inside a nested send' do
expect_no_offenses(<<~RUBY)
puts [0] + [1,2,3].map {
it * it
}, 1
RUBY
end
it 'accepts a multi-line itblock inside a nested send when the block is the receiver' do
expect_no_offenses(<<~RUBY)
puts [1,2,3].map {
it * it
} + [0], 1
RUBY
end
it 'accepts a multi-line itblock with chained method as an argument to an operator method' do
expect_no_offenses(<<~RUBY)
foo %
%w[bar baz].map {
it.upcase
}.join(', ')
RUBY
end
it 'accepts a multi-line itblock with chained method as an argument to an operator method' \
'inside a kwarg' do
expect_no_offenses(<<~RUBY)
foo :bar, baz: 'Some text: %s' %
%w[foo bar].map {
it.upcase
}.join(', ')
RUBY
end
end
end
end
shared_examples 'syntactic styles' do
it 'registers an offense for a single line block with do-end' do
expect_offense(<<~RUBY)
each do |x| end
^^ Prefer `{...}` over `do...end` for single-line blocks.
RUBY
expect_correction(<<~RUBY)
each { |x| }
RUBY
end
it 'accepts a single line block with braces' do
expect_no_offenses('each { |x| }')
end
it 'accepts a multi-line block with do-end' do
expect_no_offenses(<<~RUBY)
each do |x|
end
RUBY
end
context 'Ruby >= 2.7', :ruby27 do
it 'registers an offense for a single line numblock with do-end' do
expect_offense(<<~RUBY)
each do _1 end
^^ Prefer `{...}` over `do...end` for single-line blocks.
RUBY
expect_correction(<<~RUBY)
each { _1 }
RUBY
end
it 'accepts a single line numblock with braces' do
expect_no_offenses('each { _1 }')
end
it 'accepts a multi-line numblock with do-end' do
expect_no_offenses(<<~RUBY)
each do
_1
end
RUBY
end
end
end
context 'EnforcedStyle: semantic' do
cop_config = {
'EnforcedStyle' => 'semantic',
'ProceduralMethods' => %w[tap],
'FunctionalMethods' => %w[let],
'AllowedMethods' => ['lambda'],
'AllowedPatterns' => ['test']
}
let(:cop_config) { cop_config }
it_behaves_like 'always accepted'
it 'accepts a multi-line block with braces if the return value is assigned' do
expect_no_offenses(<<~RUBY)
foo = map { |x|
x
}
RUBY
end
it 'accepts a multi-line block with braces if it is the return value of its scope' do
expect_no_offenses(<<~RUBY)
block do
map { |x|
x
}
end
RUBY
end
it 'accepts a multi-line block with braces when passed to a method' do
expect_no_offenses(<<~RUBY)
puts map { |x|
x
}
RUBY
end
it 'accepts a multi-line block with braces when chained' do
expect_no_offenses(<<~RUBY)
map { |x|
x
}.inspect
RUBY
end
it 'accepts a multi-line block with braces when passed to a known functional method' do
expect_no_offenses(<<~RUBY)
let(:foo) {
x
}
RUBY
end
it 'registers an offense for a multi-line block with braces if the return value is not used' do
expect_offense(<<~RUBY)
each { |x|
^ Prefer `do...end` over `{...}` for procedural blocks.
x
}
RUBY
expect_correction(<<~RUBY)
each do |x|
x
end
RUBY
end
it 'registers an offense for a multi-line block with do-end if the return value is assigned' do
expect_offense(<<~RUBY)
foo = map do |x|
^^ Prefer `{...}` over `do...end` for functional blocks.
x
end
RUBY
expect_correction(<<~RUBY)
foo = map { |x|
x
}
RUBY
end
it 'registers an offense for a multi-line block with do-end if the ' \
'return value is passed to a method' do
expect_offense(<<~RUBY)
puts (map do |x|
^^ Prefer `{...}` over `do...end` for functional blocks.
x
end)
RUBY
expect_correction(<<~RUBY)
puts (map { |x|
x
})
RUBY
end
it 'registers an offense for a multi-line block with do-end if the ' \
'return value is attribute-assigned' do
expect_offense(<<~RUBY)
foo.bar = map do |x|
^^ Prefer `{...}` over `do...end` for functional blocks.
x
end
RUBY
expect_correction(<<~RUBY)
foo.bar = map { |x|
x
}
RUBY
end
it 'accepts a multi-line block with do-end if it is the return value of its scope' do
expect_no_offenses(<<~RUBY)
block do
map do |x|
x
end
end
RUBY
end
it 'accepts a single line block with {} if used in an if statement' do
expect_no_offenses('return if any? { |x| x }')
end
it 'accepts a single line block with {} if used in an `if` condition' do
expect_no_offenses(<<~RUBY)
if any? { |x| x }
return
end
RUBY
end
it 'accepts a single line block with {} if used in an `unless` condition' do
expect_no_offenses(<<~RUBY)
unless any? { |x| x }
return
end
RUBY
end
it 'accepts a single line block with {} if used in a `case` condition' do
expect_no_offenses(<<~RUBY)
case foo { |x| x }
when bar
end
RUBY
end
it 'accepts a single line block with {} if used in a `case` match condition' do
expect_no_offenses(<<~RUBY)
case foo { |x| x }
in bar
end
RUBY
end
it 'accepts a single line block with {} if used in a `while` condition' do
expect_no_offenses(<<~RUBY)
while foo { |x| x }
end
RUBY
end
it 'accepts a single line block with {} if used in an `until` condition' do
expect_no_offenses(<<~RUBY)
until foo { |x| x }
end
RUBY
end
it 'accepts a single line block with {} if used in a logical or' do
expect_no_offenses('any? { |c| c } || foo')
end
it 'accepts a single line block with {} if used in a logical and' do
expect_no_offenses('any? { |c| c } && foo')
end
it 'accepts a single line block with {} if used in an array' do
expect_no_offenses('[detect { true }, other]')
end
it 'accepts a single line block with {} if used in an irange' do
expect_no_offenses('detect { true }..other')
end
it 'accepts a single line block with {} if used in an erange' do
expect_no_offenses('detect { true }...other')
end
it 'accepts a single line block with {} followed by a safe navigation method call' do
expect_no_offenses('ary.map { |e| foo(e) }&.bar')
end
it 'accepts a multi-line functional block with do-end if it is a known procedural method' do
expect_no_offenses(<<~RUBY)
foo = bar.tap do |x|
x.age = 3
end
RUBY
end
it 'accepts a multi-line functional block with do-end if it is an ignored method' do
expect_no_offenses(<<~RUBY)
foo = lambda do
puts 42
end
RUBY
end
it 'accepts a multi-line functional block with do-end if it is an ignored method by regex' do
expect_no_offenses(<<~RUBY)
foo = test_method do
puts 42
end
RUBY
end
context 'with a procedural one-line block' do
context 'with AllowBracesOnProceduralOneLiners false or unset' do
it 'registers an offense for a single line procedural block' do
expect_offense(<<~RUBY)
each { |x| puts x }
^ Prefer `do...end` over `{...}` for procedural blocks.
RUBY
expect_correction(<<~RUBY)
each do |x| puts x end
RUBY
end
it 'accepts a single line block with do-end if it is procedural' do
expect_no_offenses('each do |x| puts x; end')
end
end
context 'with AllowBracesOnProceduralOneLiners true' do
let(:cop_config) { cop_config.merge('AllowBracesOnProceduralOneLiners' => true) }
it 'accepts a single line procedural block with braces' do
expect_no_offenses('each { |x| puts x }')
end
it 'accepts a single line procedural do-end block' do
expect_no_offenses('each do |x| puts x; end')
end
end
end
context 'with a procedural multi-line block' do
it 'autocorrects { and } to do and end' do
expect_offense(<<~RUBY)
each { |x|
^ Prefer `do...end` over `{...}` for procedural blocks.
x
}
RUBY
expect_correction(<<~RUBY)
each do |x|
x
end
RUBY
end
it 'autocorrects { and } to do and end with appropriate spacing' do
expect_offense(<<~RUBY)
each {|x|
^ Prefer `do...end` over `{...}` for procedural blocks.
x
}
RUBY
expect_correction(<<~RUBY)
each do |x|
x
end
RUBY
end
end
it 'allows {} if it is a known functional method' do
expect_no_offenses(<<~RUBY)
let(:foo) { |x|
x
}
RUBY
end
it 'allows {} if it is a known procedural method' do
expect_no_offenses(<<~RUBY)
foo = bar.tap do |x|
x.age = 1
end
RUBY
end
it 'autocorrects do-end to {} with appropriate spacing' do
expect_offense(<<~RUBY)
foo = map do|x|
^^ Prefer `{...}` over `do...end` for functional blocks.
x
end
RUBY
expect_correction(<<~RUBY)
foo = map { |x|
x
}
RUBY
end
it 'autocorrects do-end with `rescue` to {} if it is a functional block' do
expect_offense(<<~RUBY)
x = map do |a|
^^ Prefer `{...}` over `do...end` for functional blocks.
do_something
rescue StandardError => e
puts 'oh no'
end
RUBY
expect_correction(<<~RUBY)
x = map { |a|
begin
do_something
rescue StandardError => e
puts 'oh no'
end
}
RUBY
end
it 'autocorrects do-end with `ensure` to {} if it is a functional block' do
expect_offense(<<~RUBY)
x = map do |a|
^^ Prefer `{...}` over `do...end` for functional blocks.
do_something
ensure
puts 'oh no'
end
RUBY
expect_correction(<<~RUBY)
x = map { |a|
begin
do_something
ensure
puts 'oh no'
end
}
RUBY
end
end
context 'EnforcedStyle: line_count_based' do
cop_config = {
'EnforcedStyle' => 'line_count_based',
'AllowedMethods' => ['proc'],
'AllowedPatterns' => ['test']
}
let(:cop_config) { cop_config }
it_behaves_like 'always accepted'
it_behaves_like 'syntactic styles'
it 'autocorrects do-end for single line blocks to { and }' do
expect_offense(<<~RUBY)
block do |x| end
^^ Prefer `{...}` over `do...end` for single-line blocks.
RUBY
expect_correction(<<~RUBY)
block { |x| }
RUBY
end
it 'does not autocorrect do-end if {} would change the meaning' do
expect_offense(<<~RUBY)
s.subspec 'Subspec' do |sp| end
^^ Prefer `{...}` over `do...end` for single-line blocks.
RUBY
expect_no_corrections
end
it 'does not autocorrect {} if do-end would change the meaning' do
expect_no_offenses(<<~RUBY)
foo :bar, :baz, qux: lambda { |a|
bar a
}
RUBY
end
context 'when there are braces around a multi-line block' do
it 'registers an offense in the simple case' do
expect_offense(<<~RUBY)
each { |x|
^ Avoid using `{...}` for multi-line blocks.
}
RUBY
expect_correction(<<~RUBY)
each do |x|
end
RUBY
end
it 'registers an offense when combined with attribute assignment' do
expect_offense(<<~RUBY)
foo.bar = baz.map { |x|
^ Avoid using `{...}` for multi-line blocks.
}
RUBY
expect_correction(<<~RUBY)
foo.bar = baz.map do |x|
end
RUBY
end
it 'registers an offense when there is a comment after the closing brace and block body is not empty' do
expect_offense(<<~RUBY)
baz.map { |x|
^ Avoid using `{...}` for multi-line blocks.
foo(x) } # comment
RUBY
expect_correction(<<~RUBY)
# comment
baz.map do |x|
foo(x) end
RUBY
end
it 'registers an offense when there is a comment after the closing brace and bracket' do
expect_offense(<<~RUBY)
[foo {
^ Avoid using `{...}` for multi-line blocks.
}] # comment
RUBY
expect_correction(<<~RUBY)
[# comment
foo do
end]
RUBY
end
it 'registers an offense and keep chained block when there is a comment after the closing brace and block body is not empty' do
expect_offense(<<~RUBY)
baz.map { |x|
^ Avoid using `{...}` for multi-line blocks.
foo(x) }.map { |x| x.quux } # comment
RUBY
expect_correction(<<~RUBY)
# comment
baz.map do |x|
foo(x) end.map { |x| x.quux }
RUBY
end
it 'registers an offense when there is a comment after the closing brace and using method chain' do
expect_offense(<<~RUBY)
baz.map { |x|
^ Avoid using `{...}` for multi-line blocks.
foo(x) }.qux.quux # comment
RUBY
expect_correction(<<~RUBY)
# comment
baz.map do |x|
foo(x) end.qux.quux
RUBY
end
it 'registers an offense when there is a comment after the closing brace and block body is empty' do
expect_offense(<<~RUBY)
baz.map { |x|
^ Avoid using `{...}` for multi-line blocks.
} # comment
RUBY
expect_correction(<<~RUBY)
# comment
baz.map do |x|
end
RUBY
end
it 'accepts braces if do-end would change the meaning' do
expect_no_offenses(<<~RUBY)
scope :foo, lambda { |f|
where(condition: "value")
}
expect { something }.to raise_error(ErrorClass) { |error|
# ...
}
expect { x }.to change {
Counter.count
}.from(0).to(1)
cr.stubs client: mock {
expects(:email_disabled=).with(true)
expects :save
}
RUBY
end
it 'accepts braces with safe navigation if do-end would change the meaning' do
expect_no_offenses(<<~RUBY)
foo&.bar baz {
y
}
RUBY
end
it 'accepts braces with chained safe navigation if do-end would change the meaning' do
expect_no_offenses(<<~RUBY)
foo.bar baz {
y
}&.quux
RUBY
end
it 'accepts a multi-line functional block with {} if it is an ignored method' do
expect_no_offenses(<<~RUBY)
foo = proc {
puts 42
}
RUBY
end
it 'accepts a multi-line functional block with {} if it is an ignored method by regex' do
expect_no_offenses(<<~RUBY)
foo = test_method {
puts 42
}
RUBY
end
it 'registers an offense for braces if do-end would not change the meaning' do
expect_offense(<<~RUBY)
scope :foo, (lambda { |f|
^ Avoid using `{...}` for multi-line blocks.
where(condition: "value")
})
expect { something }.to(raise_error(ErrorClass) { |error|
^ Avoid using `{...}` for multi-line blocks.
# ...
})
RUBY
expect_correction(<<~RUBY)
scope :foo, (lambda do |f|
where(condition: "value")
end)
expect { something }.to(raise_error(ErrorClass) do |error|
# ...
end)
RUBY
end
it 'can handle special method names such as []= and done?' do
expect_offense(<<~RUBY)
h2[k2] = Hash.new { |h3,k3|
^ Avoid using `{...}` for multi-line blocks.
h3[k3] = 0
}
x = done? list.reject { |e|
e.nil?
}
RUBY
expect_correction(<<~RUBY)
h2[k2] = Hash.new do |h3,k3|
h3[k3] = 0
end
x = done? list.reject { |e|
e.nil?
}
RUBY
end
it 'autocorrects { and } to do and end' do
expect_offense(<<~RUBY)
each{ |x|
^ Avoid using `{...}` for multi-line blocks.
some_method
other_method
}
RUBY
expect_correction(<<~RUBY)
each do |x|
some_method
other_method
end
RUBY
end
it 'autocorrects adjacent curly braces correctly' do
expect_offense(<<~RUBY)
(0..3).each { |a| a.times {
^ Avoid using `{...}` for multi-line blocks.
^ Avoid using `{...}` for multi-line blocks.
puts a
}}
RUBY
expect_correction(<<~RUBY)
(0..3).each do |a| a.times do
puts a
end end
RUBY
end
it 'does not register an offense for a multi-line block with `{` and `}` with method chain' do
expect_no_offenses(<<~RUBY)
foo bar + baz {
}.qux.quux
RUBY
end
it 'does not register an offense for a multi-line block with `{` and `}` with method chain and safe navigation' do
expect_no_offenses(<<~RUBY)
foo x&.bar + baz {
}.qux.quux
RUBY
end
it 'does not register an offense when multi-line blocks to `{` and `}` with arithmetic operation method chain' do
expect_no_offenses(<<~RUBY)
foo bar + baz {
}.qux + quux
RUBY
end
it 'does not autocorrect {} if do-end would introduce a syntax error' do
expect_no_offenses(<<~RUBY)
my_method :arg1, arg2: proc {
something
}, arg3: :another_value
RUBY
end
it 'handles a multiline {} block with trailing comment' do
expect_offense(<<~RUBY)
my_method { |x|
^ Avoid using `{...}` for multi-line blocks.
x.foo } unless bar # comment
RUBY
expect_correction(<<~RUBY)
# comment
my_method do |x|
x.foo end unless bar
RUBY
end
end
context 'with a single line do-end block with an inline `rescue`' do
it 'autocorrects properly' do
expect_offense(<<~RUBY)
map do |x| x.y? rescue z end
^^ Prefer `{...}` over `do...end` for single-line blocks.
RUBY
expect_correction(<<~RUBY)
map { |x| x.y? rescue z }
RUBY
end
end
context 'with a single line do-end block with an inline `rescue` without a semicolon before `rescue`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo do next unless bar rescue StandardError; end
^^ Prefer `{...}` over `do...end` for single-line blocks.
RUBY
expect_correction(<<~RUBY)
foo { next unless bar rescue StandardError; }
RUBY
end
end
context 'with a single line do-end block with an inline `rescue` with a semicolon before `rescue`' do
it 'does not register an offense' do
# NOTE: `foo { next unless bar; rescue StandardError; }` is a syntax error.
expect_no_offenses(<<~RUBY)
foo do next unless bar; rescue StandardError; end
RUBY
end
end
end
context 'EnforcedStyle: braces_for_chaining' do
cop_config = {
'EnforcedStyle' => 'braces_for_chaining',
'AllowedMethods' => ['proc'],
'AllowedPatterns' => ['test']
}
let(:cop_config) { cop_config }
it_behaves_like 'always accepted'
it_behaves_like 'syntactic styles'
it 'registers an offense for multi-line chained do-end blocks' do
expect_offense(<<~RUBY)
each do |x|
^^ Prefer `{...}` over `do...end` for multi-line chained blocks.
end.map(&:to_s)
RUBY
expect_correction(<<~RUBY)
each { |x|
}.map(&:to_s)
RUBY
end
it 'accepts a multi-line functional block with {} if it is an ignored method' do
expect_no_offenses(<<~RUBY)
foo = proc {
puts 42
}
RUBY
end
it 'accepts a multi-line functional block with {} if it is an ignored method by regex' do
expect_no_offenses(<<~RUBY)
foo = test_method {
puts 42
}
RUBY
end
it 'allows when :[] is chained' do
expect_no_offenses(<<~RUBY)
foo = [{foo: :bar}].find { |h|
h.key?(:foo)
}[:foo]
RUBY
end
it 'allows do/end inside Hash[]' do
expect_no_offenses(<<~RUBY)
Hash[
{foo: :bar}.map do |k, v|
[k, v]
end
]
RUBY
end
it 'allows chaining to } inside of Hash[]' do
expect_no_offenses(<<~RUBY)
Hash[
{foo: :bar}.map { |k, v|
[k, v]
}.uniq
]
RUBY
end
it 'disallows {} with no chain inside of Hash[]' do
expect_offense(<<~RUBY)
Hash[
{foo: :bar}.map { |k, v|
^ Prefer `do...end` for multi-line blocks without chaining.
[k, v]
}
]
RUBY
expect_correction(<<~RUBY)
Hash[
{foo: :bar}.map do |k, v|
[k, v]
end
]
RUBY
end
context 'when there are braces around a multi-line block' do
it 'registers an offense in the simple case' do
expect_offense(<<~RUBY)
each { |x|
^ Prefer `do...end` for multi-line blocks without chaining.
}
RUBY
expect_correction(<<~RUBY)
each do |x|
end
RUBY
end
it 'registers an offense when combined with attribute assignment' do
expect_offense(<<~RUBY)
foo.bar = baz.map { |x|
^ Prefer `do...end` for multi-line blocks without chaining.
}
RUBY
expect_correction(<<~RUBY)
foo.bar = baz.map do |x|
end
RUBY
end
it 'allows when the block is being chained' do
expect_no_offenses(<<~RUBY)
each { |x|
}.map(&:to_sym)
RUBY
end
it 'allows when the block is being chained with attribute assignment' do
expect_no_offenses(<<~RUBY)
foo.bar = baz.map { |x|
}.map(&:to_sym)
RUBY
end
end
context 'with safe navigation' do
it 'registers an offense for multi-line chained do-end blocks' do
expect_offense(<<~RUBY)
arr&.each do |x|
^^ Prefer `{...}` over `do...end` for multi-line chained blocks.
end&.map(&:to_s)
RUBY
expect_correction(<<~RUBY)
arr&.each { |x|
}&.map(&:to_s)
RUBY
end
end
it 'autocorrects do-end with `rescue` to {} if it is a functional block' do
expect_offense(<<~RUBY)
map do |a|
^^ Prefer `{...}` over `do...end` for multi-line chained blocks.
do_something
rescue StandardError => e
puts 'oh no'
end.join('-')
RUBY
expect_correction(<<~RUBY)
map { |a|
begin
do_something
rescue StandardError => e
puts 'oh no'
end
}.join('-')
RUBY
end
it 'autocorrects do-end with `ensure` to {} if it is a functional block' do
expect_offense(<<~RUBY)
map do |a|
^^ Prefer `{...}` over `do...end` for multi-line chained blocks.
do_something
ensure
puts 'oh no'
end.join('-')
RUBY
expect_correction(<<~RUBY)
map { |a|
begin
do_something
ensure
puts 'oh no'
end
}.join('-')
RUBY
end
end
context 'EnforcedStyle: always_braces' do
cop_config = {
'EnforcedStyle' => 'always_braces',
'AllowedMethods' => ['proc'],
'AllowedPatterns' => ['test']
}
let(:cop_config) { cop_config }
it_behaves_like 'always accepted'
it 'registers an offense for a single line block with do-end' do
expect_offense(<<~RUBY)
each do |x| end
^^ Prefer `{...}` over `do...end` for blocks.
RUBY
expect_correction(<<~RUBY)
each { |x| }
RUBY
end
it 'accepts a single line block with braces' do
expect_no_offenses('each { |x| }')
end
it 'registers an offense for a multi-line block with do-end' do
expect_offense(<<~RUBY)
each do |x|
^^ Prefer `{...}` over `do...end` for blocks.
end
RUBY
expect_correction(<<~RUBY)
each { |x|
}
RUBY
end
it 'does not autocorrect do-end if {} would change the meaning' do
expect_offense(<<~RUBY)
s.subspec 'Subspec' do |sp| end
^^ Prefer `{...}` over `do...end` for blocks.
RUBY
expect_no_corrections
end
it 'accepts a multi-line block that needs braces to be valid ruby' do
expect_no_offenses(<<~RUBY)
puts [1, 2, 3].map { |n|
n * n
}, 1
RUBY
end
it 'registers an offense for multi-line chained do-end blocks' do
expect_offense(<<~RUBY)
each do |x|
^^ Prefer `{...}` over `do...end` for blocks.
end.map(&:to_s)
RUBY
expect_correction(<<~RUBY)
each { |x|
}.map(&:to_s)
RUBY
end
it 'registers an offense for multi-lined do-end blocks when combined ' \
'with attribute assignment' do
expect_offense(<<~RUBY)
foo.bar = baz.map do |x|
^^ Prefer `{...}` over `do...end` for blocks.
end
RUBY
expect_correction(<<~RUBY)
foo.bar = baz.map { |x|
}
RUBY
end
it 'accepts a multi-line functional block with do-end if it is an ignored method' do
expect_no_offenses(<<~RUBY)
foo = proc do
puts 42
end
RUBY
end
it 'accepts a multi-line functional block with do-end if it is an ignored method by regex' do
expect_no_offenses(<<~RUBY)
foo = test_method do
puts 42
end
RUBY
end
context 'when there are braces around a multi-line block' do
it 'allows in the simple case' do
expect_no_offenses(<<~RUBY)
each { |x|
}
RUBY
end
it 'allows when combined with attribute assignment' do
expect_no_offenses(<<~RUBY)
foo.bar = baz.map { |x|
}
RUBY
end
it 'allows when the block is being chained' do
expect_no_offenses(<<~RUBY)
each { |x|
}.map(&:to_sym)
RUBY
end
end
it 'autocorrects do-end with `rescue` to {} if it is a functional block' do
expect_offense(<<~RUBY)
map do |a|
^^ Prefer `{...}` over `do...end` for blocks.
do_something
rescue StandardError => e
puts 'oh no'
end
RUBY
expect_correction(<<~RUBY)
map { |a|
begin
do_something
rescue StandardError => e
puts 'oh no'
end
}
RUBY
end
it 'autocorrects do-end with `ensure` to {} if it is a functional block' do
expect_offense(<<~RUBY)
map do |a|
^^ Prefer `{...}` over `do...end` for blocks.
do_something
ensure
puts 'oh no'
end
RUBY
expect_correction(<<~RUBY)
map { |a|
begin
do_something
ensure
puts 'oh no'
end
}
RUBY
end
end
context 'BracesRequiredMethods' do
cop_config = { 'EnforcedStyle' => 'line_count_based', 'BracesRequiredMethods' => %w[sig] }
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/static_class_spec.rb | spec/rubocop/cop/style/static_class_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StaticClass, :config do
it 'registers an offense when class has only class method' do
expect_offense(<<~RUBY)
class C
^^^^^^^ Prefer modules to classes with only class methods.
def self.class_method; end
end
RUBY
expect_correction(<<~RUBY)
module C
module_function
def class_method; end
end
RUBY
end
it 'registers an offense when class has `class << self` with class methods' do
expect_offense(<<~RUBY)
class C
^^^^^^^ Prefer modules to classes with only class methods.
def self.class_method; end
class << self
def other_class_method; end
end
end
RUBY
expect_correction(<<~RUBY)
module C
module_function
def class_method; end
#{trailing_whitespace}
def other_class_method; end
#{trailing_whitespace}
end
RUBY
end
it 'does not register an offense when class has `class << self` with macro calls' do
expect_no_offenses(<<~RUBY)
class C
def self.class_method; end
class << self
macro_method
end
end
RUBY
end
it 'registers an offense when class has assignments along with class methods' do
expect_offense(<<~RUBY)
class C
^^^^^^^ Prefer modules to classes with only class methods.
CONST = 1
def self.class_method; end
end
RUBY
expect_correction(<<~RUBY)
module C
module_function
CONST = 1
def class_method; end
end
RUBY
end
it 'does not register an offense when class has instance method' do
expect_no_offenses(<<~RUBY)
class C
def self.class_method; end
def instance_method; end
end
RUBY
end
it 'does not register an offense when class has macro-like method' do
expect_no_offenses(<<~RUBY)
class C
def self.class_method; end
macro_method
end
RUBY
end
it 'does not register an offense when class is empty' do
expect_no_offenses(<<~RUBY)
class C
end
RUBY
end
it 'does not register an offense when class has a parent' do
expect_no_offenses(<<~RUBY)
class C < B
def self.class_method; end
end
RUBY
end
it 'does not register an offense when class includes/prepends a module' do
expect_no_offenses(<<~RUBY)
class C
include M
def self.class_method; end
end
class C
prepend M
def self.class_method; end
end
RUBY
end
it 'registers an offense when class extends a module' do
expect_offense(<<~RUBY)
class C
^^^^^^^ Prefer modules to classes with only class methods.
extend M
def self.class_method; end
end
RUBY
expect_correction(<<~RUBY)
module C
module_function
extend M
def class_method; end
end
RUBY
end
it 'does not register an offense for modules' do
expect_no_offenses(<<~RUBY)
module C
def self.class_method; 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/redundant_self_assignment_branch_spec.rb | spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantSelfAssignmentBranch, :config do
it 'registers and corrects an offense when self-assigning redundant else ternary branch' do
expect_offense(<<~RUBY)
foo = condition ? bar : foo
^^^ Remove the self-assignment branch.
RUBY
expect_correction(<<~RUBY)
foo = bar if condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant else ternary branch and ' \
'using method call with an argument in the if ternary branch' do
expect_offense(<<~RUBY)
foo = condition ? bar(arg) : foo
^^^ Remove the self-assignment branch.
RUBY
expect_correction(<<~RUBY)
foo = bar(arg) if condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant else ternary branch and ' \
'using a line broke method chain in the if ternary branch' do
expect_offense(<<~RUBY)
foo = condition ? bar.
baz : foo
^^^ Remove the self-assignment branch.
RUBY
expect_correction(<<~RUBY)
foo = bar.
baz if condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant else ternary branch and ' \
'using an empty parentheses in the if ternary branch' do
expect_offense(<<~RUBY)
foo = condition ? (
) : foo
^^^ Remove the self-assignment branch.
RUBY
expect_correction(<<~RUBY)
foo = (
) if condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant if ternary branch' do
expect_offense(<<~RUBY)
foo = condition ? foo : bar
^^^ Remove the self-assignment branch.
RUBY
expect_correction(<<~RUBY)
foo = bar unless condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant else branch' do
expect_offense(<<~RUBY)
foo = if condition
bar
else
foo
^^^ Remove the self-assignment branch.
end
RUBY
expect_correction(<<~RUBY)
foo = bar if condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant if branch' do
expect_offense(<<~RUBY)
foo = if condition
foo
^^^ Remove the self-assignment branch.
else
bar
end
RUBY
expect_correction(<<~RUBY)
foo = bar unless condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant if branch with heredoc' do
expect_offense(<<~RUBY)
foo = if condition
foo
^^^ Remove the self-assignment branch.
else
<<~TEXT
bar
TEXT
end
RUBY
expect_correction(<<~RUBY)
foo = <<~TEXT unless condition
bar
TEXT
RUBY
end
it 'does not register an offense when self-assigning redundant else branch and multiline if branch' do
expect_no_offenses(<<~RUBY)
foo = if condition
bar
baz
else
foo
end
RUBY
end
it 'does not register an offense when self-assigning redundant else branch and multiline else branch' do
expect_no_offenses(<<~RUBY)
foo = if condition
foo
else
bar
baz
end
RUBY
end
it 'registers and corrects an offense when self-assigning redundant else branch and empty if branch' do
expect_offense(<<~RUBY)
foo = if condition
else
foo
^^^ Remove the self-assignment branch.
end
RUBY
expect_correction(<<~RUBY)
foo = nil if condition
RUBY
end
it 'registers and corrects an offense when self-assigning redundant else branch and empty else branch' do
expect_offense(<<~RUBY)
foo = if condition
foo
^^^ Remove the self-assignment branch.
else
end
RUBY
expect_correction(<<~RUBY)
foo = nil unless condition
RUBY
end
it 'does not register an offense when self-assigning redundant else ternary branch for ivar' do
expect_no_offenses(<<~RUBY)
@foo = condition ? @bar : @foo
RUBY
end
it 'does not register an offense when self-assigning redundant else ternary branch for cvar' do
expect_no_offenses(<<~RUBY)
@@foo = condition ? @@bar : @@foo
RUBY
end
it 'does not register an offense when self-assigning redundant else ternary branch for gvar' do
expect_no_offenses(<<~RUBY)
$foo = condition ? $bar : $foo
RUBY
end
it 'does not register an offense when not self-assigning redundant branches' do
expect_no_offenses(<<~RUBY)
foo = condition ? bar : baz
RUBY
end
it 'does not register an offense when using only if branch' do
expect_no_offenses(<<~RUBY)
foo = if condition
bar
end
RUBY
end
it 'does not register an offense when multi assignment' do
expect_no_offenses(<<~RUBY)
foo, bar = baz
RUBY
end
# Ignore method calls as they can have side effects. In other words, it may be unsafe detection.
it 'does not register an offense when lhs is not variable' do
expect_no_offenses(<<~RUBY)
foo.do_something = condition ? foo.do_something : bar.do_something
RUBY
end
it 'does not register an offense when using `elsif` and self-assigning the value of `then` branch' do
expect_no_offenses(<<~RUBY)
foo = if condition
foo
elsif another_condition
bar
else
baz
end
RUBY
end
it 'does not register an offense when using `elsif` and self-assigning the value of `elsif` branch' do
expect_no_offenses(<<~RUBY)
foo = if condition
bar
elsif another_condition
foo
else
baz
end
RUBY
end
it 'does not register an offense when using `elsif` and self-assigning the value of `else` branch' do
expect_no_offenses(<<~RUBY)
foo = if condition
bar
elsif another_condition
baz
else
foo
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/numbered_parameters_spec.rb | spec/rubocop/cop/style/numbered_parameters_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NumberedParameters, :config do
context '>= Ruby 2.7', :ruby27 do
context 'EnforcedStyle: allow_single_line' do
let(:cop_config) { { 'EnforcedStyle' => 'allow_single_line' } }
it 'registers an offense when using numbered parameters with multi-line blocks' do
expect_offense(<<~RUBY)
collection.each do
^^^^^^^^^^^^^^^^^^ Avoid using numbered parameters for multi-line blocks.
puts _1
end
RUBY
end
it 'registers no offense when using numbered parameters with multi-line method chain' do
expect_no_offenses(<<~RUBY)
collection.each
.foo { puts _1 }
RUBY
end
it 'does not register an offense when using numbered parameters with single-line blocks' do
expect_no_offenses(<<~RUBY)
collection.each { puts _1 }
RUBY
end
end
context 'EnforcedStyle: disallow' do
let(:cop_config) { { 'EnforcedStyle' => 'disallow' } }
it 'does an offense when using numbered parameters even with single-line blocks' do
expect_offense(<<~RUBY)
collection.each { puts _1 }
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using numbered parameters.
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/string_literals_in_interpolation_spec.rb | spec/rubocop/cop/style/string_literals_in_interpolation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StringLiteralsInInterpolation, :config do
context 'configured with single quotes preferred' do
let(:cop_config) { { 'EnforcedStyle' => 'single_quotes' } }
it 'registers an offense for double quotes within embedded expression in a string' do
expect_offense(<<~'RUBY')
"#{"A"}"
^^^ Prefer single-quoted strings inside interpolations.
RUBY
expect_correction(<<~'RUBY')
"#{'A'}"
RUBY
end
it 'registers an offense for double quotes within embedded expression in a symbol' do
expect_offense(<<~'RUBY')
:"#{"A"}"
^^^ Prefer single-quoted strings inside interpolations.
RUBY
expect_correction(<<~'RUBY')
:"#{'A'}"
RUBY
end
it 'registers an offense for double quotes within embedded expression in a heredoc string' do
expect_offense(<<~'SOURCE')
<<RUBY
#{"A"}
^^^ Prefer single-quoted strings inside interpolations.
RUBY
SOURCE
expect_correction(<<~'SOURCE')
<<RUBY
#{'A'}
RUBY
SOURCE
end
it 'registers an offense for double quotes within a regexp' do
expect_offense(<<~'RUBY')
/foo#{"sar".sub("s", 'b')}/
^^^^^ Prefer single-quoted strings inside interpolations.
^^^ Prefer single-quoted strings inside interpolations.
RUBY
expect_correction(<<~'RUBY')
/foo#{'sar'.sub('s', 'b')}/
RUBY
end
it 'accepts double quotes on a static string' do
expect_no_offenses('"A"')
end
it 'accepts double quotes on a broken static string' do
expect_no_offenses(<<~'RUBY')
"A" \
"B"
RUBY
end
it 'accepts double quotes on static strings within a method' do
expect_no_offenses(<<~RUBY)
def m
puts "A"
puts "B"
end
RUBY
end
it 'can handle a built-in constant parsed as string' do
# Parser will produce str nodes for constants such as __FILE__.
expect_no_offenses(<<~RUBY)
if __FILE__ == $PROGRAM_NAME
end
RUBY
end
it 'can handle character literals' do
expect_no_offenses('a = ?/')
end
end
context 'configured with double quotes preferred' do
let(:cop_config) { { 'EnforcedStyle' => 'double_quotes' } }
it 'registers an offense for single quotes within embedded expression in a string' do
expect_offense(<<~'RUBY')
"#{'A'}"
^^^ Prefer double-quoted strings inside interpolations.
RUBY
expect_correction(<<~'RUBY')
"#{"A"}"
RUBY
end
it 'registers an offense for single quotes within embedded expression in a symbol' do
expect_offense(<<~'RUBY')
:"#{'A'}"
^^^ Prefer double-quoted strings inside interpolations.
RUBY
expect_correction(<<~'RUBY')
:"#{"A"}"
RUBY
end
it 'registers an offense for single quotes within embedded expression in a heredoc string' do
expect_offense(<<~'SOURCE')
<<RUBY
#{'A'}
^^^ Prefer double-quoted strings inside interpolations.
RUBY
SOURCE
expect_correction(<<~'SOURCE')
<<RUBY
#{"A"}
RUBY
SOURCE
end
end
context 'when configured with a bad value' do
let(:cop_config) { { 'EnforcedStyle' => 'other' } }
it 'fails' do
expect { expect_no_offenses('a = "#{"b"}"') }.to raise_error(RuntimeError)
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/copyright_spec.rb | spec/rubocop/cop/style/copyright_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Copyright, :config do
let(:cop_config) { { 'Notice' => 'Copyright (\(c\) )?2015 Acme Inc' } }
it 'does not register an offense when the notice is present' do
expect_no_offenses(<<~RUBY)
# Copyright 2015 Acme Inc.
# test2
names = Array.new
names << 'James'
RUBY
end
it 'does not register an offense when the notice is not the first comment' do
expect_no_offenses(<<~RUBY)
# test2
# Copyright 2015 Acme Inc.
names = Array.new
names << 'James'
RUBY
end
it 'does not register an offense when the notice is in a block comment' do
expect_no_offenses(<<~RUBY)
=begin
blah, blah, blah
Copyright 2015 Acme Inc.
=end
names = Array.new
names << 'James'
RUBY
end
context 'when multiline copyright notice' do
let(:cop_config) do
{
'Notice' => <<~'COPYRIGHT'
Copyright (\(c\) )?2015 Acme Inc.
License details\.\.\.
COPYRIGHT
}
end
it 'does not register an offense when the multiline copyright notice is present' do
cop_config['AutocorrectNotice'] = <<~COPYRIGHT
# Copyright (c) 2015 Acme Inc.
#
# License details...
COPYRIGHT
expect_no_offenses(<<~RUBY)
# Copyright 2015 Acme Inc.
#
# License details...
class Foo
end
RUBY
end
it 'registers an offense when the multiline copyright notice is missing' do
cop_config['AutocorrectNotice'] = <<~COPYRIGHT
# Copyright (c) 2015 Acme Inc.
#
# License details...
COPYRIGHT
expect_offense(<<~RUBY)
# Comment
^ Include a copyright notice matching [...]
class Foo
end
RUBY
expect_correction(<<~RUBY)
# Copyright (c) 2015 Acme Inc.
#
# License details...
# Comment
class Foo
end
RUBY
end
end
context 'when the copyright notice is missing' do
let(:source) { <<~RUBY }
# test
^ Include a copyright notice matching [...]
# test2
names = Array.new
names << 'James'
RUBY
it 'adds an offense' do
cop_config['AutocorrectNotice'] = '# Copyright (c) 2015 Acme Inc.'
expect_offense(source)
expect_correction(<<~RUBY)
# Copyright (c) 2015 Acme Inc.
# test
# test2
names = Array.new
names << 'James'
RUBY
end
it 'fails to autocorrect when the AutocorrectNotice does not match the Notice pattern' do
cop_config['AutocorrectNotice'] = '# Copyleft (c) 2015 Acme Inc.'
expect { expect_offense(source) }.to raise_error(RuboCop::Warning, %r{Style/Copyright:})
end
it 'fails to autocorrect if no AutocorrectNotice is given' do
cop_config['AutocorrectNotice'] = nil
expect { expect_offense(source) }.to raise_error(RuboCop::Warning, %r{Style/Copyright:})
end
end
context 'when the copyright notice comes after any code' do
it 'adds an offense' do
cop_config['AutocorrectNotice'] = '# Copyright (c) 2015 Acme Inc.'
expect_offense(<<~RUBY)
# test2
^ Include a copyright notice matching [...]
names = Array.new
# Copyright (c) 2015 Acme Inc.
names << 'James'
RUBY
expect_correction(<<~RUBY)
# Copyright (c) 2015 Acme Inc.
# test2
names = Array.new
# Copyright (c) 2015 Acme Inc.
names << 'James'
RUBY
end
end
context 'when the source code file is empty' do
it 'adds an offense' do
cop_config['AutocorrectNotice'] = '# Copyright (c) 2015 Acme Inc.'
expect_offense(<<~RUBY)
^{} Include a copyright notice matching [...]
RUBY
expect_no_corrections
end
end
context 'when the copyright notice is missing and the source code file starts with a shebang' do
it 'adds an offense' do
cop_config['AutocorrectNotice'] = '# Copyright (c) 2015 Acme Inc.'
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Include a copyright notice matching [...]
names = Array.new
names << 'James'
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# Copyright (c) 2015 Acme Inc.
names = Array.new
names << 'James'
RUBY
end
end
context 'when the copyright notice is missing and ' \
'the source code file starts with an encoding comment' do
it 'adds an offense' do
cop_config['AutocorrectNotice'] = '# Copyright (c) 2015 Acme Inc.'
expect_offense(<<~RUBY)
# encoding: utf-8
^ Include a copyright notice matching [...]
names = Array.new
names << 'James'
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# Copyright (c) 2015 Acme Inc.
names = Array.new
names << 'James'
RUBY
end
end
context 'when the copyright notice is missing and ' \
'the source code file starts with shebang and ' \
'an encoding comment' do
it 'adds an offense' do
cop_config['AutocorrectNotice'] = '# Copyright (c) 2015 Acme Inc.'
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Include a copyright notice matching [...]
# encoding: utf-8
names = Array.new
names << 'James'
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# Copyright (c) 2015 Acme Inc.
names = Array.new
names << 'James'
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_interpolation_spec.rb | spec/rubocop/cop/style/redundant_interpolation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantInterpolation, :config do
it 'registers an offense for "#{1 + 1}"' do
expect_offense(<<~'RUBY')
"#{1 + 1}"
^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
(1 + 1).to_s
RUBY
end
it 'registers an offense for "%|#{1 + 1}|"' do
expect_offense(<<~'RUBY')
%|#{1 + 1}|
^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
(1 + 1).to_s
RUBY
end
it 'registers an offense for "%Q(#{1 + 1})"' do
expect_offense(<<~'RUBY')
%Q(#{1 + 1})
^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
(1 + 1).to_s
RUBY
end
it 'registers an offense for "#{1 + 1; 2 + 2}"' do
expect_offense(<<~'RUBY')
"#{1 + 1; 2 + 2}"
^^^^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
(1 + 1; 2 + 2).to_s
RUBY
end
it 'registers an offense for "#{@var}"' do
expect_offense(<<~'RUBY')
"#{@var}"
^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
@var.to_s
RUBY
end
it 'registers an offense for "#@var"' do
expect_offense(<<~'RUBY')
"#@var"
^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
@var.to_s
RUBY
end
it 'registers an offense for "#{@@var}"' do
expect_offense(<<~'RUBY')
"#{@@var}"
^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
@@var.to_s
RUBY
end
it 'registers an offense for "#@@var"' do
expect_offense(<<~'RUBY')
"#@@var"
^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
@@var.to_s
RUBY
end
it 'registers an offense for "#{$var}"' do
expect_offense(<<~'RUBY')
"#{$var}"
^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
$var.to_s
RUBY
end
it 'registers an offense for "#$var"' do
expect_offense(<<~'RUBY')
"#$var"
^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
$var.to_s
RUBY
end
it 'registers an offense for "#{$1}"' do
expect_offense(<<~'RUBY')
"#{$1}"
^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
$1.to_s
RUBY
end
it 'registers an offense for "#$1"' do
expect_offense(<<~'RUBY')
"#$1"
^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
$1.to_s
RUBY
end
it 'registers an offense for "#{$+}"' do
expect_offense(<<~'RUBY')
"#{$+}"
^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
$+.to_s
RUBY
end
it 'registers an offense for "#$+"' do
expect_offense(<<~'RUBY')
"#$+"
^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
$+.to_s
RUBY
end
it 'registers an offense for "#{number}"' do
expect_offense(<<~'RUBY')
"#{number}"
^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
number.to_s
RUBY
end
it 'registers an offense for "#{do_something(42)}"' do
expect_offense(<<~'RUBY')
"#{do_something(42)}"
^^^^^^^^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
do_something(42).to_s
RUBY
end
it 'registers an offense for "#{do_something 42}"' do
expect_offense(<<~'RUBY')
"#{do_something 42}"
^^^^^^^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
do_something(42).to_s
RUBY
end
it 'registers an offense for "#{foo.do_something 42}"' do
expect_offense(<<~'RUBY')
"#{foo.do_something 42}"
^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
foo.do_something(42).to_s
RUBY
end
it 'registers an offense for "#{var}"' do
expect_offense(<<~'RUBY')
var = 1; "#{var}"
^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
var = 1; var.to_s
RUBY
end
it 'registers an offense for ["#{@var}"]' do
expect_offense(<<~'RUBY')
["#{@var}", 'foo']
^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
[@var.to_s, 'foo']
RUBY
end
it 'registers an offense for a one-line `in` pattern matching', :ruby27 do
# `42 in var` is `match-pattern` node.
expect_offense(<<~'RUBY')
"#{42 in var}"
^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
(42 in var).to_s
RUBY
end
it 'registers an offense for a one-line `in` pattern matching', :ruby30 do
# `42 in var` is `match-pattern-p` node.
expect_offense(<<~'RUBY')
"#{42 in var}"
^^^^^^^^^^^^^^ Prefer `to_s` over string interpolation.
RUBY
expect_correction(<<~RUBY)
(42 in var).to_s
RUBY
end
it 'accepts an offense for a one-line `=>` pattern matching', :ruby30 do
# `42 => var` is `match-pattern` node.
expect_no_offenses(<<~'RUBY')
"#{42 => var}"
RUBY
end
it 'accepts an offense for a part of one-line `=>` pattern matching', :ruby30 do
# `42 => var` is `match-pattern` node.
expect_no_offenses(<<~'RUBY')
"#{x; 42 => var}"
RUBY
end
it 'accepts strings with characters before the interpolation' do
expect_no_offenses('"this is #{@sparta}"')
end
it 'accepts strings with characters after the interpolation' do
expect_no_offenses('"#{@sparta} this is"')
end
it 'accepts strings implicitly concatenated with a later string' do
expect_no_offenses(%q("#{sparta}" ' this is'))
end
it 'accepts strings implicitly concatenated with an earlier string' do
expect_no_offenses(%q('this is ' "#{sparta}"))
end
it 'accepts strings that are part of a %W()' do
expect_no_offenses('%W(#{@var} foo)')
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_format_spec.rb | spec/rubocop/cop/style/redundant_format_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantFormat, :config do
%i[format sprintf].each do |method|
context "with #{method}" do
it 'does not register an offense when called with no arguments' do
expect_no_offenses(<<~RUBY)
#{method}
#{method}()
RUBY
end
it 'does not register an offense when called with additional arguments' do
expect_no_offenses(<<~RUBY)
#{method}('%s', foo)
RUBY
end
it 'does not register an offense when called with a splat' do
expect_no_offenses(<<~RUBY)
#{method}('%s', *args)
RUBY
end
it 'does not register an offense when called with a double splat' do
expect_no_offenses(<<~RUBY)
#{method}('%s', **args)
RUBY
end
it 'does not register an offense when called with a double splat with annotations' do
expect_no_offenses(<<~RUBY)
#{method}('%<username>s', **args)
RUBY
end
it 'does not register an offense when called on an object' do
expect_no_offenses(<<~RUBY)
foo.#{method}('bar')
RUBY
end
context 'when only given a single string argument' do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
%{method}('foo')
^{method}^^^^^^^ Use `'foo'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'foo'
RUBY
end
it 'registers an offense when the argument is an interpolated string' do
expect_offense(<<~'RUBY', method: method)
%{method}("#{foo}")
^{method}^^^^^^^^^^ Use `"#{foo}"` directly instead of `%{method}`.
RUBY
expect_correction(<<~'RUBY')
"#{foo}"
RUBY
end
it 'registers an offense when called with `Kernel`' do
expect_offense(<<~RUBY, method: method)
Kernel.%{method}('foo')
^^^^^^^^{method}^^^^^^^ Use `'foo'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'foo'
RUBY
end
it 'registers an offense when called with `::Kernel`' do
expect_offense(<<~RUBY, method: method)
::Kernel.%{method}('foo')
^^^^^^^^^^{method}^^^^^^^ Use `'foo'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'foo'
RUBY
end
it 'registers an offense when the argument is a control character' do
expect_offense(<<~'RUBY', method: method)
%{method}("\n")
^{method}^^^^^^ Use `"\n"` directly instead of `%{method}`.
RUBY
expect_correction(<<~'RUBY')
"\n"
RUBY
end
end
context 'with literal arguments' do
# rubocop:disable Metrics/ParameterLists
shared_examples 'offending format specifier' do |specifier, value, result, start_delim = "'", end_delim = "'", **metadata|
it 'registers an offense and corrects', **metadata do
options = {
method: method,
specifier: specifier,
value: value,
start_delim: start_delim,
end_delim: end_delim
}
expect_offense(<<~RUBY, **options)
%{method}(%{start_delim}%{specifier}%{end_delim}, %{value})
^{method}^^{start_delim}^{specifier}^{end_delim}^^^{value}^ Use `#{result}` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
#{result}
RUBY
end
end
# rubocop:enable Metrics/ParameterLists
shared_examples 'non-offending format specifier' do |specifier, value|
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
#{method}('#{specifier}', #{value})
RUBY
end
end
it_behaves_like 'offending format specifier', '%s', "'foo'", "'foo'"
it_behaves_like 'offending format specifier', '%s', "'foo'", '%{foo}', '%{', '}'
it_behaves_like 'offending format specifier', '%s', "'foo'", '%q{foo}', '%q{', '}'
it_behaves_like 'offending format specifier', '%s', "'foo'", '%Q{foo}', '%Q{', '}'
it_behaves_like 'offending format specifier', '%s', '%q{foo}', "'foo'"
it_behaves_like 'offending format specifier', '%s', '%{foo}', "'foo'"
it_behaves_like 'offending format specifier', '%s', '%Q{foo}', "'foo'"
it_behaves_like 'offending format specifier', '%s', '"#{foo}"', '"#{foo}"'
it_behaves_like 'offending format specifier', '%s', '"#{foo}"', '%{#{foo}}', '%{', '}'
it_behaves_like 'offending format specifier', '%s', '"#{foo}"', '%Q{#{foo}}', '%q{', '}'
it_behaves_like 'offending format specifier', '%s', '"#{foo}"', '%Q{#{foo}}', '%Q{', '}'
it_behaves_like 'offending format specifier', '%s', ':foo', "'foo'"
it_behaves_like 'offending format specifier', '%s', ':"#{foo}"', '"#{foo}"'
it_behaves_like 'offending format specifier', '%s', '1', "'1'"
it_behaves_like 'offending format specifier', '%s', '1.1', "'1.1'"
it_behaves_like 'offending format specifier', '%s', '1r', "'1/1'"
it_behaves_like 'offending format specifier', '%s', '1i', "'0+1i'"
it_behaves_like 'offending format specifier', '%s', 'true', "'true'"
it_behaves_like 'offending format specifier', '%s', 'false', "'false'"
it_behaves_like 'offending format specifier', '%s', 'nil', "'nil'"
it_behaves_like 'non-offending format specifier', '%s', 'foo'
it_behaves_like 'non-offending format specifier', '%s', '[]'
it_behaves_like 'non-offending format specifier', '%s', '{}'
%i[%d %i %u].each do |specifier|
it_behaves_like 'offending format specifier', specifier, '5', "'5'"
it_behaves_like 'offending format specifier', specifier, '5.5', "'5'"
it_behaves_like 'offending format specifier', specifier, '5r', "'5'"
it_behaves_like 'offending format specifier', specifier, '3/8r', "'0'"
it_behaves_like 'offending format specifier', specifier, '(3/8r)', "'0'"
it_behaves_like 'offending format specifier', specifier, '5+0i', "'5'"
it_behaves_like 'offending format specifier', specifier, '(5+0i)', "'5'"
it_behaves_like 'offending format specifier', specifier, "'5'", "'5'"
it_behaves_like 'offending format specifier', specifier, "'-5'", "'-5'"
it_behaves_like 'offending format specifier', specifier, "'-5'", "'-5'"
it_behaves_like 'non-offending format specifier', specifier, "'5.5'"
it_behaves_like 'non-offending format specifier', specifier, '"abcd"'
it_behaves_like 'non-offending format specifier', specifier, 'true'
it_behaves_like 'non-offending format specifier', specifier, 'false'
it_behaves_like 'non-offending format specifier', specifier, 'nil'
it_behaves_like 'non-offending format specifier', specifier, '[]'
it_behaves_like 'non-offending format specifier', specifier, '{}'
end
it_behaves_like 'offending format specifier', '%f', '5', "'5.000000'"
it_behaves_like 'offending format specifier', '%f', '5.5', "'5.500000'"
it_behaves_like 'offending format specifier', '%f', '5r', "'5.000000'"
it_behaves_like 'offending format specifier', '%f', '3/8r', "'0.375000'"
it_behaves_like 'offending format specifier', '%f', '(3/8r)', "'0.375000'"
it_behaves_like 'offending format specifier', '%f', '5+0i', "'5.000000'"
it_behaves_like 'offending format specifier', '%f', '(5+0i)', "'5.000000'"
it_behaves_like 'offending format specifier', '%f', "'5'", "'5.000000'"
it_behaves_like 'offending format specifier', '%f', "'-5'", "'-5.000000'"
it_behaves_like 'non-offending format specifier', '%f', '"abcd"'
it_behaves_like 'non-offending format specifier', '%f', 'true'
it_behaves_like 'non-offending format specifier', '%f', 'false'
it_behaves_like 'non-offending format specifier', '%f', 'nil'
it_behaves_like 'non-offending format specifier', '%f', '[]'
it_behaves_like 'non-offending format specifier', '%f', '{}'
# Width, precision and flags
it_behaves_like 'offending format specifier', '%10s', "'foo'", "' foo'"
it_behaves_like 'offending format specifier', '%-10s', "'foo'", "'foo '"
it_behaves_like 'offending format specifier', '%10d', '5', "' 5'"
it_behaves_like 'offending format specifier', '%-10d', '5', "'5 '"
it_behaves_like 'offending format specifier', '% d', '5', "' 5'"
it_behaves_like 'offending format specifier', '%+d', '5', "'+5'"
it_behaves_like 'offending format specifier', '%.3d', '10', "'010'"
it_behaves_like 'offending format specifier', '%.d', '0', "''"
it_behaves_like 'offending format specifier', '%05d', '5', "'00005'"
it_behaves_like 'offending format specifier', '%.2f', '5', "'5.00'"
it_behaves_like 'offending format specifier', '%10.2f', '5', "' 5.00'"
it_behaves_like 'offending format specifier', '%-10.2f', '5', "'5.00 '"
# Width or precision with interpolation
it_behaves_like 'non-offending format specifier', '%10s', '"#{foo}"'
it_behaves_like 'non-offending format specifier', '%.1s', '"#{foo}"'
it 'is able to handle `%%` specifiers' do
expect_no_offenses(<<~RUBY)
#{method}('%% %s', foo)
RUBY
end
it 'does not register an offense when a splat is given as arguments' do
expect_no_offenses(<<~RUBY)
#{method}('%d.%d.%d.%d', *@address.unpack('CCCC'))
RUBY
end
context 'with numbered specifiers' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
%{method}('%2$s %1$s', 'world', 'hello')
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `'hello world'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'hello world'
RUBY
end
it 'does not register an offense when the arguments do not match' do
expect_no_offenses(<<~RUBY)
#{method}('%2$s %1$i', 'abcd', '5')
RUBY
end
end
context 'with `*` in specifier' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
%{method}('%*d', 5, 14)
^{method}^^^^^^^^^^^^^^ Use `' 14'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
' 14'
RUBY
end
it 'registers an offense and corrects with multiple `*`s' do
expect_offense(<<~RUBY, method: method)
%{method}('$%0*.*f', 5, 2, 0.5)
^{method}^^^^^^^^^^^^^^^^^^^^^^ Use `'$00.50'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'$00.50'
RUBY
end
it 'registers an offense and corrects with a negative `*`' do
expect_offense(<<~RUBY, method: method)
%{method}('%-*d', 5, 14)
^{method}^^^^^^^^^^^^^^^ Use `'14 '` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'14 '
RUBY
end
it 'registers an offense and corrects with a variable width and a specified argument' do
expect_offense(<<~RUBY, method: method)
%{method}('%1$*2$s', 14, 5)
^{method}^^^^^^^^^^^^^^^^^^ Use `' 14'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
' 14'
RUBY
end
it 'registers an offense and corrects with a negative variable width and a specified argument' do
expect_offense(<<~RUBY, method: method)
%{method}('%1$-*2$s', 14, 5)
^{method}^^^^^^^^^^^^^^^^^^^ Use `'14 '` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'14 '
RUBY
end
it 'does not register an offense when the variable width argument is not numeric' do
expect_no_offenses(<<~RUBY)
#{method}('%*d', 'a', 'foo')
RUBY
end
it 'does not register an offense when the star argument is not literal' do
expect_no_offenses(<<~RUBY)
#{method}('%*s', foo, 'bar')
RUBY
end
it 'does not register an offense when the star argument is negative and not literal' do
expect_no_offenses(<<~RUBY)
#{method}('%-*s', foo, 'bar')
RUBY
end
it 'does not register an offense when the format argument is not literal' do
expect_no_offenses(<<~RUBY)
#{method}('%*d', 5, foo)
RUBY
end
it 'does not register an offense with multiple `*`s when the argument is not literal' do
expect_no_offenses(<<~RUBY)
#{method}('%*.*d', 5, 2, foo)
RUBY
end
end
context 'with annotated specifiers' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
#{method}('%<foo>s %<bar>s', foo: 'foo', bar: 'bar')
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `'foo bar'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'foo bar'
RUBY
end
it 'registers an offense and corrects with interpolated strings' do
expect_offense(<<~'RUBY', method: method)
%{method}('%<foo>s %<bar>s', foo: "#{foo}", bar: 'bar')
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `"#{foo} bar"` directly instead of `%{method}`.
RUBY
expect_correction(<<~'RUBY')
"#{foo} bar"
RUBY
end
it 'does not register an offense when given a non-literal' do
expect_no_offenses(<<~RUBY)
#{method}('%<foo>s', foo: foo)
RUBY
end
it 'does not register an offense when there are missing hash keys' do
expect_no_offenses(<<~RUBY)
format('(%<foo>?%<bar>s:%<baz>s)', 'foobar')
RUBY
end
end
context 'with template specifiers' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
#{method}('%{foo}s %{bar}s', foo: 'foo', bar: 'bar')
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `'foos bars'` directly instead of `#{method}`.
RUBY
expect_correction(<<~RUBY)
'foos bars'
RUBY
end
it 'registers an offense and corrects with interpolated strings' do
expect_offense(<<~'RUBY', method: method)
%{method}('%{foo}s %{bar}s', foo: "#{foo}", bar: 'bar')
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `"#{foo}s bars"` directly instead of `%{method}`.
RUBY
expect_correction(<<~'RUBY')
"#{foo}s bars"
RUBY
end
it 'does not register an offense when given a non-literal' do
expect_no_offenses(<<~RUBY)
#{method}('%{foo}', foo: foo)
RUBY
end
it 'does not register an offense when not given keyword arguments' do
expect_no_offenses(<<~RUBY)
#{method}('%{foo}', foo)
RUBY
end
it 'does not register an offense when given numeric placeholders in the template argument' do
expect_no_offenses(<<~RUBY)
#{method}('%<placeholder>d, %<placeholder>f', placeholder)
RUBY
end
end
context 'with an interpolated format string' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
#{method}("%0\#{width}d", 3)
RUBY
end
end
context 'when there are multiple %s fields and multiple string arguments' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
%{method}('%s %s', 'foo', 'bar')
^{method}^^^^^^^^^^^^^^^^^^^^^^^ Use `'foo bar'` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
'foo bar'
RUBY
end
end
context 'when there are multiple %s fields and not all arguments are string literals' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
#{method}('%s %s', 'foo', bar)
RUBY
end
end
context 'with invalid format arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
format('%{y}-%{m}-%{d}', 2015, 1, 1)
RUBY
end
end
end
context 'with constants' do
it 'registers an offense when the only argument is a constant' do
expect_offense(<<~RUBY, method: method)
%{method}(FORMAT)
^{method}^^^^^^^^ Use `FORMAT` directly instead of `%{method}`.
RUBY
expect_correction(<<~RUBY)
FORMAT
RUBY
end
it 'does not register an offense when the first argument is a constant' do
expect_no_offenses(<<~RUBY)
#{method}(FORMAT, 'foo', 'bar')
RUBY
end
it 'does not register an offense when only argument is a splatted constant' do
expect_no_offenses(<<~RUBY)
#{method}(*FORMAT)
RUBY
end
end
context 'when the string contains control characters' do
it 'registers an offense with the correct message' do
expect_offense(<<~'RUBY', method: method)
%{method}("%s\a\b\t\n\v\f\r\e", 'foo')
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `"foo\a\b\t\n\v\f\r\e"` directly instead of `%{method}`.
RUBY
expect_correction(<<~'RUBY')
"foo\a\b\t\n\v\f\r\e"
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/double_cop_disable_directive_spec.rb | spec/rubocop/cop/style/double_cop_disable_directive_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DoubleCopDisableDirective, :config do
it 'registers an offense for duplicate disable directives' do
expect_offense(<<~RUBY)
def choose_move(who_to_move) # rubocop:disable Metrics/CyclomaticComplexity # rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/MethodLength
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ More than one disable comment on one line.
end
RUBY
expect_correction(<<~RUBY)
def choose_move(who_to_move) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength
end
RUBY
end
it 'registers an offense for duplicate todo directives' do
expect_offense(<<~RUBY)
def choose_move(who_to_move) # rubocop:todo Metrics/CyclomaticComplexity # rubocop:todo Metrics/AbcSize # rubocop:todo Metrics/MethodLength
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ More than one disable comment on one line.
end
RUBY
expect_correction(<<~RUBY)
def choose_move(who_to_move) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength
end
RUBY
end
it 'does not register an offense for cops with single cop directive' do
expect_no_offenses(<<~RUBY)
def choose_move(who_to_move) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize
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/character_literal_spec.rb | spec/rubocop/cop/style/character_literal_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CharacterLiteral, :config do
it 'registers an offense for character literals' do
expect_offense(<<~RUBY)
x = ?x
^^ Do not use the character literal - use string literal instead.
RUBY
expect_correction(<<~RUBY)
x = 'x'
RUBY
end
it 'registers an offense for literals like \n' do
expect_offense(<<~'RUBY')
x = ?\n
^^^ Do not use the character literal - use string literal instead.
RUBY
expect_correction(<<~'RUBY')
x = "\n"
RUBY
end
it 'accepts literals like ?\C-\M-d' do
expect_no_offenses('x = ?\C-\M-d')
end
it 'accepts ? in a %w literal' do
expect_no_offenses('%w{? A}')
end
it 'autocorrects ?\' to "\'"' do
expect_offense(<<~RUBY)
x = ?'
^^ Do not use the character literal - use string literal instead.
RUBY
expect_correction(<<~RUBY)
x = "'"
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/mutable_constant_spec.rb | spec/rubocop/cop/style/mutable_constant_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MutableConstant, :config do
let(:prefix) { nil }
shared_examples 'mutable objects' do |o|
context 'when assigning with =' do
it "registers an offense for #{o} assigned to a constant " \
'and corrects by adding .freeze' do
expect_offense([prefix, <<~RUBY].compact.join("\n"), o: o)
CONST = %{o}
^{o} Freeze mutable objects assigned to constants.
RUBY
expect_correction([prefix, <<~RUBY].compact.join("\n"))
CONST = #{o}.freeze
RUBY
end
end
context 'when assigning with ||=' do
it "registers an offense for #{o} assigned to a constant " \
'and corrects by adding .freeze' do
expect_offense([prefix, <<~RUBY].compact.join("\n"), o: o)
CONST ||= %{o}
^{o} Freeze mutable objects assigned to constants.
RUBY
expect_correction([prefix, <<~RUBY].compact.join("\n"))
CONST ||= #{o}.freeze
RUBY
end
end
end
shared_examples 'immutable objects' do |o|
it "allows #{o} to be assigned to a constant" do
source = [prefix, "CONST = #{o}"].compact.join("\n")
expect_no_offenses(source)
end
it "allows #{o} to be ||= to a constant" do
source = [prefix, "CONST ||= #{o}"].compact.join("\n")
expect_no_offenses(source)
end
end
shared_examples 'literals that are frozen' do |o|
let(:prefix) { o }
it_behaves_like 'immutable objects', '[1, 2, 3]'
it_behaves_like 'immutable objects', '%w(a b c)'
it_behaves_like 'immutable objects', '{ a: 1, b: 2 }'
it_behaves_like 'immutable objects', "'str'"
it_behaves_like 'immutable objects', '"top#{1 + 2}"'
it_behaves_like 'immutable objects', '1'
it_behaves_like 'immutable objects', '1.5'
it_behaves_like 'immutable objects', ':sym'
it_behaves_like 'immutable objects', 'FOO + BAR'
it_behaves_like 'immutable objects', 'FOO - BAR'
it_behaves_like 'immutable objects', "'foo' + 'bar'"
it_behaves_like 'immutable objects', "ENV['foo']"
it_behaves_like 'immutable objects', "::ENV['foo']"
end
shared_examples 'literals that are not frozen' do |o|
let(:prefix) { o }
it_behaves_like 'mutable objects', '[1, 2, 3]'
it_behaves_like 'mutable objects', '%w(a b c)'
it_behaves_like 'mutable objects', '{ a: 1, b: 2 }'
it_behaves_like 'mutable objects', "'str'"
it_behaves_like 'mutable objects', '"top#{1 + 2}"'
it_behaves_like 'immutable objects', '1'
it_behaves_like 'immutable objects', '1.5'
it_behaves_like 'immutable objects', ':sym'
it_behaves_like 'immutable objects', 'FOO + BAR'
it_behaves_like 'immutable objects', 'FOO - BAR'
it_behaves_like 'immutable objects', "'foo' + 'bar'"
it_behaves_like 'immutable objects', "ENV['foo']"
it_behaves_like 'immutable objects', "::ENV['foo']"
end
shared_examples 'string literal' do
# TODO : It is not yet decided when frozen string will be the default.
# It has been abandoned in the Ruby 3.0 period, but may default in
# the long run. So these tests are left with a provisional value of 5.0.
if RuboCop::TargetRuby.supported_versions.include?(5.0)
context 'when the target ruby version >= 5.0' do
let(:ruby_version) { 5.0 }
context 'when the frozen string literal comment is missing' do
it_behaves_like 'immutable objects', '"#{a}"'
end
context 'when the frozen string literal comment is true' do
let(:prefix) { '# frozen_string_literal: true' }
it_behaves_like 'immutable objects', '"#{a}"'
end
context 'when the frozen string literal comment is false' do
let(:prefix) { '# frozen_string_literal: false' }
it_behaves_like 'immutable objects', '"#{a}"'
end
end
end
context 'Ruby 3.0 or higher', :ruby30 do
context 'when the frozen string literal comment is missing' do
it_behaves_like 'mutable objects', '"#{a}"'
end
context 'when the frozen string literal comment is true' do
let(:prefix) { '# frozen_string_literal: true' }
it_behaves_like 'mutable objects', '"#{a}"'
it_behaves_like 'immutable objects', <<~RUBY
<<~HERE
foo
bar
HERE
RUBY
it 'registers an offense when using interpolated heredoc constant' do
expect_offense(<<~'RUBY')
# frozen_string_literal: true
CONST = <<~HERE
^^^^^^^ Freeze mutable objects assigned to constants.
foo #{use_interpolation}
bar
HERE
RUBY
end
it 'does not register an offense when using a multiline string' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
CONST = 'foo' \
'bar'
RUBY
end
it 'registers an offense when using a multiline string with interpolation' do
expect_offense(<<~'RUBY')
# frozen_string_literal: true
CONST = "#{foo}" \
^^^^^^^^^^ Freeze mutable objects assigned to constants.
'bar'
RUBY
end
end
context 'when the frozen string literal comment is false' do
let(:prefix) { '# frozen_string_literal: false' }
it_behaves_like 'mutable objects', '"#{a}"'
end
end
context 'Ruby 2.7 or lower', :ruby27, unsupported_on: :prism do
context 'when the frozen string literal comment is missing' do
it_behaves_like 'mutable objects', '"#{a}"'
end
context 'when the frozen string literal comment is true' do
let(:prefix) { '# frozen_string_literal: true' }
it_behaves_like 'immutable objects', '"#{a}"'
it_behaves_like 'immutable objects', <<~RUBY
<<~HERE
foo
bar
HERE
RUBY
it 'does not register an offense when using interpolated heredoc constant' do
expect_no_offenses(<<~'RUBY')
# frozen_string_literal: true
CONST = <<~HERE
foo #{use_interpolation}
bar
HERE
RUBY
end
it 'does not register an offense when using a multiline string' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
CONST = 'foo' \
'bar'
RUBY
end
end
context 'when the frozen string literal comment is false' do
let(:prefix) { '# frozen_string_literal: false' }
it_behaves_like 'mutable objects', '"#{a}"'
end
end
end
context 'Strict: false' do
let(:cop_config) { { 'EnforcedStyle' => 'literals' } }
it_behaves_like 'mutable objects', '[1, 2, 3]'
it_behaves_like 'mutable objects', '%w(a b c)'
it_behaves_like 'mutable objects', '{ a: 1, b: 2 }'
it_behaves_like 'mutable objects', "'str'"
it_behaves_like 'mutable objects', '"top#{1 + 2}"'
it_behaves_like 'immutable objects', '1'
it_behaves_like 'immutable objects', '1.5'
it_behaves_like 'immutable objects', ':sym'
it_behaves_like 'immutable objects', 'FOO + BAR'
it_behaves_like 'immutable objects', 'FOO - BAR'
it_behaves_like 'immutable objects', "'foo' + 'bar'"
it_behaves_like 'immutable objects', "ENV['foo']"
it_behaves_like 'immutable objects', "::ENV['foo']"
it 'allows method call assignments' do
expect_no_offenses('TOP_TEST = Something.new')
end
context 'splat expansion' do
context 'expansion of a range' do
it 'registers an offense and corrects to use to_a.freeze' do
expect_offense(<<~RUBY)
FOO = *1..10
^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
FOO = (1..10).to_a.freeze
RUBY
end
context 'with parentheses' do
it 'registers an offense and corrects to use to_a.freeze' do
expect_offense(<<~RUBY)
FOO = *(1..10)
^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
FOO = (1..10).to_a.freeze
RUBY
end
end
end
end
context 'when assigning an array without brackets' do
it 'adds brackets when autocorrecting' do
expect_offense(<<~RUBY)
XXX = YYY, ZZZ
^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = [YYY, ZZZ].freeze
RUBY
end
it 'does not insert brackets for %w() arrays' do
expect_offense(<<~RUBY)
XXX = %w(YYY ZZZ)
^^^^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = %w(YYY ZZZ).freeze
RUBY
end
end
# Ruby 3.0's Regexp and Range literals are frozen.
#
# https://bugs.ruby-lang.org/issues/15504
# https://bugs.ruby-lang.org/issues/16377
context 'Ruby 3.0 or higher', :ruby30 do
context 'when assigning a regexp' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
XXX = /regexp/
RUBY
end
end
context 'when assigning a range (irange)' do
it 'does not register an offense when without parenthesis' do
expect_no_offenses(<<~RUBY)
XXX = 1..99
RUBY
end
it 'does not register an offense when with parenthesis' do
expect_no_offenses(<<~RUBY)
XXX = (1..99)
RUBY
end
end
context 'when assigning a range (erange)' do
it 'does not register an offense when without parenthesis' do
expect_no_offenses(<<~RUBY)
XXX = 1...99
RUBY
end
it 'does not register an offense when with parenthesis' do
expect_no_offenses(<<~RUBY)
XXX = (1...99)
RUBY
end
end
context 'when using shareable_constant_value' do
it_behaves_like 'literals that are frozen', '# shareable_constant_value: literal'
it_behaves_like 'literals that are frozen', '# shareable_constant_value: experimental_everything'
it_behaves_like 'literals that are frozen', '# shareable_constant_value: experimental_copy'
it_behaves_like 'literals that are not frozen', '# shareable_constant_value: none'
end
it 'raises offense when shareable_constant_value is specified as an inline comment' do
expect_offense(<<~RUBY)
X = [1, 2, 3] # shareable_constant_value: literal
^^^^^^^^^ Freeze mutable objects assigned to constants.
Y = [4, 5, 6]
^^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
end
it 'raises offense only for shareable_constant_value as none when set in the order of: literal, none and experimental_everything' do
expect_offense(<<~RUBY)
# shareable_constant_value: literal
X = [1, 2, 3]
# shareable_constant_value: none
Y = [4, 5, 6]
^^^^^^^^^ Freeze mutable objects assigned to constants.
# shareable_constant_value: experimental_everything
Z = [7, 8, 9]
RUBY
end
end
context 'Ruby 2.7 or lower', :ruby27, unsupported_on: :prism do
context 'when assigning a regexp' do
it 'registers an offense' do
expect_offense(<<~RUBY)
XXX = /regexp/
^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = /regexp/.freeze
RUBY
end
end
context 'when assigning a range (irange) without parenthesis' do
it 'adds parentheses when autocorrecting' do
expect_offense(<<~RUBY)
XXX = 1..99
^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = (1..99).freeze
RUBY
end
it 'does not insert parenthesis to range enclosed in parentheses' do
expect_offense(<<~RUBY)
XXX = (1..99)
^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = (1..99).freeze
RUBY
end
end
context 'when assigning a range (erange) without parenthesis' do
it 'adds parentheses when autocorrecting' do
expect_offense(<<~RUBY)
XXX = 1...99
^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = (1...99).freeze
RUBY
end
it 'does not insert parenthesis to range enclosed in parentheses' do
expect_offense(<<~RUBY)
XXX = (1...99)
^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = (1...99).freeze
RUBY
end
end
context 'when using shareable_constant_values' do
it_behaves_like 'literals that are not frozen', '# shareable_constant_value: literal'
it_behaves_like 'literals that are not frozen', '# shareable_constant_value: experimental_everything'
it_behaves_like 'literals that are not frozen', '# shareable_constant_value: experimental_copy'
it_behaves_like 'literals that are not frozen', '# shareable_constant_value: none'
end
end
it_behaves_like 'string literal'
end
context 'Strict: true' do
let(:cop_config) { { 'EnforcedStyle' => 'strict' } }
it_behaves_like 'mutable objects', '[1, 2, 3]'
it_behaves_like 'mutable objects', '%w(a b c)'
it_behaves_like 'mutable objects', '{ a: 1, b: 2 }'
it_behaves_like 'mutable objects', "'str'"
it_behaves_like 'mutable objects', '"top#{1 + 2}"'
it_behaves_like 'mutable objects', 'Something.new'
it_behaves_like 'immutable objects', '1'
it_behaves_like 'immutable objects', '1.5'
it_behaves_like 'immutable objects', ':sym'
it_behaves_like 'immutable objects', "ENV['foo']"
it_behaves_like 'immutable objects', "::ENV['foo']"
it_behaves_like 'immutable objects', 'OTHER_CONST'
it_behaves_like 'immutable objects', '::OTHER_CONST'
it_behaves_like 'immutable objects', 'Namespace::OTHER_CONST'
it_behaves_like 'immutable objects', '::Namespace::OTHER_CONST'
it_behaves_like 'immutable objects', 'Struct.new'
it_behaves_like 'immutable objects', '::Struct.new'
it_behaves_like 'immutable objects', 'Struct.new(:a, :b)'
it_behaves_like 'immutable objects', <<~RUBY
Struct.new(:node) do
def assignment?
true
end
end
RUBY
it 'allows calls to freeze' do
expect_no_offenses(<<~RUBY)
CONST = [1].freeze
RUBY
end
context 'splat expansion' do
context 'expansion of a range' do
it 'registers an offense and corrects to use to_a.freeze' do
expect_offense(<<~RUBY)
FOO = *1..10
^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
FOO = (1..10).to_a.freeze
RUBY
end
context 'with parentheses' do
it 'registers an offense and corrects to use to_a.freeze' do
expect_offense(<<~RUBY)
FOO = *(1..10)
^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
FOO = (1..10).to_a.freeze
RUBY
end
end
end
end
context 'when assigning with an operator' do
shared_examples 'operator methods' do |o|
it 'registers an offense and corrects with parens and freeze' do
expect_offense(<<~RUBY, o: o)
CONST = FOO %{o} BAR
^^^^^{o}^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
CONST = (FOO #{o} BAR).freeze
RUBY
end
end
it_behaves_like 'operator methods', '+'
it_behaves_like 'operator methods', '-'
it_behaves_like 'operator methods', '*'
it_behaves_like 'operator methods', '/'
it_behaves_like 'operator methods', '%'
it_behaves_like 'operator methods', '**'
end
context 'when assigning with multiple operator calls' do
it 'registers an offense and corrects with parens and freeze' do
expect_offense(<<~RUBY)
FOO = [1].freeze
BAR = [2].freeze
BAZ = [3].freeze
CONST = FOO + BAR + BAZ
^^^^^^^^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
FOO = [1].freeze
BAR = [2].freeze
BAZ = [3].freeze
CONST = (FOO + BAR + BAZ).freeze
RUBY
end
end
context 'methods and operators that produce frozen objects' do
it 'accepts assigning to an environment variable with a fallback' do
expect_no_offenses(<<~RUBY)
CONST = ENV['foo'] || 'foo'
RUBY
expect_no_offenses(<<~RUBY)
CONST = ::ENV['foo'] || 'foo'
RUBY
end
it 'accepts operating on a constant and an integer' do
expect_no_offenses(<<~RUBY)
CONST = FOO + 2
RUBY
end
it 'accepts operating on multiple integers' do
expect_no_offenses(<<~RUBY)
CONST = 1 + 2
RUBY
end
it 'accepts operating on a constant and a float' do
expect_no_offenses(<<~RUBY)
CONST = FOO + 2.1
RUBY
end
it 'accepts operating on multiple floats' do
expect_no_offenses(<<~RUBY)
CONST = 1.2 + 2.1
RUBY
end
it 'accepts comparison operators' do
expect_no_offenses(<<~RUBY)
CONST = FOO == BAR
RUBY
end
it 'accepts checking fixed size' do
expect_no_offenses(<<~RUBY)
CONST = 'foo'.count
CONST = 'foo'.count('f')
CONST = [1, 2, 3].count { |n| n > 2 }
CONST = [1, 2, 3].count(2) { |n| n > 2 }
CONST = 'foo'.length
CONST = 'foo'.size
RUBY
end
end
context 'operators that produce unfrozen objects' do
it 'registers an offense when operating on a constant and a string' do
expect_offense(<<~RUBY)
CONST = FOO + 'bar'
^^^^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
CONST = (FOO + 'bar').freeze
RUBY
end
it 'registers an offense when operating on multiple strings' do
expect_offense(<<~RUBY)
CONST = 'foo' + 'bar' + 'baz'
^^^^^^^^^^^^^^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
CONST = ('foo' + 'bar' + 'baz').freeze
RUBY
end
end
context 'when assigning an array without brackets' do
it 'adds brackets when autocorrecting' do
expect_offense(<<~RUBY)
XXX = YYY, ZZZ
^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = [YYY, ZZZ].freeze
RUBY
end
it 'does not insert brackets for %w() arrays' do
expect_offense(<<~RUBY)
XXX = %w(YYY ZZZ)
^^^^^^^^^^^ Freeze mutable objects assigned to constants.
RUBY
expect_correction(<<~RUBY)
XXX = %w(YYY ZZZ).freeze
RUBY
end
end
it 'freezes a heredoc' do
expect_offense(<<~RUBY)
FOO = <<-HERE
^^^^^^^ Freeze mutable objects assigned to constants.
SOMETHING
HERE
RUBY
expect_correction(<<~RUBY)
FOO = <<-HERE.freeze
SOMETHING
HERE
RUBY
end
it_behaves_like 'string literal'
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_while_spec.rb | spec/rubocop/cop/style/negated_while_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NegatedWhile, :config do
it 'registers an offense for while with exclamation point condition' do
expect_offense(<<~RUBY)
while !a_condition
^^^^^^^^^^^^^^^^^^ Favor `until` over `while` for negative conditions.
some_method
end
some_method while !a_condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `until` over `while` for negative conditions.
RUBY
expect_correction(<<~RUBY)
until a_condition
some_method
end
some_method until a_condition
RUBY
end
it 'registers an offense for until with exclamation point condition' do
expect_offense(<<~RUBY)
until !a_condition
^^^^^^^^^^^^^^^^^^ Favor `while` over `until` for negative conditions.
some_method
end
some_method until !a_condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `while` over `until` for negative conditions.
RUBY
expect_correction(<<~RUBY)
while a_condition
some_method
end
some_method while a_condition
RUBY
end
it 'registers an offense for while with "not" condition' do
expect_offense(<<~RUBY)
while (not a_condition)
^^^^^^^^^^^^^^^^^^^^^^^ Favor `until` over `while` for negative conditions.
some_method
end
some_method while not a_condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `until` over `while` for negative conditions.
RUBY
expect_correction(<<~RUBY)
until (a_condition)
some_method
end
some_method until a_condition
RUBY
end
it 'accepts a while where only part of the condition is negated' do
expect_no_offenses(<<~RUBY)
while !a_condition && another_condition
some_method
end
while not a_condition or another_condition
some_method
end
some_method while not a_condition or other_cond
RUBY
end
it 'accepts a while where the condition is doubly negated' do
expect_no_offenses(<<~RUBY)
while !!a_condition
some_method
end
some_method while !!a_condition
RUBY
end
it 'autocorrects by replacing while not with until' do
expect_offense(<<~RUBY)
something while !x.even?
^^^^^^^^^^^^^^^^^^^^^^^^ Favor `until` over `while` for negative conditions.
something while(!x.even?)
^^^^^^^^^^^^^^^^^^^^^^^^^ Favor `until` over `while` for negative conditions.
RUBY
expect_correction(<<~RUBY)
something until x.even?
something until(x.even?)
RUBY
end
it 'autocorrects by replacing until not with while' do
expect_offense(<<~RUBY)
something until !x.even?
^^^^^^^^^^^^^^^^^^^^^^^^ Favor `while` over `until` for negative conditions.
RUBY
expect_correction(<<~RUBY)
something while x.even?
RUBY
end
it 'does not blow up for empty while condition' do
expect_no_offenses(<<~RUBY)
while ()
end
RUBY
end
it 'does not blow up for empty until condition' do
expect_no_offenses(<<~RUBY)
until ()
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/empty_string_inside_interpolation_spec.rb | spec/rubocop/cop/style/empty_string_inside_interpolation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyStringInsideInterpolation, :config do
context 'when EnforcedStyle is trailing_conditional' do
let(:cop_config) { { 'EnforcedStyle' => 'trailing_conditional' } }
it 'does not register an offense when if branch is not a literal' do
expect_no_offenses(<<~'RUBY')
"#{condition ? send_node : 'foo'}"
RUBY
end
it 'does not register an offense when else branch is not a literal' do
expect_no_offenses(<<~'RUBY')
"#{condition ? 'foo' : send_node}"
RUBY
end
it 'does not register an offense when both if and else branches are not literals' do
expect_no_offenses(<<~'RUBY')
"#{condition ? send_node : another_send_node}"
RUBY
end
%w['' "" nil].each do |empty|
it "registers an offense when #{empty} is the false outcome of a ternary" do
expect_offense(<<~'RUBY', empty: empty)
"#{condition ? 'foo' : %{empty}}"
^^^^^^^^^^^^^^^^^^^^^{empty} Do not return empty strings in string interpolation.
RUBY
expect_correction(<<~'RUBY')
"#{'foo' if condition}"
RUBY
end
it "registers an offense when #{empty} is the false outcome of a ternary and another value is a non-string literal" do
expect_offense(<<~'RUBY', empty: empty)
"#{condition ? 42 : %{empty}}"
^^^^^^^^^^^^^^^^^^{empty} Do not return empty strings in string interpolation.
RUBY
expect_correction(<<~'RUBY')
"#{42 if condition}"
RUBY
end
it "registers an offense when #{empty} is the false outcome of a single-line conditional" do
expect_offense(<<~'RUBY', empty: empty)
"#{if condition; 'foo' else %{empty} end}"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{empty} Do not return empty strings in string interpolation.
RUBY
expect_correction(<<~'RUBY')
"#{'foo' if condition}"
RUBY
end
it "registers an offense when #{empty} is the true outcome of a ternary" do
expect_offense(<<~'RUBY', empty: empty)
"#{condition ? %{empty} : 'foo'}"
^^^^^^^^^^^^^^^^^^^^^{empty} Do not return empty strings in string interpolation.
RUBY
expect_correction(<<~'RUBY')
"#{'foo' unless condition}"
RUBY
end
it "registers an offense when #{empty} is the true outcome of a single-line conditional" do
expect_offense(<<~'RUBY', empty: empty)
"#{if condition; %{empty} else 'foo' end}"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{empty} Do not return empty strings in string interpolation.
RUBY
expect_correction(<<~'RUBY')
"#{'foo' unless condition}"
RUBY
end
it 'does not register an offense when a trailing if is used inside string interpolation' do
expect_no_offenses(<<~'RUBY')
"#{'foo' if condition}"
RUBY
end
end
end
context 'when EnforcedStyle is ternary' do
let(:cop_config) { { 'EnforcedStyle' => 'ternary' } }
it 'registers an offense when a trailing if is used inside string interpolation' do
expect_offense(<<~'RUBY')
"#{'foo' if condition}"
^^^^^^^^^^^^^^^^^^^^^ Do not use trailing conditionals in string interpolation.
RUBY
expect_correction(<<~'RUBY')
"#{condition ? 'foo' : ''}"
RUBY
end
it 'registers an offense when a trailing unless is used inside string interpolation' do
expect_offense(<<~'RUBY')
"#{'foo' unless condition}"
^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use trailing conditionals in string interpolation.
RUBY
expect_correction(<<~'RUBY')
"#{condition ? '' : 'foo'}"
RUBY
end
it 'does not register an offense when empty string is the false outcome of a ternary' do
expect_no_offenses(<<~'RUBY')
"#{condition ? 'foo' : ''}"
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/frozen_string_literal_comment_spec.rb | spec/rubocop/cop/style/frozen_string_literal_comment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FrozenStringLiteralComment, :config do
context 'always' do
let(:cop_config) { { 'Enabled' => true, 'EnforcedStyle' => 'always' } }
it 'accepts an empty source' do
expect_no_offenses('')
end
it 'accepts a source with no tokens' do
expect_no_offenses(' ')
end
it 'accepts a frozen string literal on the top line' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a disabled frozen string literal on the top line' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: false
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens' do
expect_offense(<<~RUBY)
# frozen_string_literal: token
^ Missing frozen string literal comment.
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment on the top line' do
expect_offense(<<~RUBY)
puts 1
^ Missing frozen string literal comment.
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment under a shebang' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'when there is only a shebang' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing frozen string literal comment.
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
RUBY
end
it 'accepts a frozen string literal below a shebang comment' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a disabled frozen string literal below a shebang comment' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: false
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'under an encoding comment' do
expect_offense(<<~RUBY)
# encoding: utf-8
^ Missing frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'under an encoding comment separated by a newline' do
expect_offense(<<~RUBY)
# encoding: utf-8
^ Missing frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal below an encoding comment' do
expect_no_offenses(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a disabled frozen string literal below an encoding comment' do
expect_no_offenses(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: false
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'under a shebang and an encoding comment' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing frozen string literal comment.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense with an empty line between magic comments and the code' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing frozen string literal comment.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal comment below shebang and encoding comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal comment below newline-separated magic comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a disabled frozen string literal comment below shebang and encoding comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: false
puts 1
RUBY
end
it 'accepts a frozen string literal comment below shebang above an encoding comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
# encoding: utf-8
puts 1
RUBY
end
it 'accepts a disabled frozen string literal comment below shebang above ' \
'an encoding comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: false
# encoding: utf-8
puts 1
RUBY
end
it 'accepts an emacs style combined magic comment' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# -*- encoding: UTF-8; frozen_string_literal: true -*-
# encoding: utf-8
puts 1
RUBY
end
it 'accepts a frozen string literal comment after other comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
#
# These are more comments
# frozen_string_literal: false
puts 1
RUBY
end
it 'registers an offense for having a frozen string literal comment under ruby code' do
expect_offense(<<~RUBY)
# encoding: utf-8
^ Missing frozen string literal comment.
puts 1
# frozen_string_literal: true
RUBY
# Since we're only looking at the leading comments, a
# `frozen_string_literal` comment elsewhere in the code is invisible
# to this cop so the autocorrect won't remove it.
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
# frozen_string_literal: true
RUBY
end
it 'registers an offense for an extra first empty line' do
expect_offense(<<~RUBY)
^{} Missing frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
%w[TRUE FALSE True False truE falsE].each do |value|
it "accepts a frozen string literal with `#{value}` literal" do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: #{value}
puts 1
RUBY
end
end
end
context 'never' do
let(:cop_config) { { 'Enabled' => true, 'EnforcedStyle' => 'never' } }
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 a frozen string literal comment on the top line' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal comment on the top line' do
expect_offense(<<~RUBY)
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
puts 1
RUBY
end
it 'accepts not having a frozen string literal comment on the top line' do
expect_no_offenses('puts 1')
end
it 'accepts not having not having a frozen string literal comment under a shebang' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
puts 1
RUBY
end
it 'registers an offense for a frozen string literal comment below a shebang comment' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal below a shebang comment' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
puts 1
RUBY
end
it 'allows not having a frozen string literal comment under an encoding comment' do
expect_no_offenses(<<~RUBY)
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for a frozen string literal comment below an encoding comment' do
expect_offense(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal below an encoding comment' do
expect_offense(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
puts 1
RUBY
end
it 'allows not having a frozen string literal comment ' \
'under a shebang and an encoding comment' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for a frozen string literal comment ' \
'below shebang and encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal comment ' \
'below shebang and encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for a frozen string literal comment ' \
'below shebang above an encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal comment ' \
'below shebang above an encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for having a frozen string literal comment after other comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
#
# These are more comments
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
#
# These are more comments
puts 1
RUBY
end
it 'accepts a frozen string literal comment under ruby code' do
expect_no_offenses(<<~RUBY)
# encoding: utf-8
puts 1
# frozen_string_literal: true
RUBY
end
[
'# frozen-string-literal: true',
'# frozen_string_literal: TRUE',
'# frozen-string_literal: true',
'# frozen-string_literal: TRUE',
'# frozen_string-literal: true',
'# FROZEN-STRING-LITERAL: true',
'# FROZEN_STRING_LITERAL: true'
].each do |magic_comment|
it "registers an offense for having a `#{magic_comment}` frozen string literal comment" do
expect_offense(<<~RUBY, magic_comment: magic_comment)
#{magic_comment}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
puts 1
RUBY
end
end
it 'registers an offense for having a frozen string literal comment with multiple spaces at beginning' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
puts 1
RUBY
end
context 'with emacs style magic comment' do
it 'registers an offense when the comment is the first one' do
expect_offense(<<~RUBY)
# -*- frozen_string_literal: true -*-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
puts 1
RUBY
expect_correction(<<~RUBY)
puts 1
RUBY
end
it 'registers an offense when the comment is between other comments' do
expect_offense(<<~RUBY)
# -*- encoding: utf-8 -*-
# -*- frozen_string_literal: true -*-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary frozen string literal comment.
# -*- warn_indent: true -*-
puts 1
RUBY
expect_correction(<<~RUBY)
# -*- encoding: utf-8 -*-
# -*- warn_indent: true -*-
puts 1
RUBY
end
end
end
context 'always_true' do
let(:cop_config) { { 'Enabled' => true, 'EnforcedStyle' => 'always_true' } }
it 'accepts an empty source' do
expect_no_offenses('')
end
it 'accepts a source with no tokens' do
expect_no_offenses(' ')
end
it 'accepts a frozen string literal on the top line' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal on the top line' do
expect_offense(<<~RUBY)
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens' do
expect_offense(<<~RUBY)
# frozen_string_literal: token
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment on the top line' do
expect_offense(<<~RUBY)
puts 1
^ Missing magic comment `# frozen_string_literal: true`.
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for an extra first empty line' do
expect_offense(<<~RUBY)
^{} Missing magic comment `# frozen_string_literal: true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal above an empty line' do
expect_offense(<<~RUBY)
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens above an empty line' do
expect_offense(<<~RUBY)
# frozen_string_literal: token
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing magic comment `# frozen_string_literal: true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal below a shebang comment' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal below a shebang comment' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens below a shebang comment' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: token
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'under an encoding comment' do
expect_offense(<<~RUBY)
# encoding: utf-8
^ Missing magic comment `# frozen_string_literal: true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal below an encoding comment' do
expect_no_offenses(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal below an encoding comment' do
expect_offense(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens below an encoding comment' do
expect_offense(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: token
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'under a shebang and an encoding comment' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing magic comment `# frozen_string_literal: true`.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal comment below shebang and encoding comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal comment ' \
'below shebang and encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens below shebang and encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: tokens
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal comment below shebang above an encoding comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal ' \
'comment below shebang above an encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
# encoding: utf-8
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens below shebang above an encoding comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: tokens
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
# encoding: utf-8
puts 1
RUBY
end
it 'accepts an emacs style combined magic comment' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# -*- encoding: UTF-8; frozen_string_literal: true -*-
# encoding: utf-8
puts 1
RUBY
end
context 'with emacs style disable magic comment' do
it 'registers an offense when the comment is the first one' do
expect_offense(<<~RUBY)
# -*- frozen_string_literal: false -*-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
RUBY
expect_correction(<<~RUBY)
# -*- frozen_string_literal: true -*-
RUBY
end
it 'registers an offense when the comment is between other comments' do
expect_offense(<<~RUBY)
# -*- encoding: utf-8 -*-
# -*- frozen_string_literal: false -*-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
# -*- warn_indent: true -*-
puts 1
RUBY
expect_correction(<<~RUBY)
# -*- encoding: utf-8 -*-
# -*- frozen_string_literal: true -*-
# -*- warn_indent: true -*-
puts 1
RUBY
end
end
it 'registers an offense for not having a frozen string literal comment ' \
'under a shebang, an encoding comment, and extra space' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing magic comment `# frozen_string_literal: true`.
# encoding: utf-8
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal comment below shebang, an encoding ' \
'comment, and extra space' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal comment ' \
'below shebang, an encoding comment, and extra space' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens below ' \
'shebang, an encoding comment, and extra space' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: tokens
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'under an encoding comment and extra space' do
expect_offense(<<~RUBY)
# encoding: utf-8
^ Missing magic comment `# frozen_string_literal: true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'accepts a frozen string literal comment below an encoding comment and extra space' do
expect_no_offenses(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal comment ' \
'below an encoding comment and extra space' do
expect_offense(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for arbitrary tokens below an encoding comment and extra space' do
expect_offense(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: tokens
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for not having a frozen string literal comment ' \
'under shebang with no other code' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
^ Missing magic comment `# frozen_string_literal: true`.
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
RUBY
end
it 'accepts a frozen string literal comment under shebang with no other code' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
RUBY
end
it 'accepts a frozen string literal comment after other comments' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
#
# These are more comments
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for a disabled frozen string literal comment after other comments' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
#
# These are more comments
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# encoding: utf-8
#
# These are more comments
# frozen_string_literal: true
puts 1
RUBY
end
it 'registers an offense for having a frozen string literal comment under ruby code' do
expect_offense(<<~RUBY)
# encoding: utf-8
^ Missing magic comment `# frozen_string_literal: true`.
puts 1
# frozen_string_literal: true
RUBY
# Since we're only looking at the leading comments, a
# `frozen_string_literal` comment elsewhere in the code is invisible
# to this cop so the autocorrect won't remove it.
expect_correction(<<~RUBY)
# encoding: utf-8
# frozen_string_literal: true
puts 1
# frozen_string_literal: true
RUBY
end
it 'registers an offense for a disabled frozen string literal comment ' \
'under shebang with no other code' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
RUBY
end
it 'registers an offense for arbitrary tokens under shebang with no other code' do
expect_offense(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: tokens
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
RUBY
expect_correction(<<~RUBY)
#!/usr/bin/env ruby
# frozen_string_literal: true
RUBY
end
%w[FALSE falsE].each do |value|
it "registers an offense for a frozen string literal with `#{value}` literal" do
expect_offense(<<~RUBY, value: value)
# frozen_string_literal: #{value}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Frozen string literal comment must be set to `true`.
puts 1
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
puts 1
RUBY
end
end
end
context 'target_ruby_version < 2.3', :ruby22, unsupported_on: :prism do
it 'accepts freezing a string' do
expect_no_offenses('"x".freeze')
end
it 'accepts calling << on a string' do
expect_no_offenses('"x" << "y"')
end
it 'accepts freezing a string with interpolation' do
expect_no_offenses('"#{foo}bar".freeze')
end
it 'accepts calling << on a string with interpolation' do
expect_no_offenses('"#{foo}bar" << "baz"')
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/preferred_hash_methods_spec.rb | spec/rubocop/cop/style/preferred_hash_methods_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::PreferredHashMethods, :config do
context 'with enforced `short` style' do
let(:cop_config) { { 'EnforcedStyle' => 'short' } }
it 'registers an offense for has_key? with one arg' do
expect_offense(<<~RUBY)
o.has_key?(o)
^^^^^^^^ Use `Hash#key?` instead of `Hash#has_key?`.
RUBY
expect_correction(<<~RUBY)
o.key?(o)
RUBY
end
it 'accepts has_key? with no args' do
expect_no_offenses('o.has_key?')
end
it 'registers an offense for has_value? with one arg' do
expect_offense(<<~RUBY)
o.has_value?(o)
^^^^^^^^^^ Use `Hash#value?` instead of `Hash#has_value?`.
RUBY
expect_correction(<<~RUBY)
o.value?(o)
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense for has_value? with one arg' do
expect_offense(<<~RUBY)
o&.has_value?(o)
^^^^^^^^^^ Use `Hash#value?` instead of `Hash#has_value?`.
RUBY
expect_correction(<<~RUBY)
o&.value?(o)
RUBY
end
end
it 'accepts has_value? with no args' do
expect_no_offenses('o.has_value?')
end
end
context 'with enforced `verbose` style' do
let(:cop_config) { { 'EnforcedStyle' => 'verbose' } }
it 'registers an offense for key? with one arg' do
expect_offense(<<~RUBY)
o.key?(o)
^^^^ Use `Hash#has_key?` instead of `Hash#key?`.
RUBY
expect_correction(<<~RUBY)
o.has_key?(o)
RUBY
end
it 'accepts key? with no args' do
expect_no_offenses('o.key?')
end
it 'registers an offense for value? with one arg' do
expect_offense(<<~RUBY)
o.value?(o)
^^^^^^ Use `Hash#has_value?` instead of `Hash#value?`.
RUBY
expect_correction(<<~RUBY)
o.has_value?(o)
RUBY
end
it 'accepts value? with no args' do
expect_no_offenses('o.value?')
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_chars_spec.rb | spec/rubocop/cop/style/string_chars_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StringChars, :config do
it 'registers and corrects an offense when using `split(//)`' do
expect_offense(<<~RUBY)
string.split(//)
^^^^^^^^^ Use `chars` instead of `split(//)`.
RUBY
expect_correction(<<~RUBY)
string.chars
RUBY
end
it "registers and corrects an offense when using `split('')`" do
expect_offense(<<~RUBY)
string.split('')
^^^^^^^^^ Use `chars` instead of `split('')`.
RUBY
expect_correction(<<~RUBY)
string.chars
RUBY
end
it 'registers and corrects an offense when using `split("")`' do
expect_offense(<<~RUBY)
string.split("")
^^^^^^^^^ Use `chars` instead of `split("")`.
RUBY
expect_correction(<<~RUBY)
string.chars
RUBY
end
it 'registers and corrects an offense when using `split` without parentheses' do
expect_offense(<<~RUBY)
do_something { |foo| foo.split '' }
^^^^^^^^ Use `chars` instead of `split ''`.
RUBY
expect_correction(<<~RUBY)
do_something { |foo| foo.chars }
RUBY
end
it 'registers and corrects an offense when using safe navigation `split(//)` call' do
expect_offense(<<~RUBY)
string&.split(//)
^^^^^^^^^ Use `chars` instead of `split(//)`.
RUBY
expect_correction(<<~RUBY)
string&.chars
RUBY
end
it 'does not register an offense when using `chars`' do
expect_no_offenses(<<~RUBY)
string.chars
RUBY
end
it 'does not register an offense when using `split(/ /)`' do
expect_no_offenses(<<~RUBY)
string.split(/ /)
RUBY
end
it 'does not register an offense when using `split`' do
expect_no_offenses(<<~RUBY)
string.split
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/dig_chain_spec.rb | spec/rubocop/cop/style/dig_chain_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DigChain, :config do
it 'does not register an offense for unchained `dig` without a receiver' do
expect_no_offenses(<<~RUBY)
dig
RUBY
end
it 'does not register an offense for `X::dig`' do
expect_no_offenses(<<~RUBY)
X::dig(:foo, :bar)
RUBY
end
it 'does not register an offense for dig chained to something else' do
expect_no_offenses(<<~RUBY)
x.dig(:foo).bar
x.bar.dig(:foo)
RUBY
end
it 'does not register an offense when the chain is broken up' do
expect_no_offenses(<<~RUBY)
x.dig(:foo).first.dig(:bar)
RUBY
end
it 'does not register an offense for dig without arguments' do
expect_no_offenses(<<~RUBY)
x.dig
RUBY
end
it 'does not register an offense for chained dig without arguments' do
expect_no_offenses(<<~RUBY)
x.dig(:foo, :bar).dig
x.dig.dig(:foo, :bar)
RUBY
end
it 'does not register an offense for a hash' do
expect_no_offenses(<<~RUBY)
x.dig({ foo: 1, bar: 2 }).dig({ baz: 3, quux: 4 })
RUBY
end
it 'does not register an offense for kwargs' do
expect_no_offenses(<<~RUBY)
x.dig(foo: 1, bar: 2).dig(baz: 3, quux: 4)
RUBY
end
context 'with chained `dig` calls' do
it 'registers an offense and corrects with single values' do
expect_offense(<<~RUBY)
x.dig(:foo).dig(:bar).dig(:baz)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
x.dig(:foo, :bar, :baz)
RUBY
end
it 'registers an offense and corrects when attached to a chain of non-dig receivers' do
expect_offense(<<~RUBY)
x.y.z.dig(:foo).dig(:bar).dig(:baz)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
x.y.z.dig(:foo, :bar, :baz)
RUBY
end
it 'registers an offense and corrects with multiple values' do
expect_offense(<<~RUBY)
x.dig(:foo, :bar).dig(:baz, :quux)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz, :quux)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
x.dig(:foo, :bar, :baz, :quux)
RUBY
end
it 'registers an offense and corrects with safe navigation' do
expect_offense(<<~RUBY)
x.dig(:foo, :bar)&.dig(:baz, :quux)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz, :quux)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
x.dig(:foo, :bar, :baz, :quux)
RUBY
end
it 'registers an offense and corrects with safe navigation method chain' do
expect_offense(<<~RUBY)
x&.dig(:foo, :bar)&.dig(:baz, :quux)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz, :quux)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
x&.dig(:foo, :bar, :baz, :quux)
RUBY
end
it 'registers an offense and corrects without a receiver' do
expect_offense(<<~RUBY)
dig(:foo, :bar).dig(:baz, :quux)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz, :quux)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
dig(:foo, :bar, :baz, :quux)
RUBY
end
it 'registers an offense and corrects with `::` instead of dot' do
expect_offense(<<~RUBY)
x.dig(:foo, :bar)::dig(:baz, :quux)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz, :quux)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
x.dig(:foo, :bar, :baz, :quux)
RUBY
end
it 'registers an offense and corrects with splat' do
expect_offense(<<~RUBY)
x.dig(:foo).dig(*names).dig(:bar)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, *names, :bar)` instead of chaining.
RUBY
expect_correction(<<~RUBY)
x.dig(:foo, *names, :bar)
RUBY
end
it 'registers an offense and corrects when split over multiple lines' do
expect_offense(<<~RUBY)
x.dig(:foo)
^^^^^^^^^ Use `dig(:foo, :bar, :baz)` instead of chaining.
.dig(:bar)
.dig(:baz)
RUBY
expect_correction(<<~RUBY)
x.dig(:foo, :bar, :baz)
RUBY
end
it 'registers an offense and corrects when split over multiple lines with comments' do
expect_offense(<<~RUBY)
x.dig(:foo) # comment 1
^^^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar, :baz)` instead of chaining.
.dig(:bar) # comment 2
.dig(:baz) # comment 3
RUBY
expect_correction(<<~RUBY)
# comment 1
# comment 2
x.dig(:foo, :bar, :baz) # comment 3
RUBY
end
context '`...` argument forwarding' do
it 'registers an offense and corrects with forwarded args' do
expect_offense(<<~RUBY)
def foo(...)
x.dig(:foo).dig(...)
^^^^^^^^^^^^^^^^^^ Use `dig(:foo, ...)` instead of chaining.
end
RUBY
expect_correction(<<~RUBY)
def foo(...)
x.dig(:foo, ...)
end
RUBY
end
it 'does not register an offense when combining would add a syntax error' do
expect_no_offenses(<<~RUBY)
def foo(...)
x.dig(...).dig(:foo)
x.dig(...).dig(...)
end
RUBY
end
context 'Ruby >= 3.1', :ruby31 do
it 'does not register an offense when `dig` is given a forwarded anonymous block' do
expect_no_offenses(<<~RUBY)
def foo(&)
x.dig(&).dig(:foo)
end
RUBY
end
end
context 'Ruby >= 3.2', :ruby32 do
it 'registers an offense and corrects with forwarded anonymous splat' do
expect_offense(<<~RUBY)
def foo(*)
x.dig(*).dig(*)
^^^^^^^^^^^^^ Use `dig(*, *)` instead of chaining.
end
RUBY
expect_correction(<<~RUBY)
def foo(*)
x.dig(*, *)
end
RUBY
end
it 'does not register an offense with forwarded anonymous kwsplat' do
expect_no_offenses(<<~RUBY)
def foo(**)
x.dig(**).dig(:foo)
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/hash_like_case_spec.rb | spec/rubocop/cop/style/hash_like_case_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashLikeCase, :config do
context 'MinBranchesCount: 2' do
let(:cop_config) { { 'MinBranchesCount' => 2 } }
it 'registers an offense when using `case-when` with string conditions and literal bodies of the same type' do
expect_offense(<<~RUBY)
case x
^^^^^^ Consider replacing `case-when` with a hash lookup.
when 'foo'
'FOO'
when 'bar'
'BAR'
end
RUBY
end
it 'registers an offense when using `case-when` with symbol conditions and literal bodies of the same type' do
expect_offense(<<~RUBY)
case x
^^^^^^ Consider replacing `case-when` with a hash lookup.
when :foo
'FOO'
when :bar
'BAR'
end
RUBY
end
it 'does not register an offense when using `case-when` with literals of different types as conditions' do
expect_no_offenses(<<~RUBY)
case x
when 'foo'
'FOO'
when :bar
'BAR'
end
RUBY
end
it 'does not register an offense when using `case-when` with non-literals in conditions' do
expect_no_offenses(<<~RUBY)
case x
when y
'FOO'
when z
'BAR'
end
RUBY
end
it 'does not register an offense when using `case-when` with literal bodies of different types' do
expect_no_offenses(<<~RUBY)
case x
when 'foo'
'FOO'
when 'bar'
2
end
RUBY
end
it 'does not register an offense when using `case-when` with non-literal bodies' do
expect_no_offenses(<<~RUBY)
case x
when 'foo'
y
when 'bar'
z
end
RUBY
end
it 'does not register an offense when `case` has an `else` branch' do
expect_no_offenses(<<~RUBY)
case x
when 'foo'
'FOO'
when 'bar'
'BAR'
else
'BAZ'
end
RUBY
end
end
context 'MinBranchesCount: 3' do
let(:cop_config) { { 'MinBranchesCount' => 3 } }
it 'does not register an offense when branches count is less than required' do
expect_no_offenses(<<~RUBY)
case x
when 'foo'
'FOO'
when 'bar'
'BAR'
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/env_home_spec.rb | spec/rubocop/cop/style/env_home_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EnvHome, :config do
it "registers and corrects an offense when using `ENV['HOME']`" do
expect_offense(<<~RUBY)
ENV['HOME']
^^^^^^^^^^^ Use `Dir.home` instead.
RUBY
expect_correction(<<~RUBY)
Dir.home
RUBY
end
it "registers and corrects an offense when using `ENV.fetch('HOME')`" do
expect_offense(<<~RUBY)
ENV.fetch('HOME')
^^^^^^^^^^^^^^^^^ Use `Dir.home` instead.
RUBY
expect_correction(<<~RUBY)
Dir.home
RUBY
end
it "registers and corrects an offense when using `ENV.fetch('HOME', nil)`" do
expect_offense(<<~RUBY)
ENV.fetch('HOME', nil)
^^^^^^^^^^^^^^^^^^^^^^ Use `Dir.home` instead.
RUBY
expect_correction(<<~RUBY)
Dir.home
RUBY
end
it "registers and corrects an offense when using `::ENV['HOME']`" do
expect_offense(<<~RUBY)
::ENV['HOME']
^^^^^^^^^^^^^ Use `Dir.home` instead.
RUBY
expect_correction(<<~RUBY)
Dir.home
RUBY
end
it 'does not register an offense when using `Dir.home`' do
expect_no_offenses(<<~RUBY)
Dir.home
RUBY
end
it "does not register an offense when using `ENV['HOME'] = '/home/foo'`" do
expect_no_offenses(<<~RUBY)
ENV['HOME'] = '/home/foo'
RUBY
end
it "does not register an offense when using `ENV.fetch('HOME', default)`" do
expect_no_offenses(<<~RUBY)
ENV.fetch('HOME', default)
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/multiple_comparison_spec.rb | spec/rubocop/cop/style/multiple_comparison_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultipleComparison, :config do
it 'does not register an offense for comparing an lvar' do
expect_no_offenses(<<~RUBY)
a = "a"
if a == "a"
print a
end
RUBY
end
it 'registers an offense and corrects when `a` is compared twice' do
expect_offense(<<~RUBY)
a = "a"
if a == "a" || a == "b"
^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
a = "a"
if ["a", "b"].include?(a)
print a
end
RUBY
end
it 'registers an offense and corrects when `a` is compared three times' do
expect_offense(<<~RUBY)
a = "a"
if a == "a" || a == "b" || a == "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
a = "a"
if ["a", "b", "c"].include?(a)
print a
end
RUBY
end
it 'registers an offense and corrects when `a` is compared three times on the right hand side' do
expect_offense(<<~RUBY)
a = "a"
if "a" == a || "b" == a || "c" == a
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
a = "a"
if ["a", "b", "c"].include?(a)
print a
end
RUBY
end
it 'registers an offense and corrects when `a` is compared three times, once on the ' \
'right hand side' do
expect_offense(<<~RUBY)
a = "a"
if a == "a" || "b" == a || a == "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
a = "a"
if ["a", "b", "c"].include?(a)
print a
end
RUBY
end
it 'registers an offense and corrects when multiple comparison is not part of a conditional' do
expect_offense(<<~RUBY)
def foo(x)
x == 1 || x == 2 || x == 3
^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo(x)
[1, 2, 3].include?(x)
end
RUBY
end
it 'registers an offense and corrects when `a` is compared twice in `if` and `elsif` conditions' do
expect_offense(<<~RUBY)
def foo(a)
if a == 'foo' || a == 'bar'
^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
elsif a == 'baz' || a == 'qux'
^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
elsif a == 'quux'
end
end
RUBY
expect_correction(<<~RUBY)
def foo(a)
if ['foo', 'bar'].include?(a)
elsif ['baz', 'qux'].include?(a)
elsif a == 'quux'
end
end
RUBY
end
it 'registers an offense and corrects when expression with more comparisons precedes an expression with less comparisons' do
expect_offense(<<~RUBY)
a = 1
a == 1 || a == 2 || a == 3
^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
a == 1 || a == 2
^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
RUBY
expect_correction(<<~RUBY)
a = 1
[1, 2, 3].include?(a)
[1, 2].include?(a)
RUBY
end
it 'does not register an offense for comparing multiple literal strings' do
expect_no_offenses(<<~RUBY)
if "a" == "a" || "a" == "c"
print "a"
end
RUBY
end
it 'does not register an offense for comparing multiple int literals' do
expect_no_offenses(<<~RUBY)
if 1 == 1 || 1 == 2
print 1
end
RUBY
end
it 'does not register an offense for comparing lvars' do
expect_no_offenses(<<~RUBY)
a = "a"
b = "b"
if a == "a" || b == "b"
print a
end
RUBY
end
it 'does not register an offense for comparing lvars when a string is on the lefthand side' do
expect_no_offenses(<<~RUBY)
a = "a"
b = "b"
if a == "a" || "b" == b
print a
end
RUBY
end
it 'does not register an offense for a == b || b == a' do
expect_no_offenses(<<~RUBY)
a = "a"
b = "b"
if a == b || b == a
print a
end
RUBY
end
it 'does not register an offense for a duplicated condition' do
expect_no_offenses(<<~RUBY)
a = "a"
b = "b"
if a == b || a == b
print a
end
RUBY
end
it 'does not register an offense for Array#include?' do
expect_no_offenses(<<~RUBY)
a = "a"
if ["a", "b", "c"].include? a
print a
end
RUBY
end
context 'when `AllowMethodComparison: true`' do
let(:cop_config) { { 'AllowMethodComparison' => true } }
it 'does not register an offense when using multiple method calls' do
expect_no_offenses(<<~RUBY)
col = loc.column
if col == before.column || col == after.column
do_something
end
RUBY
end
it 'does not register an offense when using multiple safe navigation method calls' do
expect_no_offenses(<<~RUBY)
col = loc.column
if col == before&.column || col == after&.column
do_something
end
RUBY
end
it 'registers an offense and corrects when `var` is compared multiple times after a method call' do
expect_offense(<<~RUBY)
var = do_something
var == foo || var == 'bar' || var == 'baz'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
RUBY
expect_correction(<<~RUBY)
var = do_something
var == foo || ['bar', 'baz'].include?(var)
RUBY
end
it 'registers an offense and corrects when comparing with hash access on rhs' do
expect_offense(<<~RUBY)
if a[:key] == 'a' || a[:key] == 'b'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
if ['a', 'b'].include?(a[:key])
print a
end
RUBY
end
it 'registers an offense and corrects when comparing with hash access on lhs' do
expect_offense(<<~RUBY)
if 'a' == a[:key] || 'b' == a[:key]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
if ['a', 'b'].include?(a[:key])
print a
end
RUBY
end
it 'registers an offense and corrects when comparing with safe navigation method call on rhs' do
expect_offense(<<~RUBY)
if a&.do_something == 'a' || a&.do_something == 'b'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
if ['a', 'b'].include?(a&.do_something)
print a
end
RUBY
end
it 'registers an offense and corrects when comparing with safe navigation method call on lhs' do
expect_offense(<<~RUBY)
if 'a' == a&.do_something || 'b' == a&.do_something
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
print a
end
RUBY
expect_correction(<<~RUBY)
if ['a', 'b'].include?(a&.do_something)
print a
end
RUBY
end
end
it 'does not register an offense when comparing two sides of the disjunction is unrelated' do
expect_no_offenses(<<~RUBY)
def do_something(foo, bar)
bar.do_something == bar || foo == :sym
end
RUBY
end
context 'when `AllowMethodComparison: false`' do
let(:cop_config) { { 'AllowMethodComparison' => false } }
it 'registers an offense and corrects when using multiple method calls' do
expect_offense(<<~RUBY)
col = loc.column
if col == before.column || col == after.column
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
do_something
end
RUBY
expect_correction(<<~RUBY)
col = loc.column
if [before.column, after.column].include?(col)
do_something
end
RUBY
end
it 'registers an offense and corrects when `var` is compared multiple times after a method call' do
expect_offense(<<~RUBY)
var = do_something
var == foo || var == 'bar' || var == 'baz'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
RUBY
expect_correction(<<~RUBY)
var = do_something
[foo, 'bar', 'baz'].include?(var)
RUBY
end
it 'does not register an offense when comparing with hash access on rhs' do
expect_no_offenses(<<~RUBY)
if a[:key] == 'a' || a[:key] == 'b'
print a
end
RUBY
end
it 'does not register an offense when comparing with hash access on lhs' do
expect_no_offenses(<<~RUBY)
if 'a' == a[:key] || 'b' == a[:key]
print a
end
RUBY
end
it 'does not register an offense when comparing with safe navigation method call on rhs' do
expect_no_offenses(<<~RUBY)
if a&.do_something == 'a' || a&.do_something == 'b'
print a
end
RUBY
end
it 'does not register an offense when comparing with safe navigation method call on lhs' do
expect_no_offenses(<<~RUBY)
if 'a' == a&.do_something || 'b' == a&.do_something
print a
end
RUBY
end
end
context 'when `ComparisonsThreshold`: 2' do
let(:cop_config) { { 'ComparisonsThreshold' => 2 } }
it 'registers an offense and corrects when `a` is compared twice' do
expect_offense(<<~RUBY)
a = "a"
foo if a == "a" || a == "b"
^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
RUBY
expect_correction(<<~RUBY)
a = "a"
foo if ["a", "b"].include?(a)
RUBY
end
end
context 'when `ComparisonsThreshold`: 3' do
let(:cop_config) { { 'ComparisonsThreshold' => 3 } }
it 'registers an offense and corrects when `a` is compared thrice' do
expect_offense(<<~RUBY)
a = "a"
foo if a == "a" || a == "b" || a == "c"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid comparing a variable with multiple items in a conditional, use `Array#include?` instead.
RUBY
expect_correction(<<~RUBY)
a = "a"
foo if ["a", "b", "c"].include?(a)
RUBY
end
it 'does not register an offense when `a` is compared twice' do
expect_no_offenses(<<~RUBY)
a = "a"
foo if a == "a" || a == "b"
RUBY
end
it 'does not register an offense when `a` is compared twice in multiple expressions' do
expect_no_offenses(<<~RUBY)
a = "a"
foo if a == "a" || a == "b"
bar if a == "a" || a == "b"
RUBY
end
it 'does not register an offense when `a` is compared twice in different contexts expressions' do
expect_no_offenses(<<~RUBY)
def foo(a)
a == "a" || a == "b"
end
def bar(a)
a == "a" || a == "b"
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/select_by_regexp_spec.rb | spec/rubocop/cop/style/select_by_regexp_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SelectByRegexp, :config do
shared_examples 'regexp match' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
context "with #{method}" do
it 'registers an offense and corrects for `match?`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| x.match? /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `Regexp#match?`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| /regexp/.match? x }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `blockvar =~ regexp`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| x =~ /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `blockvar =~ lvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array.#{method} { |x| x =~ lvar }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
lvar = /regexp/
array.#{correction}(lvar)
RUBY
end
it 'registers an offense and corrects for `regexp =~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| /regexp/ =~ x }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `lvar =~ blockvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array.#{method} { |x| lvar =~ x }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
lvar = /regexp/
array.#{correction}(lvar)
RUBY
end
it 'registers an offense and corrects when there is no explicit regexp' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| x =~ y }
^^^^^^^{method}^^^^^^^^^^^^^^^ #{message}
array.#{method} { |x| x =~ REGEXP }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^ #{message}
array.#{method} { |x| x =~ foo.bar.baz(quux) }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(y)
array.#{correction}(REGEXP)
array.#{correction}(foo.bar.baz(quux))
RUBY
end
it 'registers an offense and corrects with a multiline block' do
expect_offense(<<~RUBY, method: method)
array.#{method} do |x|
^^^^^^^{method}^^^^^^^ #{message}
x.match? /regexp/
end
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'does not register an offense when there is no block' do
expect_no_offenses(<<~RUBY)
array.#{method}
RUBY
end
it 'does not register an offense when given a proc' do
expect_no_offenses(<<~RUBY)
array.#{method}(&:even?)
RUBY
end
it 'does not register an offense when the block does not match a regexp' do
expect_no_offenses(<<~RUBY)
array.#{method} { |x| x.even? }
RUBY
end
it 'does not register an offense when the block has multiple expressions' do
expect_no_offenses(<<~RUBY)
array.#{method} do |x|
next if x.even?
x.match? /regexp/
end
RUBY
end
it 'does not register an offense when the block arity is not 1' do
expect_no_offenses(<<~RUBY)
obj.#{method} { |x, y| y.match? /regexp/ }
RUBY
end
it 'does not register an offense when the block uses an external variable in a regexp match' do
expect_no_offenses(<<~RUBY)
array.#{method} { |x| y.match? /regexp/ }
RUBY
end
it 'does not register an offense when the block param is a method argument' do
expect_no_offenses(<<~RUBY)
array.#{method} { |x| /regexp/.match?(foo(x)) }
RUBY
end
it 'does not register an offense when the block body is empty' do
expect_no_offenses(<<~RUBY)
array.#{method} { }
RUBY
end
it 'registers an offense and corrects without a receiver' do
expect_offense(<<~RUBY, method: method)
#{method} { |x| x.match?(/regexp/) }
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects when the receiver is an array' do
expect_offense(<<~RUBY, method: method)
[].#{method} { |x| x.match?(/regexp/) }
^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
foo.to_a.#{method} { |x| x.match?(/regexp/) }
^^^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
[].#{correction}(/regexp/)
foo.to_a.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects when the receiver is a range' do
expect_offense(<<~RUBY, method: method)
('aaa'...'abc').#{method} { |x| x.match?(/ab/) }
^^^^^^^^^^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
('aaa'...'abc').#{correction}(/ab/)
RUBY
end
it 'registers an offense and corrects when the receiver is a set' do
expect_offense(<<~RUBY, method: method)
Set.new.#{method} { |x| x.match?(/regexp/) }
^^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
[].to_set.#{method} { |x| x.match?(/regexp/) }
^^^^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
Set.new.#{correction}(/regexp/)
[].to_set.#{correction}(/regexp/)
RUBY
end
it 'does not register an offense when the receiver is a hash literal' do
expect_no_offenses(<<~RUBY)
{}.#{method} { |x| x.match? /regexp/ }
{ foo: :bar }.#{method} { |x| x.match? /regexp/ }
RUBY
end
it 'does not register an offense when the receiver is `Hash.new`' do
expect_no_offenses(<<~RUBY)
Hash.new.#{method} { |x| x.match? /regexp/ }
Hash.new(:default).#{method} { |x| x.match? /regexp/ }
Hash.new { |hash, key| :default }.#{method} { |x| x.match? /regexp/ }
RUBY
end
it 'does not register an offense when the receiver is `Hash[]`' do
expect_no_offenses(<<~RUBY)
Hash[h].#{method} { |x| x.match? /regexp/ }
Hash[:foo, 0, :bar, 1].#{method} { |x| x.match? /regexp/ }
RUBY
end
it 'does not register an offense when the receiver is `to_h`' do
expect_no_offenses(<<~RUBY)
to_h.#{method} { |x| x.match? /regexp/ }
foo.to_h.#{method} { |x| x.match? /regexp/ }
RUBY
end
it 'does not register an offense when the receiver is `to_hash`' do
expect_no_offenses(<<~RUBY)
to_hash.#{method} { |x| x.match? /regexp/ }
foo.to_hash.#{method} { |x| x.match? /regexp/ }
RUBY
end
it 'registers an offense if `to_h` is in the receiver chain but not the actual receiver' do
# Although there is a `to_h` in the chain, we cannot be sure
# of the type of the ultimate receiver.
expect_offense(<<~RUBY, method: method)
foo.to_h.bar.#{method} { |x| x.match? /regexp/ }
^^^^^^^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
foo.to_h.bar.#{correction}(/regexp/)
RUBY
end
it 'does not register an offense when the receiver is `ENV`' do
expect_no_offenses(<<~RUBY)
ENV.#{method} { |x| x.match? /regexp/ }
::ENV.#{method} { |x| x.match? /regexp/ }
RUBY
end
end
end
shared_examples 'regexp match with `numblock`s' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
it 'registers an offense and corrects for `match?`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { _1.match? /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `match?` with safe navigation' do
expect_offense(<<~RUBY, method: method)
array&.#{method} { _1.match? /regexp/ }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array&.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `Regexp#match?`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { /regexp/.match?(_1) }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `blockvar =~ regexp`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { _1 =~ /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `regexp =~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { /regexp/ =~ _1 }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'does not register an offense if there is more than one numbered param' do
expect_no_offenses(<<~RUBY)
array.#{method} { _1 =~ _2 }
RUBY
end
it 'does not register an offense when the param is a method argument' do
expect_no_offenses(<<~RUBY)
array.#{method} { /regexp/.match?(foo(_1)) }
RUBY
end
it 'does not register an offense when using `match?` without a receiver' do
expect_no_offenses(<<~RUBY)
array.#{method} { |item| match?(item) }
RUBY
end
end
shared_examples 'regexp match with `itblock`s' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
it 'registers an offense and corrects for `match?`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { it.match? /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `match?` with safe navigation' do
expect_offense(<<~RUBY, method: method)
array&.#{method} { it.match? /regexp/ }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array&.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `Regexp#match?`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { /regexp/.match?(it) }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `blockvar =~ regexp`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { it =~ /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `regexp =~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { /regexp/ =~ it }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'does not register an offense when the param is a method argument' do
expect_no_offenses(<<~RUBY)
array.#{method} { /regexp/.match?(foo(it)) }
RUBY
end
it 'does not register an offense when using `match?` without a receiver' do
expect_no_offenses(<<~RUBY)
array.#{method} { |item| match?(item) }
RUBY
end
end
shared_examples 'regexp match with safe navigation' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
it 'registers an offense and corrects for `match?`' do
expect_offense(<<~RUBY, method: method)
array&.#{method} { |x| x.match? /regexp/ }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array&.#{correction}(/regexp/)
RUBY
end
it 'does not register an offense when the receiver is `Hash.new`' do
expect_no_offenses(<<~RUBY)
Hash&.new.#{method} { |x| x.match? /regexp/ }
Hash&.new { |hash, key| :default }.#{method} { |x| x.match? /regexp/ }
RUBY
end
it 'does not register an offense when the receiver is `to_h`' do
expect_no_offenses(<<~RUBY)
foo&.to_h.#{method} { |x| x.match? /regexp/ }
RUBY
end
it 'does not register an offense when the receiver is `to_hash`' do
expect_no_offenses(<<~RUBY)
foo&.to_hash.#{method} { |x| x.match? /regexp/ }
RUBY
end
end
shared_examples 'regexp mismatch' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
context "with #{method}" do
it 'registers an offense and corrects for `blockvar !~ regexp`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| x !~ /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `blockvar !~ lvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array.#{method} { |x| x !~ lvar }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
lvar = /regexp/
array.#{correction}(lvar)
RUBY
end
it 'registers an offense and corrects for `regexp !~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| /regexp/ !~ x }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `lvar !~ blockvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array.#{method} { |x| lvar !~ x }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
lvar = /regexp/
array.#{correction}(lvar)
RUBY
end
it 'registers an offense and corrects when there is no explicit regexp' do
expect_offense(<<~RUBY, method: method)
array.#{method} { |x| x !~ y }
^^^^^^^{method}^^^^^^^^^^^^^^^ #{message}
array.#{method} { |x| x !~ REGEXP }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^ #{message}
array.#{method} { |x| x !~ foo.bar.baz(quux) }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(y)
array.#{correction}(REGEXP)
array.#{correction}(foo.bar.baz(quux))
RUBY
end
end
end
shared_examples 'regexp mismatch with `numblock`s' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
it 'registers an offense and corrects for `blockvar !~ regexp`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { _1 !~ /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `regexp !~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { /regexp/ !~ _1 }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'does not register an offense if there is more than one numbered param' do
expect_no_offenses(<<~RUBY)
array.#{method} { _1 !~ _2 }
RUBY
end
end
shared_examples 'regexp mismatch with `itblock`s' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
it 'registers an offense and corrects for `blockvar !~ regexp`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { it !~ /regexp/ }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `regexp !~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array.#{method} { /regexp/ !~ it }
^^^^^^^{method}^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array.#{correction}(/regexp/)
RUBY
end
end
shared_examples 'regexp mismatch with safe navigation' do |method, correction|
message = "Prefer `#{correction}` to `#{method}` with a regexp match."
context "with #{method}" do
it 'registers an offense and corrects for `blockvar !~ regexp`' do
expect_offense(<<~RUBY, method: method)
array&.#{method} { |x| x !~ /regexp/ }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array&.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `blockvar !~ lvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array&.#{method} { |x| x !~ lvar }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
lvar = /regexp/
array&.#{correction}(lvar)
RUBY
end
it 'registers an offense and corrects for `regexp !~ blockvar`' do
expect_offense(<<~RUBY, method: method)
array&.#{method} { |x| /regexp/ !~ x }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array&.#{correction}(/regexp/)
RUBY
end
it 'registers an offense and corrects for `lvar !~ blockvar`' do
expect_offense(<<~RUBY, method: method)
lvar = /regexp/
array&.#{method} { |x| lvar !~ x }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
lvar = /regexp/
array&.#{correction}(lvar)
RUBY
end
it 'registers an offense and corrects when there is no explicit regexp' do
expect_offense(<<~RUBY, method: method)
array&.#{method} { |x| x !~ y }
^^^^^^^^{method}^^^^^^^^^^^^^^^ #{message}
array&.#{method} { |x| x !~ REGEXP }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^ #{message}
array&.#{method} { |x| x !~ foo.bar.baz(quux) }
^^^^^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message}
RUBY
expect_correction(<<~RUBY)
array&.#{correction}(y)
array&.#{correction}(REGEXP)
array&.#{correction}(foo.bar.baz(quux))
RUBY
end
end
end
context 'when Ruby >= 3.4', :ruby34 do
it_behaves_like('regexp match with `itblock`s', 'select', 'grep')
it_behaves_like('regexp match with `itblock`s', 'find_all', 'grep')
it_behaves_like('regexp match with `itblock`s', 'filter', 'grep')
it_behaves_like('regexp mismatch with `itblock`s', 'reject', 'grep')
it_behaves_like('regexp match with `itblock`s', 'reject', 'grep_v')
it_behaves_like('regexp mismatch with `itblock`s', 'select', 'grep_v')
it_behaves_like('regexp mismatch with `itblock`s', 'find_all', 'grep_v')
it_behaves_like('regexp mismatch with `itblock`s', 'filter', 'grep_v')
end
context 'when Ruby >= 2.7', :ruby27 do
it_behaves_like('regexp match with `numblock`s', 'select', 'grep')
it_behaves_like('regexp match with `numblock`s', 'find_all', 'grep')
it_behaves_like('regexp match with `numblock`s', 'filter', 'grep')
it_behaves_like('regexp mismatch with `numblock`s', 'reject', 'grep')
it_behaves_like('regexp match with `numblock`s', 'reject', 'grep_v')
it_behaves_like('regexp mismatch with `numblock`s', 'select', 'grep_v')
it_behaves_like('regexp mismatch with `numblock`s', 'find_all', 'grep_v')
it_behaves_like('regexp mismatch with `numblock`s', 'filter', 'grep_v')
end
context 'when Ruby >= 2.6', :ruby26 do
it_behaves_like('regexp match', 'filter', 'grep')
it_behaves_like('regexp match with safe navigation', 'filter', 'grep')
it_behaves_like('regexp mismatch', 'filter', 'grep_v')
it_behaves_like('regexp mismatch with safe navigation', 'filter', 'grep_v')
end
context 'when Ruby <= 2.5', :ruby25, unsupported_on: :prism do
it 'does not register an offense when `filter` with regexp match' do
expect_no_offenses(<<~RUBY)
array.filter { |x| x =~ /regexp/ }
RUBY
end
it 'does not register an offense when `filter` with regexp mismatch' do
expect_no_offenses(<<~RUBY)
array.filter { |x| x !~ /regexp/ }
RUBY
end
end
context 'when Ruby >= 2.3', :ruby23 do
it_behaves_like('regexp match', 'select', 'grep')
it_behaves_like('regexp match with safe navigation', 'select', 'grep')
it_behaves_like('regexp match', 'find_all', 'grep')
it_behaves_like('regexp match with safe navigation', 'find_all', 'grep')
it_behaves_like('regexp mismatch', 'reject', 'grep')
it_behaves_like('regexp mismatch with safe navigation', 'reject', 'grep')
it_behaves_like('regexp match', 'reject', 'grep_v')
it_behaves_like('regexp match with safe navigation', 'reject', 'grep_v')
it_behaves_like('regexp mismatch', 'select', 'grep_v')
it_behaves_like('regexp mismatch with safe navigation', 'select', 'grep_v')
it_behaves_like('regexp mismatch', 'find_all', 'grep_v')
it_behaves_like('regexp mismatch with safe navigation', 'find_all', 'grep_v')
end
context 'when Ruby <= 2.2', :ruby22, unsupported_on: :prism do
it_behaves_like('regexp match', 'select', 'grep')
it_behaves_like('regexp match', 'find_all', 'grep')
it_behaves_like('regexp mismatch', 'reject', 'grep')
it 'does not register an offense when `reject` with regexp match' do
expect_no_offenses(<<~RUBY)
array.reject { |x| x =~ /regexp/ }
RUBY
end
it 'does not register an offense when `select` with regexp mismatch' do
expect_no_offenses(<<~RUBY)
array.select { |x| x !~ /regexp/ }
RUBY
end
it 'does not register an offense when `find_all` with regexp mismatch' do
expect_no_offenses(<<~RUBY)
array.find_all { |x| x !~ /regexp/ }
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_if_else_condition_spec.rb | spec/rubocop/cop/style/negated_if_else_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NegatedIfElseCondition, :config do
it 'registers an offense and corrects when negating condition with `!` for `if-else`' do
expect_offense(<<~RUBY)
if !x
^^^^^ Invert the negated condition and swap the if-else branches.
do_something
else
do_something_else
end
RUBY
expect_correction(<<~RUBY)
if x
do_something_else
else
do_something
end
RUBY
end
it 'registers an offense and corrects when negating condition with `not` for `if-else`' do
expect_offense(<<~RUBY)
if not x
^^^^^^^^ Invert the negated condition and swap the if-else branches.
do_something
else
do_something_else
end
RUBY
expect_correction(<<~RUBY)
if x
do_something_else
else
do_something
end
RUBY
end
it 'registers an offense and corrects when negating condition with `not` for ternary' do
expect_offense(<<~RUBY)
!x ? do_something : do_something_else
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Invert the negated condition and swap the ternary branches.
RUBY
expect_correction(<<~RUBY)
x ? do_something_else : do_something
RUBY
end
it 'registers an offense and corrects a multiline ternary' do
expect_offense(<<~RUBY)
!x ?
^^^^ Invert the negated condition and swap the ternary branches.
do_something :
do_something_else # comment
RUBY
expect_correction(<<~RUBY)
x ?
do_something_else :
do_something # comment
RUBY
end
shared_examples 'negation method' do |method, inverted_method|
it "registers an offense and corrects when negating condition with `#{method}` for `if-else`" do
expect_offense(<<~RUBY, method: method)
if x %{method} y
^^^^^^{method}^^ Invert the negated condition and swap the if-else branches.
do_something
else
do_something_else
end
RUBY
expect_correction(<<~RUBY)
if x #{inverted_method} y
do_something_else
else
do_something
end
RUBY
end
it "registers an offense and corrects when negating condition with `#{method}` for ternary" do
expect_offense(<<~RUBY, method: method)
x %{method} y ? do_something : do_something_else
^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Invert the negated condition and swap the ternary branches.
RUBY
expect_correction(<<~RUBY)
x #{inverted_method} y ? do_something_else : do_something
RUBY
end
it "registers an offense and corrects when negating condition with `#{method}` in parentheses for `if-else`" do
expect_offense(<<~RUBY, method: method)
if (x %{method} y)
^^^^^^^{method}^^^ Invert the negated condition and swap the if-else branches.
do_something
else
do_something_else
end
RUBY
expect_correction(<<~RUBY)
if (x #{inverted_method} y)
do_something_else
else
do_something
end
RUBY
end
it "registers an offense and corrects when negating condition with `#{method}` in parentheses for ternary" do
expect_offense(<<~RUBY, method: method)
(x %{method} y) ? do_something : do_something_else
^^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Invert the negated condition and swap the ternary branches.
RUBY
expect_correction(<<~RUBY)
(x #{inverted_method} y) ? do_something_else : do_something
RUBY
end
it "registers an offense and corrects when negating condition with `#{method}` in begin-end for `if-else`" do
expect_offense(<<~RUBY, method: method)
if begin
^^^^^^^^ Invert the negated condition and swap the if-else branches.
x %{method} y
end
do_something
else
do_something_else
end
RUBY
expect_correction(<<~RUBY)
if begin
x #{inverted_method} y
end
do_something_else
else
do_something
end
RUBY
end
it "registers an offense and corrects when negating condition with `#{method}` in begin-end for ternary" do
expect_offense(<<~RUBY, method: method)
begin
^^^^^ Invert the negated condition and swap the ternary branches.
x %{method} y
end ? do_something : do_something_else
RUBY
expect_correction(<<~RUBY)
begin
x #{inverted_method} y
end ? do_something_else : do_something
RUBY
end
end
it_behaves_like('negation method', '!=', '==')
it_behaves_like('negation method', '!~', '=~')
it 'registers an offense and corrects nested `if-else` with negated condition' do
expect_offense(<<~RUBY)
if !x
^^^^^ Invert the negated condition and swap the if-else branches.
do_something
else
if !y
^^^^^ Invert the negated condition and swap the if-else branches.
do_something_else_1
else
do_something_else_2
end
end
RUBY
expect_correction(<<~RUBY)
if x
if y
do_something_else_2
else
do_something_else_1
end
else
do_something
end
RUBY
end
it 'registers an offense when using negated condition and `if` branch body is empty' do
expect_offense(<<~RUBY)
if !condition.nil?
^^^^^^^^^^^^^^^^^^ Invert the negated condition and swap the if-else branches.
else
foo = 42
end
RUBY
expect_correction(<<~RUBY)
if condition.nil?
foo = 42
end
RUBY
end
it 'does not register an offense when the `else` branch is empty' do
expect_no_offenses(<<~RUBY)
if !condition.nil?
foo = 42
else
end
RUBY
end
it 'does not register an offense when both branches are empty' do
expect_no_offenses(<<~RUBY)
if !condition.nil?
else
end
RUBY
end
it 'does not crash when using `()` as a condition' do
expect_no_offenses(<<~RUBY)
if ()
foo
else
bar
end
RUBY
end
it 'moves comments to correct branches during autocorrect' do
expect_offense(<<~RUBY)
if !condition.nil?
^^^^^^^^^^^^^^^^^^ Invert the negated condition and swap the if-else branches.
# part B
# and foo is 39
foo = 39
else
# part A
# and foo is 42
foo = 42
end
RUBY
expect_correction(<<~RUBY)
if condition.nil?
# part A
# and foo is 42
foo = 42
else
# part B
# and foo is 39
foo = 39
end
RUBY
end
it 'works with comments and multiple statements' do
expect_offense(<<~RUBY)
if !condition.nil?
^^^^^^^^^^^^^^^^^^ Invert the negated condition and swap the if-else branches.
# part A
# and foo is 1 and bar is 2
foo = 1
bar = 2
else
# part B
# and foo is 3 and bar is 4
foo = 3
bar = 4
end
RUBY
expect_correction(<<~RUBY)
if condition.nil?
# part B
# and foo is 3 and bar is 4
foo = 3
bar = 4
else
# part A
# and foo is 1 and bar is 2
foo = 1
bar = 2
end
RUBY
end
it 'works with comments when one branch is a begin and the other is not' do
expect_offense(<<~RUBY)
if !condition
^^^^^^^^^^^^^ Invert the negated condition and swap the if-else branches.
# comment
do_a
do_b
else
do_c
end
RUBY
expect_correction(<<~RUBY)
if condition
do_c
else
# comment
do_a
do_b
end
RUBY
end
it 'works with comments when neither branch is a begin node' do
expect_offense(<<~RUBY)
if !condition
^^^^^^^^^^^^^ Invert the negated condition and swap the if-else branches.
# comment
do_b
else
do_c
end
RUBY
expect_correction(<<~RUBY)
if condition
do_c
else
# comment
do_b
end
RUBY
end
it 'works with duplicate nodes' do
expect_offense(<<~RUBY)
# outer comment
do_a
if !condition
^^^^^^^^^^^^^ Invert the negated condition and swap the if-else branches.
# comment
do_a
else
do_c
end
RUBY
expect_correction(<<~RUBY)
# outer comment
do_a
if condition
do_c
else
# comment
do_a
end
RUBY
end
it 'correctly moves comments at the end of branches' do
expect_offense(<<~RUBY)
if !condition
^^^^^^^^^^^^^ Invert the negated condition and swap the if-else branches.
do_a
# comment
else
do_c
end
RUBY
expect_correction(<<~RUBY)
if condition
do_c
else
do_a
# comment
end
RUBY
end
it 'does not register an offense when negating condition for `if-elsif`' do
expect_no_offenses(<<~RUBY)
if !x
do_something
elsif !y
do_something_else
else
do_another_thing
end
RUBY
end
it 'does not register an offense when only part of the condition is negated' do
expect_no_offenses(<<~RUBY)
if !x && y
do_something
else
do_another_thing
end
RUBY
end
it 'does not register an offense when `if` with `!!` condition' do
expect_no_offenses(<<~RUBY)
if !!x
do_something
else
do_another_thing
end
RUBY
end
it 'does not register an offense when `if` with negated condition has no `else` branch' do
expect_no_offenses(<<~RUBY)
if !x
do_something
end
RUBY
end
it 'does not register an offense for != with multiple arguments' do
expect_no_offenses(<<~RUBY)
if foo.!=(bar, baz)
do_a
else
do_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/single_line_do_end_block_spec.rb | spec/rubocop/cop/style/single_line_do_end_block_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SingleLineDoEndBlock, :config do
it 'registers an offense when using single line `do`...`end`' do
expect_offense(<<~RUBY)
foo do bar end
^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
foo do
bar#{' '}
end
RUBY
end
it 'registers an offense when using single line `do`...`end` with no body' do
expect_offense(<<~RUBY)
foo do end
^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
foo do
#{' '}
end
RUBY
end
it 'registers an offense when using single line `do`...`end` with block argument' do
expect_offense(<<~RUBY)
foo do |arg| bar(arg) end
^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
foo do |arg|
bar(arg)#{' '}
end
RUBY
end
it 'registers an offense when using single line `do`...`end` with numbered block argument' do
expect_offense(<<~RUBY)
foo do bar(_1) end
^^^^^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
foo do
bar(_1)#{' '}
end
RUBY
end
it 'registers an offense when using single line `do`...`end` with `it` block argument', :ruby34 do
expect_offense(<<~RUBY)
foo do bar(it) end
^^^^^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
foo do
bar(it)#{' '}
end
RUBY
end
it 'registers an offense when using single line `do`...`end` with heredoc body' do
expect_offense(<<~RUBY)
foo do <<~EOS end
^^^^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
text
EOS
RUBY
expect_correction(<<~RUBY)
foo do
<<~EOS#{' '}
text
EOS
end
RUBY
end
it 'registers an offense when using single line `do`...`end` with `->` block' do
expect_offense(<<~RUBY)
->(arg) do foo arg end
^^^^^^^^^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
->(arg) do
foo arg#{' '}
end
RUBY
end
it 'registers an offense when using single line `do`...`end` with `lambda` block' do
expect_offense(<<~RUBY)
lambda do |arg| foo(arg) end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
lambda do |arg|
foo(arg)#{' '}
end
RUBY
end
it 'does not register an offense when using multiline `do`...`end`' do
expect_no_offenses(<<~RUBY)
foo do
bar
end
RUBY
end
it 'does not register an offense when using single line `{`...`}`' do
expect_no_offenses(<<~RUBY)
foo { bar }
RUBY
end
context 'when `Layout/LineLength` is disabled' do
let(:other_cops) { { 'Layout/LineLength' => { 'Enabled' => false } } }
it 'registers an offense when using single line `do`...`end`' do
expect_offense(<<~RUBY)
foo do bar end
^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
foo do
bar#{' '}
end
RUBY
end
end
context 'when `Layout/RedundantLineBreak` is enabled with `InspectBlocks: true`' do
let(:other_cops) do
{
'Layout/RedundantLineBreak' => { 'Enabled' => true, 'InspectBlocks' => true },
'Layout/LineLength' => { 'Max' => 20 }
}
end
context 'when a block fits on a single line' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
a do b end
RUBY
end
end
context 'when the block does not fit on a single line' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
aaaaaaaaaaaa do bbbbbbbbbbbbb end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer multiline `do`...`end` block.
RUBY
expect_correction(<<~RUBY)
aaaaaaaaaaaa do
bbbbbbbbbbbbb#{' '}
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/colon_method_call_spec.rb | spec/rubocop/cop/style/colon_method_call_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ColonMethodCall, :config do
it 'registers an offense for instance method call' do
expect_offense(<<~RUBY)
test::method_name
^^ Do not use `::` for method calls.
RUBY
expect_correction(<<~RUBY)
test.method_name
RUBY
end
it 'registers an offense for instance method call with arg' do
expect_offense(<<~RUBY)
test::method_name(arg)
^^ Do not use `::` for method calls.
RUBY
expect_correction(<<~RUBY)
test.method_name(arg)
RUBY
end
it 'registers an offense for class method call' do
expect_offense(<<~RUBY)
Class::method_name
^^ Do not use `::` for method calls.
RUBY
expect_correction(<<~RUBY)
Class.method_name
RUBY
end
it 'registers an offense for class method call with arg' do
expect_offense(<<~RUBY)
Class::method_name(arg, arg2)
^^ Do not use `::` for method calls.
RUBY
expect_correction(<<~RUBY)
Class.method_name(arg, arg2)
RUBY
end
it 'does not register an offense for constant access' do
expect_no_offenses('Tip::Top::SOME_CONST')
end
it 'does not register an offense for nested class' do
expect_no_offenses('Tip::Top.some_method')
end
it 'does not register an offense for op methods' do
expect_no_offenses('Tip::Top.some_method[3]')
end
it 'does not register an offense when for constructor methods' do
expect_no_offenses('Tip::Top(some_arg)')
end
it 'does not register an offense for Java static types' do
expect_no_offenses('Java::int')
end
it 'does not register an offense for Java package namespaces' do
expect_no_offenses('Java::com')
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_and_module_children_spec.rb | spec/rubocop/cop/style/class_and_module_children_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ClassAndModuleChildren, :config do
context 'nested style' do
let(:cop_config) { { 'EnforcedStyle' => 'nested' } }
it 'registers an offense for not nested classes' do
expect_offense(<<~RUBY)
class FooClass::BarClass
^^^^^^^^^^^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
module FooClass
class BarClass
end
end
RUBY
end
it 'registers an offense for not nested classes when namespace is defined as a class' do
expect_offense(<<~RUBY)
class FooClass
end
class FooClass::BarClass
^^^^^^^^^^^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
class FooClass
end
class FooClass
class BarClass
end
end
RUBY
end
it 'registers an offense for not nested classes when namespace is defined as a module' do
expect_offense(<<~RUBY)
module FooClass
end
class FooClass::BarClass
^^^^^^^^^^^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
module FooClass
end
module FooClass
class BarClass
end
end
RUBY
end
it 'registers an offense for not nested classes with explicit superclass' do
expect_offense(<<~RUBY)
class FooClass::BarClass < Super
^^^^^^^^^^^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
module FooClass
class BarClass < Super
end
end
RUBY
end
it 'registers an offense for not nested modules' do
expect_offense(<<~RUBY)
module FooModule::BarModule
^^^^^^^^^^^^^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
module FooModule
module BarModule
end
end
RUBY
end
it 'registers an offense for partially nested classes' do
expect_offense(<<~RUBY)
class Foo::Bar
^^^^^^^^ Use nested module/class definitions instead of compact style.
class Baz
end
end
RUBY
expect_correction(<<~RUBY)
module Foo
class Bar
class Baz
end
end
end
RUBY
end
it 'registers an offense for partially nested modules' do
expect_offense(<<~RUBY)
module Foo::Bar
^^^^^^^^ Use nested module/class definitions instead of compact style.
module Baz
end
end
RUBY
expect_correction(<<~RUBY)
module Foo
module Bar
module Baz
end
end
end
RUBY
end
it 'preserves comments' do
expect_offense(<<~RUBY)
# top comment
class Foo::Bar # describe Foo::Bar
^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
# top comment
module Foo
class Bar # describe Foo::Bar
end
end
RUBY
end
it 'accepts nested children' do
expect_no_offenses(<<~RUBY)
class FooClass
class BarClass
end
end
module FooModule
module BarModule
end
end
RUBY
end
it 'accepts cbase class name' do
expect_no_offenses(<<~RUBY)
class ::Foo
end
RUBY
end
it 'accepts cbase module name' do
expect_no_offenses(<<~RUBY)
module ::Foo
end
RUBY
end
it 'accepts :: in parent class on inheritance' do
expect_no_offenses(<<~RUBY)
class FooClass
class BarClass
end
end
class BazClass < FooClass::BarClass
end
RUBY
end
it 'accepts compact style when inside another module' do
expect_no_offenses(<<~RUBY)
module Z
module X::Y
end
end
RUBY
end
it 'accepts compact style when inside another class' do
expect_no_offenses(<<~RUBY)
class Z
module X::Y
end
end
RUBY
end
end
context 'compact style' do
let(:cop_config) { { 'EnforcedStyle' => 'compact' } }
it 'registers an offense for classes with nested children' do
expect_offense(<<~RUBY)
class FooClass
^^^^^^^^ Use compact module/class definition instead of nested style.
class BarClass
end
end
RUBY
expect_correction(<<~RUBY)
class FooClass::BarClass
end
RUBY
end
it 'registers an offense for modules with nested children' do
expect_offense(<<~RUBY)
module FooModule
^^^^^^^^^ Use compact module/class definition instead of nested style.
module BarModule
def method_example
end
end
end
RUBY
expect_correction(<<~RUBY)
module FooModule::BarModule
def method_example
end
end
RUBY
end
it 'correctly indents heavily nested children' do
expect_offense(<<~RUBY)
module FooModule
^^^^^^^^^ Use compact module/class definition instead of nested style.
module BarModule
module BazModule
module QuxModule
CONST = 1
def method_example
end
end
end
end
end
RUBY
expect_correction(<<~RUBY)
module FooModule::BarModule::BazModule::QuxModule
CONST = 1
def method_example
end
end
RUBY
end
it 'registers an offense for classes with partially nested children' do
expect_offense(<<~RUBY)
class Foo::Bar
^^^^^^^^ Use compact module/class definition instead of nested style.
class Baz
end
end
class Foo
^^^ Use compact module/class definition instead of nested style.
class Bar::Baz
end
end
RUBY
expect_correction(<<~RUBY)
class Foo::Bar::Baz
end
class Foo::Bar::Baz
end
RUBY
end
it 'registers an offense for deeply nested children' do
expect_offense(<<~RUBY)
class Foo
^^^ Use compact module/class definition instead of nested style.
class Bar
class Baz
end
end
end
RUBY
expect_correction(<<~RUBY)
class Foo::Bar::Baz
end
RUBY
end
it 'registers an offense for modules with partially nested children' do
expect_offense(<<~RUBY)
module Foo::Bar
^^^^^^^^ Use compact module/class definition instead of nested style.
module Baz
end
end
module Foo
^^^ Use compact module/class definition instead of nested style.
module Bar::Baz
end
end
RUBY
expect_correction(<<~RUBY)
module Foo::Bar::Baz
end
module Foo::Bar::Baz
end
RUBY
end
it 'preserves comments between classes' do
expect_offense(<<~RUBY)
# describe Foo
# more Foo
class Foo
^^^ Use compact module/class definition instead of nested style.
# describe Bar
# more Bar
class Bar
end
end
RUBY
expect_correction(<<~RUBY)
# describe Foo
# more Foo
# describe Bar
# more Bar
class Foo::Bar
end
RUBY
end
it 'accepts compact style for classes/modules' do
expect_no_offenses(<<~RUBY)
class FooClass::BarClass
end
module FooClass::BarModule
end
RUBY
end
it 'accepts nesting for classes/modules with more than one child' do
expect_no_offenses(<<~RUBY)
class FooClass
class BarClass
end
class BazClass
end
end
module FooModule
module BarModule
end
class BazModule
end
end
RUBY
end
it 'accepts class/module with single method' do
expect_no_offenses(<<~RUBY)
class FooClass
def bar_method
end
end
RUBY
end
it 'accepts nesting for classes with an explicit superclass' do
expect_no_offenses(<<~RUBY)
class FooClass < Super
class BarClass
end
end
RUBY
end
it 'registers an offense for tab-intended nested children' do
expect_offense(<<~RUBY)
module A
^ Use compact module/class definition instead of nested style.
\tmodule B
\t\tmodule C
\t\t\tbody
\t\tend
\tend
end
RUBY
expect_correction(<<~RUBY)
module A::B::C
\t\t\tbody
end
RUBY
end
context 'with unindented nested nodes' do
it 'registers an offense and autocorrects unindented class' do
expect_offense(<<~RUBY)
module M
^ Use compact module/class definition instead of nested style.
class C
end
end
RUBY
expect_correction(<<~RUBY)
class M::C
end
RUBY
end
it 'registers an offense and autocorrects unindented class and method' do
expect_offense(<<~RUBY)
module M
^ Use compact module/class definition instead of nested style.
class C
def foo; 1; end
end
end
RUBY
expect_correction(<<~RUBY)
class M::C
def foo; 1; end
end
RUBY
end
it 'registers an offense and autocorrects unindented method' do
expect_offense(<<~RUBY)
module M
^ Use compact module/class definition instead of nested style.
class C
def foo; 1; end
end
end
RUBY
expect_correction(<<~RUBY)
class M::C
def foo; 1; end
end
RUBY
end
context 'with tab-intended nested nodes' do
it 'registers an offense and autocorrects when 3rd-level module has unintended body' do
expect_offense(<<~RUBY)
module A
^ Use compact module/class definition instead of nested style.
\tmodule B
\t\tmodule C
\t\tbody
\t\tend
\tend
end
RUBY
expect_correction(<<~RUBY)
module A::B::C
\t\tbody
end
RUBY
end
it 'registers an offense and autocorrects when all nested modules have the same indentation' do
expect_offense(<<~RUBY)
module A
^ Use compact module/class definition instead of nested style.
\tmodule B
\tmodule C
\tbody
\tend
\tend
end
RUBY
expect_correction(<<~RUBY)
module A::B::C
\tbody
end
RUBY
end
it 'registers an offense and autocorrects when all nested modules have the same indentation and nested body is intended' do
expect_offense(<<~RUBY)
module A
^ Use compact module/class definition instead of nested style.
\tmodule B
\tmodule C
\t\tbody
\tend
\tend
end
RUBY
expect_correction(<<~RUBY)
module A::B::C
\t\tbody
end
RUBY
end
end
end
context 'with one-liner class definition' do
it 'registers an offense for classes with nested one-liner children' do
expect_offense(<<~RUBY)
class FooClass
^^^^^^^^ Use compact module/class definition instead of nested style.
class BarClass; end
end
RUBY
expect_correction(<<~RUBY)
class FooClass::BarClass
end
RUBY
end
it 'registers an offense when one-liner class definition is 3 levels deep' do
expect_offense(<<~RUBY)
class A < B
class C
^ Use compact module/class definition instead of nested style.
class D; end
end
class E
end
end
RUBY
expect_correction(<<~RUBY)
class A < B
class C::D
end
class E
end
end
RUBY
end
it 'registers an offense when one-liner class definition is 4 levels deep' do
expect_offense(<<~RUBY)
class A < B
class F
class C
^ Use compact module/class definition instead of nested style.
class D; end
end
class E
end
end
end
RUBY
expect_correction(<<~RUBY)
class A < B
class F
class C::D
end
class E
end
end
end
RUBY
end
it 'registers an offense when one-liner class definition has multiple whitespaces before the `end` token' do
expect_offense(<<~RUBY)
class A < B
class C
^ Use compact module/class definition instead of nested style.
class D; end
end
class E
end
end
RUBY
expect_correction(<<~RUBY)
class A < B
class C::D
end
class E
end
end
RUBY
end
end
end
context 'when EnforcedStyleForClasses is set' do
let(:cop_config) do
{ 'EnforcedStyle' => 'nested', 'EnforcedStyleForClasses' => enforced_style_for_classes }
end
context 'EnforcedStyleForClasses: nil' do
let(:enforced_style_for_classes) { nil }
it 'uses the set `EnforcedStyle` for classes' do
expect_offense(<<~RUBY)
class FooClass::BarClass
^^^^^^^^^^^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
module FooClass
class BarClass
end
end
RUBY
end
end
context 'EnforcedStyleForClasses: compact' do
let(:enforced_style_for_classes) { 'compact' }
it 'registers an offense for classes with nested children' do
expect_offense(<<~RUBY)
class FooClass
^^^^^^^^ Use compact module/class definition instead of nested style.
class BarClass
end
end
RUBY
expect_correction(<<~RUBY)
class FooClass::BarClass
end
RUBY
end
end
end
context 'when EnforcedStyleForModules is set' do
let(:cop_config) do
{ 'EnforcedStyle' => 'nested', 'EnforcedStyleForModules' => enforced_style_for_modules }
end
context 'EnforcedStyleForModules: nil' do
let(:enforced_style_for_modules) { nil }
it 'uses the set `EnforcedStyle` for modules' do
expect_offense(<<~RUBY)
module FooModule::BarModule
^^^^^^^^^^^^^^^^^^^^ Use nested module/class definitions instead of compact style.
end
RUBY
expect_correction(<<~RUBY)
module FooModule
module BarModule
end
end
RUBY
end
end
context 'EnforcedStyleForModules: compact' do
let(:enforced_style_for_modules) { 'compact' }
it 'registers an offense for modules with nested children' do
expect_offense(<<~RUBY)
module FooModule
^^^^^^^^^ Use compact module/class definition instead of nested style.
module BarModule
def method_example
end
end
end
RUBY
expect_correction(<<~RUBY)
module FooModule::BarModule
def method_example
end
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/yoda_condition_spec.rb | spec/rubocop/cop/style/yoda_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::YodaCondition, :config do
context 'enforce not yoda' do
let(:cop_config) { { 'EnforcedStyle' => 'forbid_for_all_comparison_operators' } }
it 'accepts method call on receiver on left' do
expect_no_offenses('b.value == 2')
end
it 'accepts safe navigation on left' do
expect_no_offenses('b&.value == 2')
end
it 'accepts instance variable on left' do
expect_no_offenses('@value == 2')
end
it 'accepts class variable on left' do
expect_no_offenses('@@value == 2')
end
it 'accepts variable on left after assign' do
expect_no_offenses('b = 1; b == 2')
end
it 'accepts global variable on left' do
expect_no_offenses('$var == 5')
end
it 'accepts string literal on right' do
expect_no_offenses('foo == "bar"')
end
it 'accepts constant on right' do
expect_no_offenses('foo == BAR')
end
it 'accepts interpolated string on left' do
expect_no_offenses('"#{interpolation}" == foo')
end
it 'accepts interpolated regex on left' do
expect_no_offenses('/#{interpolation}/ == foo')
end
it 'accepts accessor and variable on left in boolean expression' do
expect_no_offenses('foo[0] > "bar" || baz != "baz"')
end
it 'accepts assignment' do
expect_no_offenses('node = last_node.parent')
end
it 'accepts subtraction expression on left of comparison' do
expect_no_offenses('(first_line - second_line) > 0')
end
it 'accepts number on both sides' do
expect_no_offenses('5 == 6')
end
it 'accepts array of numbers on both sides' do
expect_no_offenses('[1, 2, 3] <=> [4, 5, 6]')
end
it 'accepts negation' do
expect_no_offenses('!true')
expect_no_offenses('not true')
end
it 'accepts number on left of <=>' do
expect_no_offenses('0 <=> val')
end
it 'accepts string literal on left of case equality check' do
expect_no_offenses('"foo" === bar')
end
it 'accepts __FILE__ on left in program name check' do
expect_no_offenses('__FILE__ == $0')
expect_no_offenses('__FILE__ == $PROGRAM_NAME')
end
it 'accepts __FILE__ on left in negated program name check' do
expect_no_offenses('__FILE__ != $0')
expect_no_offenses('__FILE__ != $PROGRAM_NAME')
end
it 'registers an offense for string literal on left' do
expect_offense(<<~RUBY)
"foo" == bar
^^^^^^^^^^^^ Reverse the order of the operands `"foo" == bar`.
RUBY
expect_correction(<<~RUBY)
bar == "foo"
RUBY
end
it 'registers an offense for nil on left' do
expect_offense(<<~RUBY)
nil == bar
^^^^^^^^^^ Reverse the order of the operands `nil == bar`.
RUBY
expect_correction(<<~RUBY)
bar == nil
RUBY
end
it 'registers an offense for boolean literal on left' do
expect_offense(<<~RUBY)
false == active?
^^^^^^^^^^^^^^^^ Reverse the order of the operands `false == active?`.
RUBY
expect_correction(<<~RUBY)
active? == false
RUBY
end
it 'registers an offense number on left' do
expect_offense(<<~RUBY)
15 != @foo
^^^^^^^^^^ Reverse the order of the operands `15 != @foo`.
RUBY
expect_correction(<<~RUBY)
@foo != 15
RUBY
end
it 'registers an offense number on left of comparison' do
expect_offense(<<~RUBY)
42 < bar
^^^^^^^^ Reverse the order of the operands `42 < bar`.
RUBY
expect_correction(<<~RUBY)
bar > 42
RUBY
end
it 'registers an offense constant on left of comparison' do
expect_offense(<<~RUBY)
FOO < bar
^^^^^^^^^ Reverse the order of the operands `FOO < bar`.
RUBY
expect_correction(<<~RUBY)
bar > FOO
RUBY
end
context 'within an if or ternary statement' do
it 'registers an offense for number on left in if condition' do
expect_offense(<<~RUBY)
if 10 == my_var; end
^^^^^^^^^^^^ Reverse the order of the operands `10 == my_var`.
RUBY
expect_correction(<<~RUBY)
if my_var == 10; end
RUBY
end
it 'registers an offense for number on left of comparison in if condition' do
expect_offense(<<~RUBY)
if 2 < bar;end
^^^^^^^ Reverse the order of the operands `2 < bar`.
RUBY
expect_correction(<<~RUBY)
if bar > 2;end
RUBY
end
it 'registers an offense for number on left in modifier if' do
expect_offense(<<~RUBY)
foo = 42 if 42 > bar
^^^^^^^^ Reverse the order of the operands `42 > bar`.
RUBY
expect_correction(<<~RUBY)
foo = 42 if bar < 42
RUBY
end
it 'registers an offense for number on left of <= in ternary condition' do
expect_offense(<<~RUBY)
42 <= foo ? bar : baz
^^^^^^^^^ Reverse the order of the operands `42 <= foo`.
RUBY
expect_correction(<<~RUBY)
foo >= 42 ? bar : baz
RUBY
end
it 'registers an offense for number on left of >= in ternary condition' do
expect_offense(<<~RUBY)
42 >= foo ? bar : baz
^^^^^^^^^ Reverse the order of the operands `42 >= foo`.
RUBY
expect_correction(<<~RUBY)
foo <= 42 ? bar : baz
RUBY
end
it 'registers an offense for nil on left in ternary condition' do
expect_offense(<<~RUBY)
nil != foo ? bar : baz
^^^^^^^^^^ Reverse the order of the operands `nil != foo`.
RUBY
expect_correction(<<~RUBY)
foo != nil ? bar : baz
RUBY
end
end
context 'with EnforcedStyle: forbid_for_equality_operators_only' do
let(:cop_config) { { 'EnforcedStyle' => 'forbid_for_equality_operators_only' } }
it 'accepts number on left of comparison' do
expect_no_offenses('42 < bar')
end
it 'accepts nil on left of comparison' do
expect_no_offenses('nil >= baz')
end
it 'accepts mixed order in comparisons' do
expect_no_offenses('3 < a && a < 5')
end
it 'registers an offense for negated equality check' do
expect_offense(<<~RUBY)
42 != answer
^^^^^^^^^^^^ Reverse the order of the operands `42 != answer`.
RUBY
expect_correction(<<~RUBY)
answer != 42
RUBY
end
it 'registers an offense for equality check' do
expect_offense(<<~RUBY)
false == foo
^^^^^^^^^^^^ Reverse the order of the operands `false == foo`.
RUBY
expect_correction(<<~RUBY)
foo == false
RUBY
end
end
end
context 'enforce yoda' do
let(:cop_config) { { 'EnforcedStyle' => 'require_for_all_comparison_operators' } }
it 'accepts method call on receiver on right' do
expect_no_offenses('2 == b.value')
end
it 'accepts safe navigation on right' do
expect_no_offenses('2 == b&.value')
end
it 'accepts instance variable on right' do
expect_no_offenses('2 == @value')
end
it 'accepts class variable on right' do
expect_no_offenses('2 == @@value')
end
it 'accepts variable on right after assignment' do
expect_no_offenses('b = 1; 2 == b')
end
it 'accepts global variable on right' do
expect_no_offenses('5 == $var')
end
it 'accepts string literal on left' do
expect_no_offenses('"bar" == foo')
end
it 'accepts accessor and variable on right in boolean expression' do
expect_no_offenses('"bar" > foo[0] || "bar" != baz')
end
it 'accepts assignment' do
expect_no_offenses('node = last_node.parent')
end
it 'accepts subtraction on right of comparison' do
expect_no_offenses('0 < (first_line - second_line)')
end
it 'accepts numbers on both sides' do
expect_no_offenses('5 == 6')
end
it 'accepts arrays of numbers on both sides' do
expect_no_offenses('[1, 2, 3] <=> [4, 5, 6]')
end
it 'accepts negation' do
expect_no_offenses('!true')
expect_no_offenses('not true')
end
it 'accepts number on left of <=>' do
expect_no_offenses('0 <=> val')
end
it 'accepts string literal on right of case equality check' do
expect_no_offenses('bar === "foo"')
end
it 'accepts equality check method is used without the first argument' do
expect_no_offenses('foo.==')
end
it 'registers an offense for string literal on right' do
expect_offense(<<~RUBY)
bar == "foo"
^^^^^^^^^^^^ Reverse the order of the operands `bar == "foo"`.
RUBY
expect_correction(<<~RUBY)
"foo" == bar
RUBY
end
it 'registers an offense for nil on right' do
expect_offense(<<~RUBY)
bar == nil
^^^^^^^^^^ Reverse the order of the operands `bar == nil`.
RUBY
expect_correction(<<~RUBY)
nil == bar
RUBY
end
it 'registers an offense for boolean literal on right' do
expect_offense(<<~RUBY)
active? == false
^^^^^^^^^^^^^^^^ Reverse the order of the operands `active? == false`.
RUBY
expect_correction(<<~RUBY)
false == active?
RUBY
end
it 'registers an offense for number on right' do
expect_offense(<<~RUBY)
@foo != 15
^^^^^^^^^^ Reverse the order of the operands `@foo != 15`.
RUBY
expect_correction(<<~RUBY)
15 != @foo
RUBY
end
it 'registers an offense for number on right of comparison' do
expect_offense(<<~RUBY)
bar > 42
^^^^^^^^ Reverse the order of the operands `bar > 42`.
RUBY
expect_correction(<<~RUBY)
42 < bar
RUBY
end
context 'within an if or ternary statement' do
it 'registers an offense number on right in if condition' do
expect_offense(<<~RUBY)
if my_var == 10; end
^^^^^^^^^^^^ Reverse the order of the operands `my_var == 10`.
RUBY
expect_correction(<<~RUBY)
if 10 == my_var; end
RUBY
end
it 'registers an offense number on right of comparison in if condition' do
expect_offense(<<~RUBY)
if bar > 2;end
^^^^^^^ Reverse the order of the operands `bar > 2`.
RUBY
expect_correction(<<~RUBY)
if 2 < bar;end
RUBY
end
it 'registers an offense for number on right in modifier if' do
expect_offense(<<~RUBY)
foo = 42 if bar < 42
^^^^^^^^ Reverse the order of the operands `bar < 42`.
RUBY
expect_correction(<<~RUBY)
foo = 42 if 42 > bar
RUBY
end
it 'registers an offense for number on right of >= in ternary condition' do
expect_offense(<<~RUBY)
foo >= 42 ? bar : baz
^^^^^^^^^ Reverse the order of the operands `foo >= 42`.
RUBY
expect_correction(<<~RUBY)
42 <= foo ? bar : baz
RUBY
end
it 'registers an offense for number on right of <= in ternary condition' do
expect_offense(<<~RUBY)
foo <= 42 ? bar : baz
^^^^^^^^^ Reverse the order of the operands `foo <= 42`.
RUBY
expect_correction(<<~RUBY)
42 >= foo ? bar : baz
RUBY
end
it 'registers an offense for nil on right in ternary condition' do
expect_offense(<<~RUBY)
foo != nil ? bar : baz
^^^^^^^^^^ Reverse the order of the operands `foo != nil`.
RUBY
expect_correction(<<~RUBY)
nil != foo ? bar : baz
RUBY
end
end
context 'with EnforcedStyle: require_for_equality_operators_only' do
let(:cop_config) { { 'EnforcedStyle' => 'require_for_equality_operators_only' } }
it 'accepts number on right of comparison' do
expect_no_offenses('bar > 42')
end
it 'accepts nil on right of comparison' do
expect_no_offenses('bar <= nil')
end
it 'accepts mixed order in comparisons' do
expect_no_offenses('a > 3 && 5 > a')
end
it 'registers an offense for negated equality check' do
expect_offense(<<~RUBY)
answer != 42
^^^^^^^^^^^^ Reverse the order of the operands `answer != 42`.
RUBY
expect_correction(<<~RUBY)
42 != answer
RUBY
end
it 'registers an offense for equality check' do
expect_offense(<<~RUBY)
foo == false
^^^^^^^^^^^^ Reverse the order of the operands `foo == false`.
RUBY
expect_correction(<<~RUBY)
false == 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/inline_comment_spec.rb | spec/rubocop/cop/style/inline_comment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::InlineComment, :config do
it 'registers an offense for a trailing inline comment' do
expect_offense(<<~RUBY)
two = 1 + 1 # A trailing inline comment
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid trailing inline comments.
RUBY
end
it 'does not register an offense for special rubocop inline comments' do
expect_no_offenses(<<~RUBY)
two = 1 + 1 # rubocop:disable Layout/ExtraSpacing
RUBY
end
it 'does not register an offense for a standalone comment' do
expect_no_offenses('# A standalone comment')
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/it_assignment_spec.rb | spec/rubocop/cop/style/it_assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ItAssignment, :config do
it 'registers an offense when assigning a local `it` variable' do
expect_offense(<<~RUBY)
it = 5
^^ `it` is the default block parameter; consider another name.
RUBY
end
it 'registers an offense when naming a method parameter `it`' do
expect_offense(<<~RUBY)
def foo(it)
^^ `it` is the default block parameter; consider another name.
end
RUBY
end
it 'registers an offense when naming a kwarg `it`' do
expect_offense(<<~RUBY)
def foo(it:)
^^ `it` is the default block parameter; consider another name.
end
RUBY
end
it 'registers an offense when naming a method parameter `it` with a default value' do
expect_offense(<<~RUBY)
def foo(it = 5)
^^ `it` is the default block parameter; consider another name.
end
RUBY
end
it 'registers an offense when naming a kwarg `it` with a default value' do
expect_offense(<<~RUBY)
def foo(it: 5)
^^ `it` is the default block parameter; consider another name.
end
RUBY
end
it 'registers an offense when naming a method parameter `*it`' do
expect_offense(<<~RUBY)
def foo(*it)
^^ `it` is the default block parameter; consider another name.
end
RUBY
end
it 'registers an offense when naming a kwarg splat `**it`' do
expect_offense(<<~RUBY)
def foo(**it)
^^ `it` is the default block parameter; consider another name.
end
RUBY
end
it 'registers an offense when naming a block argument `&it`' do
expect_offense(<<~RUBY)
def foo(&it)
^^ `it` is the default block parameter; consider another name.
end
RUBY
end
it 'registers an offense when assigning a local `it` variable inside a block' do
expect_offense(<<~RUBY)
foo { it = 5 }
^^ `it` is the default block parameter; consider another name.
RUBY
end
it 'registers an offense when assigning a local `it` variable inside a multiline block' do
expect_offense(<<~RUBY)
foo do
it = 5
^^ `it` is the default block parameter; consider another name.
bar(it)
end
RUBY
end
it 'registers an offense when assigning a local `it` variable inside a block with parameters' do
expect_offense(<<~RUBY)
foo { |x| it = x }
^^ `it` is the default block parameter; consider another name.
RUBY
end
it 'registers an offense when assigning a local `it` variable inside a numblock' do
expect_offense(<<~RUBY)
foo { it = _2 }
^^ `it` is the default block parameter; consider another name.
RUBY
end
it 'registers an offense inside a lambda' do
expect_offense(<<~RUBY)
-> { it = 5 }
^^ `it` is the default block parameter; consider another name.
RUBY
end
it 'does not register an offense when assigning `self.it`' do
expect_no_offenses(<<~RUBY)
self.it = 5
RUBY
end
it 'does not register an offense when assigning `self.it` inside a block' do
expect_no_offenses(<<~RUBY)
foo { self.it = 5 }
RUBY
end
it 'does not register an offense when assigning `@it`' do
expect_no_offenses(<<~RUBY)
@it = 5
RUBY
end
it 'does not register an offense when assigning `@it` inside a block' do
expect_no_offenses(<<~RUBY)
foo { @it = 5 }
RUBY
end
it 'does not register an offense when assigning `$it`' do
expect_no_offenses(<<~RUBY)
$it = 5
RUBY
end
it 'does not register an offense when assigning `$it` inside a block' do
expect_no_offenses(<<~RUBY)
foo { $it = 5 }
RUBY
end
it 'does not register an offense when assigning a constant `IT`' do
expect_no_offenses(<<~RUBY)
IT = 5
RUBY
end
it 'does not register an offense when naming a method `it`' do
expect_no_offenses(<<~RUBY)
def it
end
RUBY
end
context 'Ruby < 3.4', :ruby33 do
it 'does not register an offense when calling `it` in a block' do
expect_no_offenses(<<~RUBY)
foo { puts it }
RUBY
end
end
context 'Ruby >= 3.4', :ruby34 do
it 'does not register an offense when calling `it` in a block' do
expect_no_offenses(<<~RUBY)
foo { 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/yaml_file_read_spec.rb | spec/rubocop/cop/style/yaml_file_read_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::YAMLFileRead, :config do
context 'when Ruby >= 3.0', :ruby30 do
it 'registers an offense when using `YAML.load` with `File.read` argument' do
expect_offense(<<~RUBY)
YAML.load(File.read(path))
^^^^^^^^^^^^^^^^^^^^^ Use `load_file(path)` instead.
RUBY
expect_correction(<<~RUBY)
YAML.load_file(path)
RUBY
end
it 'registers an offense when using `YAML.safe_load` with `File.read` argument' do
expect_offense(<<~RUBY)
YAML.safe_load(File.read(path))
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `safe_load_file(path)` instead.
RUBY
expect_correction(<<~RUBY)
YAML.safe_load_file(path)
RUBY
end
it 'registers an offense when using `YAML.safe_load` with `File.read` and some arguments' do
expect_offense(<<~RUBY)
YAML.safe_load(File.read(path), permitted_classes: [Regexp, Symbol], aliases: true)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `safe_load_file(path, permitted_classes: [Regexp, Symbol], aliases: true)` instead.
RUBY
expect_correction(<<~RUBY)
YAML.safe_load_file(path, permitted_classes: [Regexp, Symbol], aliases: true)
RUBY
end
it 'registers an offense when using `YAML.parse` with `File.read` argument' do
expect_offense(<<~RUBY)
YAML.parse(File.read(path))
^^^^^^^^^^^^^^^^^^^^^^ Use `parse_file(path)` instead.
RUBY
expect_correction(<<~RUBY)
YAML.parse_file(path)
RUBY
end
it 'registers an offense when using `::YAML.load` with `::File.read` argument' do
expect_offense(<<~RUBY)
::YAML.load(::File.read(path))
^^^^^^^^^^^^^^^^^^^^^^^ Use `load_file(path)` instead.
RUBY
end
it "registers an offense when using `YAML.load` with `File.read(Rails.root.join('foo', 'bar', 'baz'))` argument" do
expect_offense(<<~RUBY)
YAML.load(File.read(Rails.root.join('foo', 'bar', 'baz')))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `load_file(Rails.root.join('foo', 'bar', 'baz'))` instead.
RUBY
expect_correction(<<~RUBY)
YAML.load_file(Rails.root.join('foo', 'bar', 'baz'))
RUBY
end
it 'does not register an offense when using `YAML.load` with variable argument' do
expect_no_offenses(<<~RUBY)
YAML.load(yaml)
RUBY
end
it 'does not register an offense when using `YAML.load_file`' do
expect_no_offenses(<<~RUBY)
YAML.load_file(File.read(path))
RUBY
end
end
context 'when Ruby <= 2.7', :ruby27, unsupported_on: :prism do
it 'registers an offense when using `YAML.load` with `File.read` argument' do
expect_offense(<<~RUBY)
YAML.load(File.read(path))
^^^^^^^^^^^^^^^^^^^^^ Use `load_file(path)` instead.
RUBY
expect_correction(<<~RUBY)
YAML.load_file(path)
RUBY
end
it 'does not register an offense when using `YAML.safe_load` with `File.read` argument' do
expect_no_offenses(<<~RUBY)
YAML.safe_load(File.read(path))
RUBY
end
it 'registers an offense when using `YAML.parse` with `File.read` argument' do
expect_offense(<<~RUBY)
YAML.parse(File.read(path))
^^^^^^^^^^^^^^^^^^^^^^ Use `parse_file(path)` instead.
RUBY
expect_correction(<<~RUBY)
YAML.parse_file(path)
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/min_max_comparison_spec.rb | spec/rubocop/cop/style/min_max_comparison_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MinMaxComparison, :config do
it 'registers and corrects an offense when using `a > b ? a : b`' do
expect_offense(<<~RUBY)
a > b ? a : b
^^^^^^^^^^^^^ Use `[a, b].max` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].max
RUBY
end
it 'registers and corrects an offense when using `a >= b ? a : b`' do
expect_offense(<<~RUBY)
a >= b ? a : b
^^^^^^^^^^^^^^ Use `[a, b].max` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].max
RUBY
end
it 'registers and corrects an offense when using `a < b ? b : a`' do
expect_offense(<<~RUBY)
a < b ? b : a
^^^^^^^^^^^^^ Use `[a, b].max` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].max
RUBY
end
it 'registers and corrects an offense when using `a <= b ? b : a`' do
expect_offense(<<~RUBY)
a <= b ? b : a
^^^^^^^^^^^^^^ Use `[a, b].max` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].max
RUBY
end
it 'registers and corrects an offense when using `a < b ? a : b`' do
expect_offense(<<~RUBY)
a < b ? a : b
^^^^^^^^^^^^^ Use `[a, b].min` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].min
RUBY
end
it 'registers and corrects an offense when using `a <= b ? a : b`' do
expect_offense(<<~RUBY)
a <= b ? a : b
^^^^^^^^^^^^^^ Use `[a, b].min` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].min
RUBY
end
it 'registers and corrects an offense when using `a > b ? b : a`' do
expect_offense(<<~RUBY)
a > b ? b : a
^^^^^^^^^^^^^ Use `[a, b].min` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].min
RUBY
end
it 'registers and corrects an offense when using `a >= b ? b : a`' do
expect_offense(<<~RUBY)
a >= b ? b : a
^^^^^^^^^^^^^^ Use `[a, b].min` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].min
RUBY
end
# Consider `Style/TernaryParentheses` cop with `EnforcedStyle: require_parentheses_when_complex`
it 'registers and corrects an offense when using `(a >= b) ? b : a`' do
expect_offense(<<~RUBY)
(a >= b) ? b : a
^^^^^^^^^^^^^^^^ Use `[a, b].min` instead.
RUBY
expect_correction(<<~RUBY)
[a, b].min
RUBY
end
it 'registers and corrects an offense when using `a > b a : b` with `if/else`' do
expect_offense(<<~RUBY)
if a > b
^^^^^^^^ Use `[a, b].max` instead.
a
else
b
end
RUBY
expect_correction(<<~RUBY)
[a, b].max
RUBY
end
it 'registers and corrects an offense when using `a < b a : b` with `if/else`' do
expect_offense(<<~RUBY)
if a < b
^^^^^^^^ Use `[a, b].min` instead.
a
else
b
end
RUBY
expect_correction(<<~RUBY)
[a, b].min
RUBY
end
it 'registers and corrects an offense when using `a < b a : b` with `elsif/else`' do
expect_offense(<<~RUBY)
if x
elsif a < b
^^^^^^^^^^^ Use `[a, b].min` instead.
a
else
b
end
RUBY
expect_correction(<<~RUBY)
if x
else
[a, b].min
end
RUBY
end
it 'does not register an offense when using `a > b ? c : d`' do
expect_no_offenses(<<~RUBY)
a > b ? c : d
RUBY
end
it 'does not register an offense when using `condition ? a : b`' do
expect_no_offenses(<<~RUBY)
condition ? a : b
RUBY
end
it 'does not register an offense when using `elsif`' do
expect_no_offenses(<<~RUBY)
if a
elsif foo(b)
b
end
RUBY
end
it 'does not register an offense when using `[a, b].max`' do
expect_no_offenses(<<~RUBY)
[a, b].max
RUBY
end
it 'does not register an offense when using `[a, b].min`' do
expect_no_offenses(<<~RUBY)
[a, b].min
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/safe_navigation_spec.rb | spec/rubocop/cop/style/safe_navigation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SafeNavigation, :config do
let(:cop_config) { { 'ConvertCodeThatCanStartToReturnNil' => false } }
let(:target_ruby_version) { 2.3 }
it 'allows calls to methods not safeguarded by respond_to' do
expect_no_offenses('foo.bar')
end
it 'allows calls using safe navigation' do
expect_no_offenses('foo&.bar')
end
it 'allows calls on nil' do
expect_no_offenses('nil&.bar')
end
it 'allows non-object checks' do
expect_no_offenses('x.foo? && x.bar?')
end
it 'allows non-object checks with safe navigation' do
expect_no_offenses('x&.foo? && x&.bar?')
end
it 'allows an object check before hash access' do
expect_no_offenses('foo && foo[:bar]')
end
it 'allows hash key access and then a different hash key access' do
expect_no_offenses('return if foo[:bar] && foo[:baz].blank?')
end
it 'allows an object check before a negated predicate' do
expect_no_offenses('foo && !foo.bar?')
end
it 'allows an object check before a nil check on a short chain' do
expect_no_offenses('user && user.thing.nil?')
end
it 'allows an object check before a method chain longer than 2 methods' do
expect_no_offenses('user && user.one.two.three')
end
it 'allows an object check before a long chain with a block' do
expect_no_offenses('user && user.thing.plus.another { |a| a}.other_thing')
end
it 'allows an object check before a nil check on a long chain' do
expect_no_offenses('user && user.thing.plus.some.other_thing.nil?')
end
it 'allows an object check before a blank check' do
# The `nil` object doesn't respond to `blank?` in normal Ruby (it's added
# by Rails), but it's included in the AllowedMethods parameter in default
# configuration for this cop.
expect_no_offenses('user && user.thing.blank?')
end
it 'allows an object check before a negated predicate method chain' do
expect_no_offenses('foo && !foo.bar.baz?')
end
it 'allows method call that is used in a comparison safe guarded by an object check' do
expect_no_offenses('foo.bar > 2 if foo')
end
it 'allows method call that is used in a regex comparison safe guarded by an object check' do
expect_no_offenses('foo.bar =~ /baz/ if foo')
end
it 'allows method call that is used in a negated regex comparison ' \
'safe guarded by an object check' do
expect_no_offenses('foo.bar !~ /baz/ if foo')
end
it 'allows method call that is used in a spaceship comparison safe guarded by an object check' do
expect_no_offenses('foo.bar <=> baz if foo')
end
it 'allows an object check before a method call that is used in a comparison' do
expect_no_offenses('foo && foo.bar > 2')
end
it 'allows an object check before a method call that is used in a regex comparison' do
expect_no_offenses('foo && foo.bar =~ /baz/')
end
it 'allows an object check before a method call that is used in a negated regex comparison' do
expect_no_offenses('foo && foo.bar !~ /baz/')
end
it 'allows an object check before a method call that is used with `empty?`' do
expect_no_offenses('foo && foo.empty?')
end
it 'allows an object check before a method call that is used in a spaceship comparison' do
expect_no_offenses('foo && foo.bar <=> baz')
end
it 'allows an object check before a method chain that is used in a comparison' do
expect_no_offenses('foo && foo.bar.baz > 2')
end
it 'allows a method chain that is used in a comparison safe guarded by an object check' do
expect_no_offenses('foo.bar.baz > 2 if foo')
end
it 'allows a method call safeguarded with a negative check for the object when using `unless`' do
expect_no_offenses('obj.do_something unless obj')
end
it 'allows a method call safeguarded with a negative check for the object when using `if`' do
expect_no_offenses('obj.do_something if !obj')
end
it 'allows method calls that do not get called using . safe guarded by an object check' do
expect_no_offenses('foo + bar if foo')
end
it 'allows chained method calls during arithmetic operations safe guarded by an object check' do
expect_no_offenses('foo.baz + bar if foo')
end
it 'allows chained method calls during assignment safe guarded by an object check' do
expect_no_offenses('foo.baz = bar if foo')
end
it 'allows an object check before a negated method call with a safe navigation' do
expect_no_offenses('obj && !obj&.do_something')
end
it 'allows object checks in the condition of an elsif statement ' \
'and a method call on that object in the body' do
expect_no_offenses(<<~RUBY)
if foo
something
elsif bar
bar.baz
end
RUBY
end
it 'allows for empty if blocks with comments' do
expect_no_offenses(<<~RUBY)
if foo
# a random comment
# TODO: Implement this before
end
RUBY
end
it 'allows a method call as a parameter when the parameter is ' \
'safe guarded with an object check' do
expect_no_offenses('foo(bar.baz) if bar')
end
it 'allows a method call safeguarded when using `unless nil?`' do
expect_no_offenses(<<~RUBY)
foo unless nil?
RUBY
end
it 'allows a negated `and` clause that does not do an object check' do
expect_no_offenses(<<~RUBY)
foo? && !((x.bar? || y.baz?) && z?)
RUBY
end
it 'allows an `and` with a `block` that contains an `and`' do
expect_no_offenses(<<~RUBY)
x? && y? do |b|
b.foo? && b.bar?
end
RUBY
end
it 'allows for nested `begin`s on the LHS' do
expect_no_offenses(<<~RUBY)
(x? + (y? && z?)) && !w?
RUBY
end
it 'allows mixed `||` and `&&` inside begin node' do
expect_no_offenses(<<~RUBY)
x? && (y? || z? && w?)
RUBY
end
# See https://github.com/rubocop/rubocop/issues/8781
it 'does not move comments that are inside an inner block' do
expect_offense(<<~RUBY)
# Comment 1
if x
^^^^ Use safe navigation (`&.`) instead of checking if an object exists before calling the method.
# Comment 2
x.each do
# Comment 3
# Comment 4
end
# Comment 5
end
RUBY
expect_correction(<<~RUBY)
# Comment 1
# Comment 2
# Comment 5
x&.each do
# Comment 3
# Comment 4
end
RUBY
end
shared_examples 'all variable types' do |variable|
context 'modifier if' do
shared_examples 'safe guarding logical break keywords' do |keyword|
it "allows a method call being passed to #{keyword} safe guarded by an object check" do
expect_no_offenses(<<~RUBY)
something.each do
#{keyword} #{variable}.bar if #{variable}
end
RUBY
end
end
it_behaves_like 'safe guarding logical break keywords', 'break'
it_behaves_like 'safe guarding logical break keywords', 'fail'
it_behaves_like 'safe guarding logical break keywords', 'next'
it_behaves_like 'safe guarding logical break keywords', 'raise'
it_behaves_like 'safe guarding logical break keywords', 'return'
it_behaves_like 'safe guarding logical break keywords', 'throw'
it_behaves_like 'safe guarding logical break keywords', 'yield'
it 'registers an offense for a method call that nil responds to ' \
'safe guarded by an object check' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.to_i if %{variable}
^{variable}^^^^^^^^^^{variable} Use safe navigation (`&.`) instead of checking if an object exists before calling the method.
RUBY
expect_correction(<<~RUBY)
#{variable}&.to_i
RUBY
end
it 'registers an offense when safe guard check and safe navigation method call are connected with `&&` condition' do
expect_offense(<<~RUBY, variable: variable)
%{variable} && %{variable}&.do_something
^{variable}^^^^^{variable}^^^^^^^^^^^^^^ Use safe navigation (`&.`) instead of checking if an object exists before calling the method.
RUBY
expect_correction(<<~RUBY)
#{variable}&.do_something
RUBY
end
it 'registers an offense for a method call on an accessor ' \
'safeguarded by a check for the accessed variable' do
expect_offense(<<~RUBY, variable: variable)
%{variable}[1].bar if %{variable}[1]
^{variable}^^^^^^^^^^^^{variable}^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}[1]&.bar
RUBY
end
it 'registers an offense for a method call safeguarded with a check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar if %{variable}
^{variable}^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a method call with params safeguarded ' \
'with a check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) if %{variable}
^{variable}^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a method call with a block safeguarded ' \
'with a check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar { |e| e.qux } if %{variable}
^{variable}^^^^^^^^^^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a method call with params and a block ' \
'safeguarded with a check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) { |e| e.qux } if %{variable}
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a chained method call safeguarded with a check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.one.two(baz) { |e| e.qux } if %{variable}
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.one&.two(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a method call safeguarded with a ' \
'negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar unless !%{variable}
^{variable}^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a method call with params safeguarded ' \
'with a negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) unless !%{variable}
^{variable}^^^^^^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a method call with a block safeguarded ' \
'with a negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar { |e| e.qux } unless !%{variable}
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a method call with params and a block ' \
'safeguarded with a negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) { |e| e.qux } unless !%{variable}
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a method call safeguarded with a nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar unless %{variable}.nil?
^{variable}^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a method call with params safeguarded ' \
'with a nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) unless %{variable}.nil?
^{variable}^^^^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a method call with a block safeguarded ' \
'with a nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar { |e| e.qux } unless %{variable}.nil?
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a method call with params and a block ' \
'safeguarded with a nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) { |e| e.qux } unless %{variable}.nil?
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a chained method call safeguarded ' \
'with an unless nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.one.two(baz) { |e| e.qux } unless %{variable}.nil?
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.one&.two(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a method call safeguarded with a ' \
'negative nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar if !%{variable}.nil?
^{variable}^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a method call with params safeguarded ' \
'with a negative nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) if !%{variable}.nil?
^{variable}^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a method call with a block safeguarded ' \
'with a negative nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar { |e| e.qux } if !%{variable}.nil?
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a method call with params and a block ' \
'safeguarded with a negative nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.bar(baz) { |e| e.qux } if !%{variable}.nil?
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a chained method call safeguarded ' \
'with a negative nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.one.two(baz) { |e| e.qux } if !%{variable}.nil?
^{variable}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.one&.two(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for an object check followed by a method call ' \
'with a comment at EOL' do
expect_offense(<<~RUBY, variable: variable)
foo if %{variable} && %{variable}.bar # comment
^{variable}^^^^^{variable}^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
foo if #{variable}&.bar # comment
RUBY
end
context 'method chaining' do
context 'MaxChainLength: 1' do
let(:cop_config) { { 'MaxChainLength' => 1 } }
it 'registers an offense for an object check followed by 1 chained method calls' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.one if %{variable}
^{variable}^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.one
RUBY
end
it 'allows an object check followed by 2 chained method calls' do
expect_no_offenses(<<~RUBY)
%{variable}.one.two if %{variable}
RUBY
end
end
end
end
context 'if expression' do
it 'registers an offense for a single method call inside of a check for the object' do
expect_offense(<<~RUBY, variable: variable)
if %{variable}
^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a single method call with params ' \
'inside of a check for the object' do
expect_offense(<<~RUBY, variable: variable)
if %{variable}
^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz)
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a single method call with a block ' \
'inside of a check for the object' do
expect_offense(<<~RUBY, variable: variable)
if %{variable}
^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a single method call with params ' \
'and a block inside of a check for the object' do
expect_offense(<<~RUBY, variable: variable)
if %{variable}
^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz) { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a single method call inside of a non-nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
if !%{variable}.nil?
^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a single method call with params ' \
'inside of a non-nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
if !%{variable}.nil?
^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz)
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a single method call with a block ' \
'inside of a non-nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
if !%{variable}.nil?
^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a single method call with params ' \
'and a block inside of a non-nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
if !%{variable}.nil?
^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz) { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a single method call inside of an ' \
'unless nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless %{variable}.nil?
^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a single method call with params ' \
'inside of an unless nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless %{variable}.nil?
^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz)
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a single method call with a block ' \
'inside of an unless nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless %{variable}.nil?
^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a single method call with params ' \
'and a block inside of an unless nil check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless %{variable}.nil?
^^^^^^^^{variable}^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz) { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'registers an offense for a single method call inside of an ' \
'unless negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless !%{variable}
^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
RUBY
end
it 'registers an offense for a single method call with params ' \
'inside of an unless negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless !%{variable}
^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz)
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz)
RUBY
end
it 'registers an offense for a single method call with a block ' \
'inside of an unless negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless !%{variable}
^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar { |e| e.qux }
RUBY
end
it 'registers an offense for a single method call with params ' \
'and a block inside of an unless negative check for the object' do
expect_offense(<<~RUBY, variable: variable)
unless !%{variable}
^^^^^^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.bar(baz) { |e| e.qux }
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar(baz) { |e| e.qux }
RUBY
end
it 'does not lose comments within if expression' do
expect_offense(<<~RUBY, variable: variable)
if %{variable} # hello
^^^^{variable}^^^^^^^^ Use safe navigation (`&.`) instead [...]
# this is a comment
# another comment
%{variable}.bar
end # bye!
RUBY
expect_correction(<<~RUBY)
# hello
# this is a comment
# another comment
#{variable}&.bar # bye!
RUBY
end
it 'only moves comments that fall within the expression' do
expect_offense(<<~RUBY, variable: variable)
# comment one
def foobar
if %{variable}
^^^^{variable} Use safe navigation (`&.`) instead [...]
# comment 2
%{variable}.bar
end
end
RUBY
expect_correction(<<~RUBY)
# comment one
def foobar
# comment 2
#{variable}&.bar
end
RUBY
end
it 'allows a single method call inside of a check for the object with an else' do
expect_no_offenses(<<~RUBY)
if #{variable}
#{variable}.bar
else
something
end
RUBY
end
context 'ternary expression' do
it 'allows non-convertible ternary expression' do
expect_no_offenses(<<~RUBY)
!#{variable}.nil? ? #{variable}.bar : something
RUBY
end
it 'allows ternary expression with index access call without dot' do
expect_no_offenses(<<~RUBY)
#{variable} ? #{variable}[index] : nil
RUBY
end
it 'allows ternary expression with index access call with method chain' do
expect_no_offenses(<<~RUBY)
#{variable} ? #{variable}[index].do_something : nil
RUBY
end
it 'allows ternary expression with indexed assignment call without dot' do
expect_no_offenses(<<~RUBY)
#{variable} ? #{variable}[index] = 1 : nil
RUBY
end
it 'allows ternary expression with index access call chain without dot' do
expect_no_offenses(<<~RUBY)
#{variable}.nil? ? nil : #{variable}.foo[index]
RUBY
end
it 'allows ternary expression with double colon method call' do
expect_no_offenses(<<~RUBY)
#{variable} ? #{variable}::foo : nil
RUBY
end
it 'allows ternary expression with operator method call without dot' do
expect_no_offenses(<<~RUBY)
#{variable}.nil? ? nil : #{variable} * 42
RUBY
end
it 'allows ternary expression with operator method call chain without dot' do
expect_no_offenses(<<~RUBY)
%{variable}.nil? ? nil : %{variable}.foo * 42
RUBY
end
it 'registers an offense for ternary expressions in a method argument' do
expect_offense(<<~RUBY, variable: variable)
puts(%{variable} ? %{variable}.bar : nil)
^{variable}^^^^{variable}^^^^^^^^^^ Use safe navigation (`&.`) instead [...]
results << (%{variable} ? %{variable}.bar : nil)
^{variable}^^^^{variable}^^^^^^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
puts(#{variable}&.bar)
results << (#{variable}&.bar)
RUBY
end
it 'registers an offense for ternary expression with index access call with dot' do
expect_offense(<<~RUBY, variable: variable)
#{variable} ? #{variable}&.[](index) : nil
^{variable}^^^^{variable}^^^^^^^^^^^^^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.[](index)
RUBY
end
it 'registers an offense for ternary expression with indexed assignment with dot' do
expect_offense(<<~RUBY, variable: variable)
#{variable} ? #{variable}&.[]=(index) : nil
^{variable}^^^^{variable}^^^^^^^^^^^^^^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.[]=(index)
RUBY
end
it 'registers an offense for ternary expression with operator method call with dot' do
expect_offense(<<~RUBY, variable: variable)
%{variable}.nil? ? nil : %{variable}.*(42)
^{variable}^^^^^^^^^^^^^^^{variable}^^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.*(42)
RUBY
end
it 'registers an offense for ternary expressions in a collection assignment' do
expect_offense(<<~RUBY, variable: variable)
results[0] = %{variable} ? %{variable}.bar : nil
^{variable}^^^^{variable}^^^^^^^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
results[0] = #{variable}&.bar
RUBY
end
it 'registers an offense for convertible ternary expressions' do
expect_offense(<<~RUBY, variable: variable)
%{variable} ? %{variable}.bar : nil
^{variable}^^^^{variable}^^^^^^^^^^ Use safe navigation (`&.`) instead [...]
%{variable}.nil? ? nil : %{variable}.bar
^{variable}^^^^^^^^^^^^^^^{variable}^^^^ Use safe navigation (`&.`) instead [...]
!%{variable}.nil? ? %{variable}.bar : nil
^^{variable}^^^^^^^^^^{variable}^^^^^^^^^ Use safe navigation (`&.`) instead [...]
!%{variable} ? nil : %{variable}.bar
^^{variable}^^^^^^^^^^{variable}^^^^ Use safe navigation (`&.`) instead [...]
RUBY
expect_correction(<<~RUBY)
#{variable}&.bar
#{variable}&.bar
#{variable}&.bar
#{variable}&.bar
RUBY
end
end
context 'method chaining' do
context 'MaxChainLength: 1' do
let(:cop_config) { { 'MaxChainLength' => 1 } }
it 'registers an offense for an object check followed by 1 chained method calls' do
expect_offense(<<~RUBY, variable: variable)
if %{variable}
^^^^{variable} Use safe navigation (`&.`) instead [...]
%{variable}.one
end
RUBY
expect_correction(<<~RUBY)
#{variable}&.one
RUBY
end
it 'allows an object check followed by 2 chained method calls' do
expect_no_offenses(<<~RUBY)
if #{variable}
#{variable}.one.two
end
RUBY
end
end
end
end
context 'object check before method call' do
context 'ConvertCodeThatCanStartToReturnNil true' do
let(:cop_config) { { 'ConvertCodeThatCanStartToReturnNil' => true } }
it 'registers an offense for a non-nil object check followed by a method call' do
expect_offense(<<~RUBY, variable: variable)
!%{variable}.nil? && %{variable}.bar
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/method_def_parentheses_spec.rb | spec/rubocop/cop/style/method_def_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MethodDefParentheses, :config do
shared_examples 'no parentheses' do
# common to require_no_parentheses and
# require_no_parentheses_except_multiline
it 'reports an offense for def with parameters with parens' do
expect_offense(<<~RUBY)
def func(a, b)
^^^^^^ Use def without parentheses.
end
RUBY
expect_correction(<<~RUBY)
def func a, b
end
RUBY
end
it 'accepts a def with parameters but no parens' do
expect_no_offenses(<<~RUBY)
def func a, b
end
RUBY
end
it 'reports an offense for opposite + correct' do
expect_offense(<<~RUBY)
def func(a, b)
^^^^^^ Use def without parentheses.
end
def func a, b
end
RUBY
expect_correction(<<~RUBY)
def func a, b
end
def func a, b
end
RUBY
end
it 'reports an offense for class def with parameters with parens' do
expect_offense(<<~RUBY)
def Test.func(a, b)
^^^^^^ Use def without parentheses.
end
RUBY
expect_correction(<<~RUBY)
def Test.func a, b
end
RUBY
end
it 'accepts a class def with parameters with parens' do
expect_no_offenses(<<~RUBY)
def Test.func a, b
end
RUBY
end
it 'reports an offense for def with no args and parens' do
expect_offense(<<~RUBY)
def func()
^^ Use def without parentheses.
end
RUBY
expect_correction(<<~RUBY)
def func#{trailing_whitespace}
end
RUBY
end
it 'accepts def with no args and no parens' do
expect_no_offenses(<<~RUBY)
def func
end
RUBY
end
it 'auto-removes the parens for defs' do
expect_offense(<<~RUBY)
def self.test(param); end
^^^^^^^ Use def without parentheses.
RUBY
expect_correction(<<~RUBY)
def self.test param; end
RUBY
end
it 'requires parens for forwarding', :ruby27 do
expect_no_offenses(<<~RUBY)
def foo(...)
bar(...)
end
RUBY
end
it 'requires parens for anonymous block forwarding', :ruby31 do
expect_no_offenses(<<~RUBY)
def foo(&)
bar(&)
end
RUBY
end
it 'requires parens for anonymous rest arguments forwarding', :ruby32 do
expect_no_offenses(<<~RUBY)
def foo(*)
bar(*)
end
RUBY
end
it 'requires parens for anonymous keyword rest arguments forwarding', :ruby32 do
expect_no_offenses(<<~RUBY)
def foo(**)
bar(**)
end
RUBY
end
end
shared_examples 'endless methods' do
context 'endless methods', :ruby30 do
it 'accepts parens without args' do
expect_no_offenses(<<~RUBY)
def foo() = x
RUBY
end
it 'accepts parens with args' do
expect_no_offenses(<<~RUBY)
def foo(x) = x
RUBY
end
it 'accepts parens for method calls inside an endless method' do
expect_no_offenses(<<~RUBY)
def foo(x) = bar(x)
RUBY
end
it 'accepts parens with `forward-arg`' do
expect_no_offenses(<<~RUBY)
def foo(...)= bar(...)
RUBY
end
end
end
context 'require_parentheses' do
let(:cop_config) { { 'EnforcedStyle' => 'require_parentheses' } }
it_behaves_like 'endless methods'
it 'reports an offense for def with parameters but no parens' do
expect_offense(<<~RUBY)
def func a, b
^^^^ Use def with parentheses when there are parameters.
end
RUBY
expect_correction(<<~RUBY)
def func(a, b)
end
RUBY
end
it 'reports an offense for correct + opposite' do
expect_offense(<<~RUBY)
def func(a, b)
end
def func a, b
^^^^ Use def with parentheses when there are parameters.
end
RUBY
expect_correction(<<~RUBY)
def func(a, b)
end
def func(a, b)
end
RUBY
end
it 'reports an offense for class def with parameters but no parens' do
expect_offense(<<~RUBY)
def Test.func a, b
^^^^ Use def with parentheses when there are parameters.
end
RUBY
expect_correction(<<~RUBY)
def Test.func(a, b)
end
RUBY
end
it 'accepts def with no args and no parens' do
expect_no_offenses(<<~RUBY)
def func
end
RUBY
end
it 'auto-adds required parens for a defs' do
expect_offense(<<~RUBY)
def self.test param; end
^^^^^ Use def with parentheses when there are parameters.
RUBY
expect_correction(<<~RUBY)
def self.test(param); end
RUBY
end
it 'auto-adds required parens for a defs after a passing method' do
expect_offense(<<~RUBY)
def self.fine; end
def self.test param; end
^^^^^ Use def with parentheses when there are parameters.
def self.test2 param; end
^^^^^ Use def with parentheses when there are parameters.
RUBY
expect_correction(<<~RUBY)
def self.fine; end
def self.test(param); end
def self.test2(param); end
RUBY
end
it 'auto-adds required parens to argument lists on multiple lines' do
expect_offense(<<~RUBY)
def test one,
^^^^ Use def with parentheses when there are parameters.
two
end
RUBY
expect_correction(<<~RUBY)
def test(one,
two)
end
RUBY
end
end
context 'require_no_parentheses' do
let(:cop_config) { { 'EnforcedStyle' => 'require_no_parentheses' } }
it_behaves_like 'no parentheses'
it_behaves_like 'endless methods'
end
context 'require_no_parentheses_except_multiline' do
let(:cop_config) { { 'EnforcedStyle' => 'require_no_parentheses_except_multiline' } }
it_behaves_like 'endless methods'
context 'when args are all on a single line' do
it_behaves_like 'no parentheses'
end
context 'when args span multiple lines' do
it 'auto-adds required parens to argument lists on multiple lines' do
expect_offense(<<~RUBY)
def test one,
^^^^ Use def with parentheses when there are parameters.
two
end
RUBY
expect_correction(<<~RUBY)
def test(one,
two)
end
RUBY
end
it 'reports an offense for correct + opposite' do
expect_offense(<<~RUBY)
def func(a,
b)
end
def func a,
^^ Use def with parentheses when there are parameters.
b
end
RUBY
expect_correction(<<~RUBY)
def func(a,
b)
end
def func(a,
b)
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/accessor_grouping_spec.rb | spec/rubocop/cop/style/accessor_grouping_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::AccessorGrouping, :config do
context 'when EnforcedStyle is grouped' do
let(:cop_config) { { 'EnforcedStyle' => 'grouped' } }
it 'registers an offense and corrects when using separated accessors' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar1
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :bar2
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_accessor :quux
attr_reader :bar3, :bar4
^^^^^^^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
other_macro :zoo
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :bar1, :bar2, :bar3, :bar4
attr_accessor :quux
other_macro :zoo
end
RUBY
end
it 'registers an offense and corrects when using separated accessors with different access modifiers' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar1
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :bar2
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
protected
attr_accessor :quux
private
attr_reader :baz1, :baz2
^^^^^^^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_writer :baz3
attr_reader :baz4
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
public
attr_reader :bar3
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
other_macro :zoo
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :bar1, :bar2, :bar3
protected
attr_accessor :quux
private
attr_reader :baz1, :baz2, :baz4
attr_writer :baz3
public
other_macro :zoo
end
RUBY
end
it 'registers an offense and corrects when using separated accessors within eigenclass' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar
class << self
attr_reader :baz1, :baz2
^^^^^^^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :baz3
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
private
attr_reader :quux1
^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :quux2
^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :bar
class << self
attr_reader :baz1, :baz2, :baz3
private
attr_reader :quux1, :quux2
end
end
RUBY
end
it 'does not register an offense when using grouped accessors' do
expect_no_offenses(<<~RUBY)
class Foo
attr_reader :bar, :baz
end
RUBY
end
it 'does not register offense for accessors with comments' do
expect_no_offenses(<<~RUBY)
class Foo
# @return [String] value of foo
attr_reader :one, :two
attr_reader :four
end
RUBY
end
it 'does not register an offense for accessors with other methods' do
expect_no_offenses(<<~RUBY)
class Foo
extend T::Sig
annotation_method :one
attr_reader :one
annotation_method :two
attr_reader :two
sig { returns(Integer) }
attr_reader :three
end
RUBY
end
it 'does not register an offense for grouped accessors below a typechecked accessor method' do
expect_no_offenses(<<~RUBY)
class Foo
extend T::Sig
sig { returns(Integer) }
attr_reader :one
attr_reader :two, :three
end
RUBY
end
it 'registers an offense for grouped accessors distinct from a typechecked accessor method' do
expect_offense(<<~RUBY)
class Foo
extend T::Sig
sig { returns(Integer) }
attr_reader :one
attr_reader :two, :three
^^^^^^^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :four
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
end
RUBY
expect_correction(<<~RUBY)
class Foo
extend T::Sig
sig { returns(Integer) }
attr_reader :one
attr_reader :two, :three, :four
end
RUBY
end
it 'registers an offense for accessors with method definitions' do
expect_offense(<<~RUBY)
class Foo
def foo
end
attr_reader :one
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
def bar
end
attr_reader :two
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
end
RUBY
expect_correction(<<~RUBY)
class Foo
def foo
end
attr_reader :one, :two
def bar
end
end
RUBY
end
it 'registers an offense and corrects if at least two separate accessors without comments' do
expect_offense(<<~RUBY)
class Foo
# @return [String] value of foo
attr_reader :one, :two
# [String] Some bar value return
attr_reader :three
attr_reader :four
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :five
^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
end
RUBY
expect_correction(<<~RUBY)
class Foo
# @return [String] value of foo
attr_reader :one, :two
# [String] Some bar value return
attr_reader :three
attr_reader :four, :five
end
RUBY
end
it 'registers an offense and correct if the same accessor is listed twice' do
expect_offense(<<~RUBY)
class Foo
attr_reader :one
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :two
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :one
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :one, :two
end
RUBY
end
it 'does not register an offense when the same accessor is given more than once in the same statement' do
expect_no_offenses(<<~RUBY)
class Foo
attr_reader :one, :one
end
RUBY
end
it 'does not register an offense for grouped accessors having RBS::Inline annotation' do
expect_no_offenses(<<~RUBY)
class Foo
attr_reader :one #: String
attr_reader :two, :three
end
RUBY
end
it 'registers an offense for grouped accessors having non-RBS::Inline annotation' do
expect_offense(<<~RUBY)
class Foo
attr_reader :one # comment #: String
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :two, :three
^^^^^^^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :one, :two, :three # comment #: String
end
RUBY
end
context 'when constant is used in accessor' do
it 'registers and corrects an offense considering ordering of constant' do
expect_offense(<<~RUBY)
class Foo
attr_reader :one
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
OTHER_ATTRS = %i[two three].freeze
attr_reader(*OTHER_ATTRS)
^^^^^^^^^^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
end
RUBY
expect_correction(<<~RUBY)
class Foo
OTHER_ATTRS = %i[two three].freeze
attr_reader :one, *OTHER_ATTRS
end
RUBY
end
it 'registers and corrects when there is no attr_reader after constant' do
expect_offense(<<~RUBY)
class Foo
attr_reader :one
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
attr_reader :bar
^^^^^^^^^^^^^^^^ Group together all `attr_reader` attributes.
OTHER_ATTRS = %i[two three].freeze
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :one, :bar
OTHER_ATTRS = %i[two three].freeze
end
RUBY
end
end
end
context 'when EnforcedStyle is separated' do
let(:cop_config) { { 'EnforcedStyle' => 'separated' } }
it 'registers an offense and corrects when using grouped accessors' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar, :baz
^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
attr_accessor :quux
other_macro :zoo, :woo
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :bar
attr_reader :baz
attr_accessor :quux
other_macro :zoo, :woo
end
RUBY
end
it 'registers an offense and corrects when using grouped accessors with different access modifiers' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar1, :bar2
^^^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
protected
attr_accessor :quux
private
attr_reader :baz1, :baz2
^^^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
attr_writer :baz3
attr_reader :baz4
public
attr_reader :bar3
other_macro :zoo
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :bar1
attr_reader :bar2
protected
attr_accessor :quux
private
attr_reader :baz1
attr_reader :baz2
attr_writer :baz3
attr_reader :baz4
public
attr_reader :bar3
other_macro :zoo
end
RUBY
end
it 'registers an offense and corrects when using grouped accessors within eigenclass' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar
class << self
attr_reader :baz1, :baz2
^^^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
attr_reader :baz3
private
attr_reader :quux1, :quux2
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :bar
class << self
attr_reader :baz1
attr_reader :baz2
attr_reader :baz3
private
attr_reader :quux1
attr_reader :quux2
end
end
RUBY
end
it 'does not register an offense when using separated accessors' do
expect_no_offenses(<<~RUBY)
class Foo
attr_reader :bar
attr_reader :baz
end
RUBY
end
it 'does not register an offense for grouped accessors with comments' do
expect_no_offenses(<<~RUBY)
class Foo
# Some comment
attr_reader :one, :two
end
RUBY
end
it 'does not register an offense if the same accessor is listed twice' do
expect_no_offenses(<<~RUBY)
class Foo
attr_reader :one
attr_reader :two
attr_reader :one
end
RUBY
end
it 'registers an offense and corrects when the same accessor is given more than once in the same statement' do
expect_offense(<<~RUBY)
class Foo
attr_reader :one, :two, :one
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :one
attr_reader :two
attr_reader :one
end
RUBY
end
it 'registers an offense and corrects when other method is followed by a space and grouped accessors' do
expect_offense(<<~RUBY)
class Foo
other_macro :zoo, :woo
attr_reader :foo, :bar
^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
end
RUBY
expect_correction(<<~RUBY)
class Foo
other_macro :zoo, :woo
attr_reader :foo
attr_reader :bar
end
RUBY
end
context 'when there are comments for attributes with parentheses' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
class Foo
attr_reader(
^^^^^^^^^^^^ Use one attribute per `attr_reader`.
# comment one
:one,
# comment two A
:two, # comment two B
:three # comment three
)
end
RUBY
expect_correction(<<~RUBY)
class Foo
# comment one
attr_reader :one
# comment two A
# comment two B
attr_reader :two
# comment three
attr_reader :three
end
RUBY
end
end
context 'when there are comments for attributes without parentheses' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
class Foo
attr_reader :a, # comment a
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use one attribute per `attr_reader`.
:b, # comment b
:c # comment c
end
RUBY
expect_correction(<<~RUBY)
class Foo
# comment a
attr_reader :a
# comment b
attr_reader :b
# comment c
attr_reader :c
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/single_line_methods_spec.rb | spec/rubocop/cop/style/single_line_methods_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SingleLineMethods, :config do
let(:config) do
RuboCop::Config.new('AllCops' => all_cops_config,
'Style/SingleLineMethods' => cop_config,
'Layout/IndentationWidth' => { 'Width' => 2 },
'Style/EndlessMethod' => { 'Enabled' => false })
end
let(:cop_config) { { 'AllowIfMethodIsEmpty' => true } }
it 'registers an offense for a single-line method' do
expect_offense(<<~RUBY)
def some_method; body end
^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
def link_to(name, url); {:name => name}; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
def @table.columns; super; end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<~RUBY)
def some_method;#{trailing_whitespace}
body#{trailing_whitespace}
end
def link_to(name, url);#{trailing_whitespace}
{:name => name};#{trailing_whitespace}
end
def @table.columns;#{trailing_whitespace}
super;#{trailing_whitespace}
end
RUBY
end
it 'registers an offense for a single-line method and method body is enclosed in parentheses' do
expect_offense(<<~RUBY)
def foo() (do_something) end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<~RUBY)
def foo()#{trailing_whitespace}
(do_something)#{trailing_whitespace}
end
RUBY
end
context 'when AllowIfMethodIsEmpty is disabled' do
let(:cop_config) { { 'AllowIfMethodIsEmpty' => false } }
it 'registers an offense for an empty method' do
expect_offense(<<~RUBY)
def no_op; end
^^^^^^^^^^^^^^ Avoid single-line method definitions.
def self.resource_class=(klass); end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
def @table.columns; end
^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<~RUBY)
def no_op;#{trailing_whitespace}
end
def self.resource_class=(klass);#{trailing_whitespace}
end
def @table.columns;#{trailing_whitespace}
end
RUBY
end
end
context 'when AllowIfMethodIsEmpty is enabled' do
let(:cop_config) { { 'AllowIfMethodIsEmpty' => true } }
it 'accepts a single-line empty method' do
expect_no_offenses(<<~RUBY)
def no_op; end
def self.resource_class=(klass); end
def @table.columns; end
RUBY
end
end
it 'accepts a multi-line method' do
expect_no_offenses(<<~RUBY)
def some_method
body
end
RUBY
end
it 'does not crash on a method with a capitalized name' do
expect_no_offenses(<<~RUBY)
def NoSnakeCase
end
RUBY
end
it 'autocorrects def with semicolon after method name' do
expect_offense(<<-RUBY.strip_margin('|'))
| def some_method; body end # Cmnt
| ^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| # Cmnt
| def some_method;#{trailing_whitespace}
| body#{trailing_whitespace}
| end#{trailing_whitespace}
RUBY
end
it 'autocorrects defs with parentheses after method name' do
expect_offense(<<-RUBY.strip_margin('|'))
| def self.some_method() body end
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| def self.some_method()#{trailing_whitespace}
| body#{trailing_whitespace}
| end
RUBY
end
it 'autocorrects def with argument in parentheses' do
expect_offense(<<-RUBY.strip_margin('|'))
| def some_method(arg) body end
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| def some_method(arg)#{trailing_whitespace}
| body#{trailing_whitespace}
| end
RUBY
end
it 'autocorrects def with argument and no parentheses' do
expect_offense(<<-RUBY.strip_margin('|'))
| def some_method arg; body end
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| def some_method arg;#{trailing_whitespace}
| body#{trailing_whitespace}
| end
RUBY
end
it 'autocorrects def with semicolon before end' do
expect_offense(<<-RUBY.strip_margin('|'))
| def some_method; b1; b2; end
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid single-line method definitions.
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| def some_method;#{trailing_whitespace}
| b1;#{trailing_whitespace}
| b2;#{trailing_whitespace}
| end
RUBY
end
context 'endless methods', :ruby30 do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def some_method() = x
RUBY
end
end
context 'when `Style/EndlessMethod` is enabled', :ruby30 do
before { config['Style/EndlessMethod'] = { 'Enabled' => true }.merge(endless_method_config) }
shared_examples 'convert to endless method' do
it 'corrects to an endless method definition' do
expect_correction(<<~RUBY.strip, source: 'def some_method; body end')
def some_method() = body
RUBY
end
it 'corrects to an endless class method definition' do
expect_correction(<<~RUBY.strip, source: 'def self.some_method; body end')
def self.some_method() = body
RUBY
end
it 'corrects to an endless singleton method definition' do
expect_correction(<<~RUBY.strip, source: 'def foo.some_method; body end')
def foo.some_method() = body
RUBY
end
it 'retains comments' do
source = 'def some_method; body end # comment'
expect_correction(<<~RUBY.strip, source: source)
def some_method() = body # comment
RUBY
end
it 'handles arguments properly' do
expect_correction(<<~RUBY.strip, source: 'def some_method(a, b, c) body end')
def some_method(a, b, c) = body
RUBY
end
it 'corrects to an endless method definition when method body is a literal' do
expect_correction(<<~RUBY.strip, source: 'def some_method; 42 end')
def some_method() = 42
RUBY
end
it 'corrects to an endless method definition when single line method call with parentheses' do
expect_correction(<<~RUBY.strip, source: 'def index() head(:ok) end')
def index() = head(:ok)
RUBY
end
it 'corrects to an endless method definition when single line method call without parentheses' do
expect_correction(<<~RUBY.strip, source: 'def index() head :ok end')
def index() = head(:ok)
RUBY
end
it 'does not add parens if they are already present' do
expect_correction(<<~RUBY.strip, source: 'def some_method() body end')
def some_method() = body
RUBY
end
RuboCop::AST::Node::COMPARISON_OPERATORS.each do |op|
it "corrects to an endless class method definition when using #{op}" do
expect_correction(<<~RUBY.strip, source: "def #{op}(other) self #{op} other end")
def #{op}(other) = self #{op} other
RUBY
end
end
RuboCop::AST::MethodDispatchNode.const_get(:ARITHMETIC_OPERATORS).each do |op|
it "corrects to an endless class method definition when using #{op}" do
expect_correction(<<~RUBY.strip, source: "def foo() bar #{op} baz end")
def foo() = bar #{op} baz
RUBY
end
end
it 'registers an offense when a single-line method definition contains `if` modifier' do
expect_correction(<<~RUBY.strip, source: 'def foo() bar if baz end')
def foo()#{trailing_whitespace}
bar if baz#{trailing_whitespace}
end
RUBY
end
it 'registers an offense when a single-line method definition contains `unless` modifier' do
expect_correction(<<~RUBY.strip, source: 'def foo() bar unless baz end')
def foo()#{trailing_whitespace}
bar unless baz#{trailing_whitespace}
end
RUBY
end
it 'registers an offense when a single-line method definition contains `while` modifier' do
expect_correction(<<~RUBY.strip, source: 'def foo() bar while baz end')
def foo()#{trailing_whitespace}
bar while baz#{trailing_whitespace}
end
RUBY
end
it 'registers an offense when a single-line method definition contains `until` modifier' do
expect_correction(<<~RUBY.strip, source: 'def foo() bar until baz end')
def foo()#{trailing_whitespace}
bar until baz#{trailing_whitespace}
end
RUBY
end
it 'does not to an endless class method definition when using `return`' do
expect_correction(<<~RUBY.strip, source: 'def foo(argument) return bar(argument); end')
def foo(argument)#{trailing_whitespace}
return bar(argument);#{trailing_whitespace}
end
RUBY
end
it 'does not to an endless class method definition when using `break`', :ruby32, unsupported_on: :prism do
expect_correction(<<~RUBY.strip, source: 'def foo(argument) break bar(argument); end')
def foo(argument)#{trailing_whitespace}
break bar(argument);#{trailing_whitespace}
end
RUBY
end
it 'does not to an endless class method definition when using `next`', :ruby32, unsupported_on: :prism do
expect_correction(<<~RUBY.strip, source: 'def foo(argument) next bar(argument); end')
def foo(argument)#{trailing_whitespace}
next bar(argument);#{trailing_whitespace}
end
RUBY
end
# NOTE: Setter method cannot be defined in the endless method definition.
it 'corrects to multiline method definition when defining setter method' do
expect_correction(<<~RUBY.chop, source: 'def foo=(foo) @foo = foo end')
def foo=(foo)#{trailing_whitespace}
@foo = foo#{trailing_whitespace}
end
RUBY
end
it 'corrects to a normal method if the method body contains multiple statements' do
expect_correction(<<~RUBY.strip, source: 'def some_method; foo; bar end')
def some_method;#{trailing_whitespace}
foo;#{trailing_whitespace}
bar#{trailing_whitespace}
end
RUBY
end
context 'with AllowIfMethodIsEmpty: false' do
let(:cop_config) { { 'AllowIfMethodIsEmpty' => false } }
it 'does not turn a method with no body into an endless method' do
expect_correction(<<~RUBY.strip, source: 'def some_method; end')
def some_method;#{trailing_whitespace}
end
RUBY
end
end
context 'with AllowIfMethodIsEmpty: true' do
let(:cop_config) { { 'AllowIfMethodIsEmpty' => true } }
it 'does not correct' do
expect_no_offenses('def some_method; end')
end
end
end
context 'with `disallow` style' do
let(:endless_method_config) { { 'EnforcedStyle' => 'disallow' } }
it 'corrects to a normal method' do
expect_correction(<<~RUBY.strip, source: 'def some_method; body end')
def some_method;#{trailing_whitespace}
body#{trailing_whitespace}
end
RUBY
end
end
context 'with `allow_single_line` style' do
let(:endless_method_config) { { 'EnforcedStyle' => 'allow_single_line' } }
it_behaves_like 'convert to endless method'
end
context 'with `allow_always` style' do
let(:endless_method_config) { { 'EnforcedStyle' => 'allow_always' } }
it_behaves_like 'convert to endless method'
end
context 'with `require_single_line` style' do
let(:endless_method_config) { { 'EnforcedStyle' => 'require_single_line' } }
it_behaves_like 'convert to endless method'
end
context 'with `require_always` style' do
let(:endless_method_config) { { 'EnforcedStyle' => 'require_always' } }
it_behaves_like 'convert to endless method'
end
context 'prior to ruby 3.0', :ruby27, unsupported_on: :prism do
let(:endless_method_config) { { 'EnforcedStyle' => 'allow_always' } }
it 'corrects to a multiline method' do
expect_correction(<<~RUBY.strip, source: 'def some_method; body end')
def some_method;#{trailing_whitespace}
body#{trailing_whitespace}
end
RUBY
end
end
end
context 'when `Style/EndlessMethod` is disabled', :ruby30 do
before { config['Style/EndlessMethod'] = { 'Enabled' => false } }
it 'corrects to a normal method' do
expect_correction(<<~RUBY.strip, source: 'def some_method; body end')
def some_method;#{trailing_whitespace}
body#{trailing_whitespace}
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_defined_spec.rb | spec/rubocop/cop/style/combinable_defined_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CombinableDefined, :config do
it 'does not register an offense for a single `defined?`' do
expect_no_offenses(<<~RUBY)
defined?(Foo)
RUBY
end
%i[&& and].each do |operator|
context "joined by `#{operator}`" do
it 'does not register an offense for two separate `defined?`s' do
expect_no_offenses(<<~RUBY)
defined?(Foo) #{operator} defined?(Bar)
RUBY
end
it 'does not register an offense for two identical `defined?`s' do
# handled by Lint/BinaryOperatorWithIdenticalOperands
expect_no_offenses(<<~RUBY)
defined?(Foo) #{operator} defined?(Foo)
RUBY
end
it 'does not register an offense for the same constant with different `cbase`s' do
expect_no_offenses(<<~RUBY)
defined?(Foo) #{operator} defined?(::Foo)
RUBY
end
it 'registers an offense for two `defined?`s with same nesting' do
expect_offense(<<~RUBY, operator: operator)
defined?(Foo) #{operator} defined?(Foo::Bar)
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(Foo::Bar)
RUBY
end
it 'registers an offense for two `defined?`s with the same nesting in reverse order' do
expect_offense(<<~RUBY, operator: operator)
defined?(Foo::Bar) #{operator} defined?(Foo)
^^^^^^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(Foo::Bar)
RUBY
end
it 'registers an offense for two `defined?`s with the same nesting and `cbase`' do
expect_offense(<<~RUBY, operator: operator)
defined?(::Foo) #{operator} defined?(::Foo::Bar)
^^^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(::Foo::Bar)
RUBY
end
it 'registers an offense for two `defined?`s with the same deep nesting' do
expect_offense(<<~RUBY, operator: operator)
defined?(Foo::Bar) #{operator} defined?(Foo::Bar::Baz)
^^^^^^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(Foo::Bar::Baz)
RUBY
end
it 'registers an offense for three `defined?`s with same nesting' do
expect_offense(<<~RUBY, operator: operator)
defined?(Foo) #{operator} defined?(Foo::Bar) #{operator} defined?(Foo::Bar::Baz)
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(Foo::Bar::Baz)
RUBY
end
it 'registers an offense for three `defined?`s with the same module ancestor' do
expect_offense(<<~RUBY, operator: operator)
defined?(Foo) #{operator} defined?(Foo::Bar) #{operator} defined?(Foo::Baz)
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(Foo::Bar) #{operator} defined?(Foo::Baz)
RUBY
end
it 'does not register an offense for two `defined?`s with same namespace but different nesting' do
expect_no_offenses(<<~RUBY)
defined?(Foo::Bar) #{operator} defined?(Foo::Baz)
RUBY
end
it 'does not register an offense for two `defined?`s with negation' do
expect_no_offenses(<<~RUBY)
defined?(Foo) #{operator} !defined?(Foo::Bar)
RUBY
end
it 'does not register an offense for two `defined?` with different `cbase`s' do
expect_no_offenses(<<~RUBY)
defined?(::Foo) #{operator} defined?(Foo::Bar)
RUBY
end
it 'does not register an offense when skipping a nesting level' do
expect_no_offenses(<<~RUBY)
defined?(Foo) #{operator} defined?(Foo::Bar::Baz)
RUBY
end
it 'registers an offense when the namespace is not a constant' do
expect_offense(<<~RUBY, operator: operator)
defined?(foo) #{operator} defined?(foo::Bar)
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(foo::Bar)
RUBY
end
it 'registers an offense for method chain with dots' do
expect_offense(<<~RUBY, operator: operator)
defined?(foo) #{operator} defined?(foo.bar)
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(foo.bar)
RUBY
end
it 'registers an offense for method chain with `::`' do
expect_offense(<<~RUBY, operator: operator)
defined?(foo) #{operator} defined?(foo::bar)
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(foo::bar)
RUBY
end
it 'registers an offense for a method chain followed by constant nesting' do
expect_offense(<<~RUBY, operator: operator)
defined?(foo) #{operator} defined?(foo.bar) #{operator} defined?(foo.bar::BAZ)
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^^{operator}^^^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(foo.bar::BAZ)
RUBY
end
it 'does not register an offense when there is another term between `defined?`s' do
expect_no_offenses(<<~RUBY)
foo #{operator} defined?(Foo) #{operator} bar #{operator} defined?(Foo::Bar)
RUBY
end
end
end
context 'mixed operators' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
defined?(Foo) && defined?(Foo::Bar) and defined?(Foo::Bar::Baz)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
expect_correction(<<~RUBY)
defined?(Foo::Bar::Baz)
RUBY
end
it 'registers an offense and corrects when an operator is retained' do
expect_offense(<<~RUBY)
defined?(Foo) && defined?(Foo::Bar) and defined?(Foo::Baz)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine nested `defined?` calls.
RUBY
# The deleted operator is the one attached to the term being removed
# (in this case `defined?(Foo)`).
# `Style/AndOr` will subsequently update the operator if necessary.
expect_correction(<<~RUBY)
defined?(Foo::Bar) and defined?(Foo::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/array_coercion_spec.rb | spec/rubocop/cop/style/array_coercion_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ArrayCoercion, :config do
it 'registers an offense and corrects when splatting variable into array' do
expect_offense(<<~RUBY)
[*paths].each { |path| do_something(path) }
^^^^^^^^ Use `Array(paths)` instead of `[*paths]`.
RUBY
expect_correction(<<~RUBY)
Array(paths).each { |path| do_something(path) }
RUBY
end
it 'registers an offense and corrects when converting variable into array with check' do
expect_offense(<<~RUBY)
paths = [paths] unless paths.is_a?(Array)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Array(paths)` instead of explicit `Array` check.
RUBY
expect_correction(<<~RUBY)
paths = Array(paths)
RUBY
end
it 'does not register an offense when splat is not in array' do
expect_no_offenses(<<~RUBY)
first_path, rest = *paths
RUBY
end
it 'does not register an offense when splatting multiple variables into array' do
expect_no_offenses(<<~RUBY)
[*paths, '/root'].each { |path| do_something(path) }
RUBY
end
it 'does not register an offense when converting variable into other named array variable with check' do
expect_no_offenses(<<~RUBY)
other_paths = [paths] unless paths.is_a?(Array)
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_body_on_class_spec.rb | spec/rubocop/cop/style/trailing_body_on_class_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrailingBodyOnClass, :config do
let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 2 }) }
it 'registers an offense when body trails after class definition' do
expect_offense(<<~RUBY)
class Foo; body
^^^^ Place the first line of class body on its own line.
end
class Foo body
^^^^ Place the first line of class body on its own line.
end
class Bar; def bar; end
^^^^^^^^^^^^ Place the first line of class body on its own line.
end
class Bar def bar; end
^^^^^^^^^^^^ Place the first line of class body on its own line.
end
RUBY
expect_correction(<<~RUBY)
class Foo#{trailing_whitespace}
body
end
class Foo#{trailing_whitespace}
body
end
class Bar#{trailing_whitespace}
def bar; end
end
class Bar#{trailing_whitespace}
def bar; end
end
RUBY
end
it 'registers an offense when body trails after singleton class definition' do
expect_offense(<<~RUBY)
class << self; body
^^^^ Place the first line of class body on its own line.
end
class << self; def bar; end
^^^^^^^^^^^^ Place the first line of class body on its own line.
end
RUBY
expect_correction(<<~RUBY)
class << self#{trailing_whitespace}
body
end
class << self#{trailing_whitespace}
def bar; end
end
RUBY
end
it 'registers an offense with multi-line class' do
expect_offense(<<~RUBY)
class Foo; body
^^^^ Place the first line of class body on its own line.
def bar
qux
end
end
RUBY
expect_correction(<<~RUBY)
class Foo#{trailing_whitespace}
body
def bar
qux
end
end
RUBY
end
it 'accepts regular class' do
expect_no_offenses(<<~RUBY)
class Foo
def no_op; end
end
RUBY
end
it 'accepts class inheritance' do
expect_no_offenses(<<~RUBY)
class Foo < Bar
end
RUBY
end
it 'autocorrects with comment after body' do
expect_offense(<<~RUBY)
class BarQux; foo # comment
^^^ Place the first line of class body on its own line.
end
RUBY
expect_correction(<<~RUBY)
# comment
class BarQux#{trailing_whitespace}
foo#{trailing_whitespace}
end
RUBY
end
context 'when class is not on first line of processed_source' do
it 'autocorrect offense' do
expect_offense(<<-RUBY.strip_margin('|'))
|
| class Foo; body#{trailing_whitespace}
| ^^^^ Place the first line of class body on its own line.
| end
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
|
| class Foo#{trailing_whitespace}
| body#{trailing_whitespace}
| 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/infinite_loop_spec.rb | spec/rubocop/cop/style/infinite_loop_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::InfiniteLoop, :config do
let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 2 }) }
%w(1 2.0 [1] {}).each do |lit|
it "registers an offense for a while loop with #{lit} as condition" do
expect_offense(<<~RUBY)
while #{lit}
^^^^^ Use `Kernel#loop` for infinite loops.
top
end
RUBY
expect_correction(<<~RUBY)
loop do
top
end
RUBY
end
end
%w[false nil].each do |lit|
it "registers an offense for a until loop with #{lit} as condition" do
expect_offense(<<~RUBY)
until #{lit}
^^^^^ Use `Kernel#loop` for infinite loops.
top
end
RUBY
expect_correction(<<~RUBY)
loop do
top
end
RUBY
end
end
it 'accepts Kernel#loop' do
expect_no_offenses('loop { break if something }')
end
it 'accepts while true if loop {} would change semantics' do
expect_no_offenses(<<~RUBY)
def f1
a = nil # This `a` is local to `f1` and should not affect `f2`.
puts a
end
def f2
b = 17
while true
# `a` springs into existence here, while `b` already existed. Because
# of `a` we can't introduce a block.
a, b = 42, 42
break
end
puts a, b
end
RUBY
end
it 'accepts modifier while true if loop {} would change semantics' do
expect_no_offenses(<<~RUBY)
a = next_value or break while true
p a
RUBY
end
it 'registers an offense for modifier until false if loop {} would not change semantics' do
expect_offense(<<~RUBY)
a = nil
a = next_value or break until false
^^^^^ Use `Kernel#loop` for infinite loops.
p a
RUBY
expect_correction(<<~RUBY)
a = nil
loop { a = next_value or break }
p a
RUBY
end
it 'registers an offense for until false if loop {} would work because of ' \
'previous assignment in a while loop' do
expect_offense(<<~RUBY)
while true
a = 42
break
end
until false
^^^^^ Use `Kernel#loop` for infinite loops.
# The variable `a` already exists here, having been introduced in the
# above `while` loop. We can therefore safely change it too `Kernel#loop`.
a = 43
break
end
puts a
RUBY
expect_correction(<<~RUBY)
while true
a = 42
break
end
loop do
# The variable `a` already exists here, having been introduced in the
# above `while` loop. We can therefore safely change it too `Kernel#loop`.
a = 43
break
end
puts a
RUBY
end
it 'registers an offense for until false if loop {} would work because the ' \
'assigned variable is not used afterwards' do
expect_offense(<<~RUBY)
until false
^^^^^ Use `Kernel#loop` for infinite loops.
a = 43
break
end
RUBY
expect_correction(<<~RUBY)
loop do
a = 43
break
end
RUBY
end
it 'registers an offense for while true or until false if loop {} would ' \
'work because of an earlier assignment' do
expect_offense(<<~RUBY)
a = 0
while true
^^^^^ Use `Kernel#loop` for infinite loops.
a = 42 # `a` is in scope outside of the `while`
break
end
until false
^^^^^ Use `Kernel#loop` for infinite loops.
a = 43 # `a` is in scope outside of the `until`
break
end
puts a
RUBY
expect_correction(<<~RUBY)
a = 0
loop do
a = 42 # `a` is in scope outside of the `while`
break
end
loop do
a = 43 # `a` is in scope outside of the `until`
break
end
puts a
RUBY
end
it 'registers an offense for while true if loop {} would work because it ' \
'is an instance variable being assigned' do
expect_offense(<<~RUBY)
while true
^^^^^ Use `Kernel#loop` for infinite loops.
@a = 42
break
end
puts @a
RUBY
expect_correction(<<~RUBY)
loop do
@a = 42
break
end
puts @a
RUBY
end
shared_examples 'autocorrector' do |keyword, lit|
it "autocorrects single line modifier #{keyword}" do
expect_offense(<<~RUBY, keyword: keyword, lit: lit)
something += 1 %{keyword} %{lit} # comment
^{keyword} Use `Kernel#loop` for infinite loops.
RUBY
expect_correction(<<~RUBY)
loop { something += 1 } # comment
RUBY
end
context 'with non-default indentation width' do
let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 4 }) }
it "autocorrects multi-line modifier #{keyword} and indents correctly" do
expect_offense(<<~RUBY, keyword: keyword, lit: lit)
# comment
something 1, # comment 1
# comment 2
2 %{keyword} %{lit}
^{keyword} Use `Kernel#loop` for infinite loops.
RUBY
expect_correction(<<~RUBY)
# comment
loop do
something 1, # comment 1
# comment 2
2
end
RUBY
end
end
it "autocorrects begin-end-#{keyword} with one statement" do
expect_offense(<<~RUBY, keyword: keyword, lit: lit)
begin # comment 1
something += 1 # comment 2
end %{keyword} %{lit} # comment 3
^{keyword} Use `Kernel#loop` for infinite loops.
RUBY
expect_correction(<<~RUBY)
loop do # comment 1
something += 1 # comment 2
end # comment 3
RUBY
end
it "autocorrects begin-end-#{keyword} with two statements" do
expect_offense(<<~RUBY, keyword: keyword, lit: lit)
begin
something += 1
something_else += 1
end %{keyword} %{lit}
^{keyword} Use `Kernel#loop` for infinite loops.
RUBY
expect_correction(<<~RUBY)
loop do
something += 1
something_else += 1
end
RUBY
end
it "autocorrects single line modifier #{keyword} with and" do
expect_offense(<<~RUBY, keyword: keyword, lit: lit)
something and something_else %{keyword} %{lit}
^{keyword} Use `Kernel#loop` for infinite loops.
RUBY
expect_correction(<<~RUBY)
loop { something and something_else }
RUBY
end
it "autocorrects the usage of #{keyword} with do" do
expect_offense(<<~RUBY, keyword: keyword, lit: lit)
%{keyword} %{lit} do
^{keyword} Use `Kernel#loop` for infinite loops.
end
RUBY
expect_correction(<<~RUBY)
loop do
end
RUBY
end
it "autocorrects the usage of #{keyword} without do" do
expect_offense(<<~RUBY, keyword: keyword, lit: lit)
%{keyword} %{lit}
^{keyword} Use `Kernel#loop` for infinite loops.
end
RUBY
expect_correction(<<~RUBY)
loop do
end
RUBY
end
end
it_behaves_like 'autocorrector', 'while', 'true'
it_behaves_like 'autocorrector', 'until', 'false'
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/random_with_offset_spec.rb | spec/rubocop/cop/style/random_with_offset_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RandomWithOffset, :config do
it 'registers an offense when using rand(int) + offset' do
expect_offense(<<~RUBY)
rand(6) + 1
^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..6)
RUBY
end
it 'registers an offense when using offset + rand(int)' do
expect_offense(<<~RUBY)
1 + rand(6)
^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..6)
RUBY
end
it 'registers an offense when using rand(int).succ' do
expect_offense(<<~RUBY)
rand(6).succ
^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..6)
RUBY
end
it 'registers an offense when using rand(int) - offset' do
expect_offense(<<~RUBY)
rand(6) - 1
^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(-1..4)
RUBY
end
it 'registers an offense when using offset - rand(int)' do
expect_offense(<<~RUBY)
1 - rand(6)
^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(-4..1)
RUBY
end
it 'registers an offense when using rand(int).pred' do
expect_offense(<<~RUBY)
rand(6).pred
^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(-1..4)
RUBY
end
it 'registers an offense when using rand(int).next' do
expect_offense(<<~RUBY)
rand(6).next
^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..6)
RUBY
end
it 'registers an offense when using Kernel.rand' do
expect_offense(<<~RUBY)
Kernel.rand(6) + 1
^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
Kernel.rand(1..6)
RUBY
end
it 'registers an offense when using ::Kernel.rand' do
expect_offense(<<~RUBY)
::Kernel.rand(6) + 1
^^^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
::Kernel.rand(1..6)
RUBY
end
it 'registers an offense when using Random.rand' do
expect_offense(<<~RUBY)
Random.rand(6) + 1
^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
Random.rand(1..6)
RUBY
end
it 'registers an offense when using ::Random.rand' do
expect_offense(<<~RUBY)
::Random.rand(6) + 1
^^^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
::Random.rand(1..6)
RUBY
end
it 'registers an offense when using rand(irange) + offset' do
expect_offense(<<~RUBY)
rand(0..6) + 1
^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..7)
RUBY
end
it 'registers an offense when using rand(erange) + offset' do
expect_offense(<<~RUBY)
rand(0...6) + 1
^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..6)
RUBY
end
it 'registers an offense when using offset + Random.rand(int)' do
expect_offense(<<~RUBY)
1 + Random.rand(6)
^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
Random.rand(1..6)
RUBY
end
it 'registers an offense when using offset - ::Random.rand(int)' do
expect_offense(<<~RUBY)
1 - ::Random.rand(6)
^^^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
::Random.rand(-4..1)
RUBY
end
it 'registers an offense when using Random.rand(int).succ' do
expect_offense(<<~RUBY)
Random.rand(6).succ
^^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
Random.rand(1..6)
RUBY
end
it 'registers an offense when using ::Random.rand(int).pred' do
expect_offense(<<~RUBY)
::Random.rand(6).pred
^^^^^^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
::Random.rand(-1..4)
RUBY
end
it 'registers an offense when using rand(irange) - offset' do
expect_offense(<<~RUBY)
rand(0..6) - 1
^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(-1..5)
RUBY
end
it 'registers an offense when using rand(erange) - offset' do
expect_offense(<<~RUBY)
rand(0...6) - 1
^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(-1..4)
RUBY
end
it 'registers an offense when using offset - rand(irange)' do
expect_offense(<<~RUBY)
1 - rand(0..6)
^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(-5..1)
RUBY
end
it 'registers an offense when using offset - rand(erange)' do
expect_offense(<<~RUBY)
1 - rand(0...6)
^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(-4..1)
RUBY
end
it 'registers an offense when using rand(irange).succ' do
expect_offense(<<~RUBY)
rand(0..6).succ
^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..7)
RUBY
end
it 'registers an offense when using rand(erange).succ' do
expect_offense(<<~RUBY)
rand(0...6).succ
^^^^^^^^^^^^^^^^ Prefer ranges when generating random numbers instead of integers with offsets.
RUBY
expect_correction(<<~RUBY)
rand(1..6)
RUBY
end
it 'does not register an offense when using rand(irange) + offset with a non-integer range value' do
expect_no_offenses(<<~RUBY)
rand(0..limit) + 1
RUBY
end
it 'does not register an offense when using offset - rand(erange) with a non-integer range value' do
expect_no_offenses(<<~RUBY)
1 - rand(0...limit)
RUBY
end
it 'does not register an offense when using rand(irange).succ with a non-integer range value' do
expect_no_offenses(<<~RUBY)
rand(0..limit).succ
RUBY
end
it 'does not register an offense when using rand(erange).pred with a non-integer range value' do
expect_no_offenses(<<~RUBY)
rand(0...limit).pred
RUBY
end
it 'does not register an offense when using range with double dots' do
expect_no_offenses('rand(1..6)')
end
it 'does not register an offense when using range with triple dots' do
expect_no_offenses('rand(1...6)')
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_ternary_operator_spec.rb | spec/rubocop/cop/style/nested_ternary_operator_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NestedTernaryOperator, :config do
it 'registers an offense and corrects for a nested ternary operator expression' do
expect_offense(<<~RUBY)
a ? (b ? b1 : b2) : a2
^^^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
RUBY
expect_correction(<<~RUBY)
if a
b ? b1 : b2
else
a2
end
RUBY
end
it 'registers an offense and corrects for a nested ternary operator expression with block' do
expect_offense(<<~RUBY)
cond ? foo : bar(foo.a ? foo.b : foo) { |e, k| e.nil? ? nil : e[k] }
^^^^^^^^^^^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
^^^^^^^^^^^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
RUBY
expect_correction(<<~RUBY)
if cond
foo
else
bar(foo.a ? foo.b : foo) { |e, k| e.nil? ? nil : e[k] }
end
RUBY
end
it 'registers an offense and corrects for a nested ternary operator expression with no parentheses on the outside' do
expect_offense(<<~RUBY)
x ? y + (z ? 1 : 0) : nil
^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
RUBY
expect_correction(<<~RUBY)
if x
y + (z ? 1 : 0)
else
nil
end
RUBY
end
it 'registers an offense when a ternary operator has a nested ternary operator within an `if`' do
expect_offense(<<~RUBY)
a ? (
if b
c ? 1 : 2
^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
end
) : 3
RUBY
expect_correction(<<~RUBY)
if a
if b
c ? 1 : 2
end
else
3
end
RUBY
end
it 'accepts a non-nested ternary operator within an if' do
expect_no_offenses(<<~RUBY)
a = if x
cond ? b : c
else
d
end
RUBY
end
it 'can handle multiple nested ternaries' do
expect_offense(<<~RUBY)
a ? b : c ? d : e ? f : g
^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
^^^^^^^^^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
RUBY
expect_correction(<<~RUBY)
if a
b
else
if c
d
else
e ? f : g
end
end
RUBY
end
it 'registers an offense and corrects when ternary operators are nested and the inner condition is parenthesized' do
expect_offense(<<~RUBY)
foo ? (bar && baz) ? qux : quux : corge
^^^^^^^^^^^^^^^^^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
RUBY
expect_correction(<<~RUBY)
if foo
(bar && baz) ? qux : quux
else
corge
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/collection_querying_spec.rb | spec/rubocop/cop/style/collection_querying_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CollectionQuerying, :config do
it 'registers an offense for `.count.positive?`' do
expect_offense(<<~RUBY)
x.count.positive?
^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x.any?
RUBY
end
it 'registers an offense for multiline `.count.positive?`' do
expect_offense(<<~RUBY)
x
.count
^^^^^ Use `any?` instead.
.positive?
RUBY
expect_correction(<<~RUBY)
x
.any?
RUBY
end
it 'registers an offense for `.count(&:foo?).positive?`' do
expect_offense(<<~RUBY)
x.count(&:foo?).positive?
^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x.any?(&:foo?)
RUBY
end
it 'registers an offense for `.count { |item| item.foo? }.positive?`' do
expect_offense(<<~RUBY)
x.count { |item| item.foo? }.positive?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x.any? { |item| item.foo? }
RUBY
end
it 'registers an offense for `.count { _1.foo? }.positive?`' do
expect_offense(<<~RUBY)
x.count { _1.foo? }.positive?
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x.any? { _1.foo? }
RUBY
end
it 'registers an offense for `.count { it.foo? }.positive?`' do
expect_offense(<<~RUBY)
x.count { it.foo? }.positive?
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x.any? { it.foo? }
RUBY
end
it 'registers an offense for `&.count(&:foo?).positive?`' do
expect_offense(<<~RUBY)
x&.count(&:foo?).positive?
^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x&.any?(&:foo?)
RUBY
end
it 'registers an offense for `&.count.positive?`' do
expect_offense(<<~RUBY)
x&.count.positive?
^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x&.any?
RUBY
end
it 'registers an offense for `.count(&:foo?) > 0`' do
expect_offense(<<~RUBY)
x.count(&:foo?) > 0
^^^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x.any?(&:foo?)
RUBY
end
it 'registers an offense for `.count(&:foo?) != 0`' do
expect_offense(<<~RUBY)
x.count(&:foo?) != 0
^^^^^^^^^^^^^^^^^^ Use `any?` instead.
RUBY
expect_correction(<<~RUBY)
x.any?(&:foo?)
RUBY
end
it 'registers an offense for `.count(&:foo?).zero?`' do
expect_offense(<<~RUBY)
x.count(&:foo?).zero?
^^^^^^^^^^^^^^^^^^^ Use `none?` instead.
RUBY
expect_correction(<<~RUBY)
x.none?(&:foo?)
RUBY
end
it 'registers an offense for `.count(&:foo?) == 0`' do
expect_offense(<<~RUBY)
x.count(&:foo?) == 0
^^^^^^^^^^^^^^^^^^ Use `none?` instead.
RUBY
expect_correction(<<~RUBY)
x.none?(&:foo?)
RUBY
end
it 'registers an offense for `.count(&:foo?) == 1`' do
expect_offense(<<~RUBY)
x.count(&:foo?) == 1
^^^^^^^^^^^^^^^^^^ Use `one?` instead.
RUBY
expect_correction(<<~RUBY)
x.one?(&:foo?)
RUBY
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => true })
end
it 'registers an offense for `.count(&:foo?) > 1`' do
expect_offense(<<~RUBY)
x.count(&:foo?) > 1
^^^^^^^^^^^^^^^^^ Use `many?` instead.
RUBY
expect_correction(<<~RUBY)
x.many?(&:foo?)
RUBY
end
end
context 'when `AllCops/ActiveSupportExtensionsEnabled: false`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => false })
end
it 'does not register an offense for `.count(&:foo?) > 1`' do
expect_no_offenses(<<~RUBY)
x.count(&:foo?) > 1
RUBY
end
end
it 'does not register an offense for `.count(foo).positive?`' do
expect_no_offenses(<<~RUBY)
x.count(foo).positive?
RUBY
end
it 'does not register an offense for `.count(foo: bar).positive?`' do
expect_no_offenses(<<~RUBY)
x.count(foo: bar).positive?
RUBY
end
it 'does not register an offense for `.count&.positive?`' do
expect_no_offenses(<<~RUBY)
x.count&.positive?
RUBY
end
it 'does not register an offense for `.count`' do
expect_no_offenses(<<~RUBY)
x.count
RUBY
end
it 'does not register an offense when `count` does not have a receiver' do
expect_no_offenses(<<~RUBY)
count.positive?
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/line_end_concatenation_spec.rb | spec/rubocop/cop/style/line_end_concatenation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::LineEndConcatenation, :config do
it 'registers an offense for string concat at line end' do
expect_offense(<<~RUBY)
top = "test" +
^ Use `\\` instead of `+` to concatenate multiline strings.
"top"
RUBY
expect_correction(<<~RUBY)
top = "test" \\
"top"
RUBY
end
it 'registers an offense for string concat with << at line end' do
expect_offense(<<~RUBY)
top = "test" <<
^^ Use `\\` instead of `<<` to concatenate multiline strings.
"top"
RUBY
expect_correction(<<~RUBY)
top = "test" \\
"top"
RUBY
end
it 'registers an offense for string concat with << and \ at line ends' do
expect_offense(<<~RUBY)
top = "test " \\
"foo" <<
^^ Use `\\` instead of `<<` to concatenate multiline strings.
"bar"
RUBY
expect_correction(<<~RUBY)
top = "test " \\
"foo" \\
"bar"
RUBY
end
it 'registers an offense for dynamic string concat at line end' do
expect_offense(<<~'RUBY')
top = "test#{x}" +
^ Use `\` instead of `+` to concatenate multiline strings.
"top"
RUBY
expect_correction(<<~'RUBY')
top = "test#{x}" \
"top"
RUBY
end
it 'registers an offense for dynamic string concat with << at line end' do
expect_offense(<<~'RUBY')
top = "test#{x}" <<
^^ Use `\` instead of `<<` to concatenate multiline strings.
"top"
RUBY
expect_correction(<<~'RUBY')
top = "test#{x}" \
"top"
RUBY
end
it 'registers multiple offenses when there are chained << methods' do
expect_offense(<<~'RUBY')
top = "test#{x}" <<
^^ Use `\` instead of `<<` to concatenate multiline strings.
"top" <<
^^ Use `\` instead of `<<` to concatenate multiline strings.
"ubertop"
RUBY
expect_correction(<<~'RUBY')
top = "test#{x}" \
"top" \
"ubertop"
RUBY
end
it 'registers multiple offenses when there are chained concatenations' do
expect_offense(<<~'RUBY')
top = "test#{x}" +
^ Use `\` instead of `+` to concatenate multiline strings.
"top" +
^ Use `\` instead of `+` to concatenate multiline strings.
"foo"
RUBY
expect_correction(<<~'RUBY')
top = "test#{x}" \
"top" \
"foo"
RUBY
end
it 'registers multiple offenses when there are chained concatenations combined with << calls' do
expect_offense(<<~'RUBY')
top = "test#{x}" <<
^^ Use `\` instead of `<<` to concatenate multiline strings.
"top" +
^ Use `\` instead of `+` to concatenate multiline strings.
"foo" <<
^^ Use `\` instead of `<<` to concatenate multiline strings.
"bar"
RUBY
expect_correction(<<~'RUBY')
top = "test#{x}" \
"top" \
"foo" \
"bar"
RUBY
end
it 'accepts string concat on the same line' do
expect_no_offenses('top = "test" + "top"')
end
it 'accepts string concat with a return value of method on a string' do
expect_no_offenses(<<~RUBY)
content_and_three_spaces = "content" +
" " * 3
a_thing = 'a ' +
'gniht'.reverse
output = 'value: ' +
'%d' % value
'letter: ' +
'abcdefghij'[ix]
RUBY
end
it 'accepts string concat with a return value of method on an interpolated string' do
expect_no_offenses(<<~RUBY)
x3a = 'x' +
"\#{'a' + "\#{3}"}".reverse
RUBY
end
it 'accepts string concat at line end when followed by comment' do
expect_no_offenses(<<~RUBY)
top = "test" + # something
"top"
RUBY
end
it 'accepts string concat at line end when followed by a comment line' do
expect_no_offenses(<<~RUBY)
top = "test" +
# something
"top"
RUBY
end
it 'accepts string concat at line end when % literals are involved' do
expect_no_offenses(<<~RUBY)
top = %(test) +
"top"
RUBY
end
it 'accepts string concat at line end for special strings like __FILE__' do
expect_no_offenses(<<~RUBY)
top = __FILE__ +
"top"
RUBY
end
it 'registers offenses only for the appropriate lines in chained concats' do
# only the last concatenation is an offense
expect_offense(<<~'RUBY')
top = "test#{x}" + # comment
"foo" +
%(bar) +
"baz" +
^ Use `\` instead of `+` to concatenate multiline strings.
"qux"
RUBY
expect_correction(<<~'RUBY')
top = "test#{x}" + # comment
"foo" +
%(bar) +
"baz" \
"qux"
RUBY
end
# The "central autocorrection engine" can't handle intermediate states where
# the code has syntax errors, so it's important to fix the trailing
# whitespace in this cop.
it 'autocorrects a + with trailing whitespace to \\' do
expect_offense(<<~RUBY)
top = "test" +#{trailing_whitespace}
^ Use `\\` instead of `+` to concatenate multiline strings.
"top"
RUBY
expect_correction(<<~RUBY)
top = "test" \\
"top"
RUBY
end
it 'autocorrects a + with \\ to just \\' do
expect_offense(<<~RUBY)
top = "test" + \\
^ Use `\\` instead of `+` to concatenate multiline strings.
"top"
RUBY
expect_correction(<<~RUBY)
top = "test" \\
"top"
RUBY
end
it 'autocorrects only the lines that should be autocorrected' do
expect_offense(<<~'RUBY')
top = "test#{x}" <<
^^ Use `\` instead of `<<` to concatenate multiline strings.
"top" + # comment
"foo" +
^ Use `\` instead of `+` to concatenate multiline strings.
"bar" +
%(baz) +
"qux"
RUBY
expect_correction(<<~'RUBY')
top = "test#{x}" \
"top" + # comment
"foo" \
"bar" +
%(baz) +
"qux"
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_check_spec.rb | spec/rubocop/cop/style/class_check_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ClassCheck, :config do
context 'when enforced style is `is_a?`' do
let(:cop_config) { { 'EnforcedStyle' => 'is_a?' } }
it 'registers an offense for `kind_of?` and corrects to `is_a?`' do
expect_offense(<<~RUBY)
x.kind_of? y
^^^^^^^^ Prefer `Object#is_a?` over `Object#kind_of?`.
RUBY
expect_correction(<<~RUBY)
x.is_a? y
RUBY
end
it 'registers an offense for `kind_of?` is safe navigation called and corrects to `is_a?`' do
expect_offense(<<~RUBY)
x&.kind_of? y
^^^^^^^^ Prefer `Object#is_a?` over `Object#kind_of?`.
RUBY
expect_correction(<<~RUBY)
x&.is_a? y
RUBY
end
end
context 'when enforced style is kind_of?' do
let(:cop_config) { { 'EnforcedStyle' => 'kind_of?' } }
it 'registers an offense for `is_a?` and corrects to `kind_of?`' do
expect_offense(<<~RUBY)
x.is_a? y
^^^^^ Prefer `Object#kind_of?` over `Object#is_a?`.
RUBY
expect_correction(<<~RUBY)
x.kind_of? y
RUBY
end
it 'registers an offense for `is_a?` is safe navigation called and corrects to `kind_of?`' do
expect_offense(<<~RUBY)
x&.is_a? y
^^^^^ Prefer `Object#kind_of?` over `Object#is_a?`.
RUBY
expect_correction(<<~RUBY)
x&.kind_of? y
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/implicit_runtime_error_spec.rb | spec/rubocop/cop/style/implicit_runtime_error_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ImplicitRuntimeError, :config do
it 'registers an offense for `raise` without error class' do
expect_offense(<<~RUBY)
raise 'message'
^^^^^^^^^^^^^^^ Use `raise` with an explicit exception class and message, rather than just a message.
RUBY
end
it 'registers an offense for `fail` without error class' do
expect_offense(<<~RUBY)
fail 'message'
^^^^^^^^^^^^^^ Use `fail` with an explicit exception class and message, rather than just a message.
RUBY
end
it 'registers an offense for `raise` with a multiline string' do
expect_offense(<<~RUBY)
raise 'message' \\
^^^^^^^^^^^^^^^^^ Use `raise` with an explicit exception class and message, rather than just a message.
'2nd line'
RUBY
end
it 'registers an offense for `fail` with a multiline string' do
expect_offense(<<~RUBY)
fail 'message' \\
^^^^^^^^^^^^^^^^ Use `fail` with an explicit exception class and message, rather than just a message.
'2nd line'
RUBY
end
it 'does not register an offense for `raise` with an error class' do
expect_no_offenses(<<~RUBY)
raise StandardError, 'message'
RUBY
end
it 'does not register an offense for `fail` with an error class' do
expect_no_offenses(<<~RUBY)
fail StandardError, 'message'
RUBY
end
it 'does not register an offense for `raise` without arguments' do
expect_no_offenses('raise')
end
it 'does not register an offense for `fail` without arguments' do
expect_no_offenses('fail')
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/mixin_usage_spec.rb | spec/rubocop/cop/style/mixin_usage_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MixinUsage, :config do
context 'include' do
it 'registers an offense when using outside class (used above)' do
expect_offense(<<~RUBY)
include M
^^^^^^^^^ `include` is used at the top level. Use inside `class` or `module`.
class C
end
RUBY
end
it 'registers an offense when using outside class (used below)' do
expect_offense(<<~RUBY)
class C
end
include M
^^^^^^^^^ `include` is used at the top level. Use inside `class` or `module`.
RUBY
end
it 'registers an offense when using only `include` statement' do
expect_offense(<<~RUBY)
include M
^^^^^^^^^ `include` is used at the top level. Use inside `class` or `module`.
RUBY
end
it 'registers an offense when using `include` in method definition outside class or module' do
expect_offense(<<~RUBY)
def foo
include M
^^^^^^^^^ `include` is used at the top level. Use inside `class` or `module`.
end
RUBY
end
it 'does not register an offense when using outside class' do
expect_no_offenses(<<~RUBY)
Foo.include M
class C; end
RUBY
end
it 'does not register an offense when using inside class' do
expect_no_offenses(<<~RUBY)
class C
include M
end
RUBY
end
it 'does not register an offense when using inside block' do
expect_no_offenses(<<~RUBY)
Class.new do
include M
end
RUBY
end
it 'does not register an offense when using inside block ' \
'and `if` condition is after `include`' do
expect_no_offenses(<<~RUBY)
klass.class_eval do
include M1
include M2 if defined?(M)
end
RUBY
end
it "doesn't register an offense when `include` call is a method argument" do
expect_no_offenses(<<~RUBY)
do_something(include(M))
RUBY
end
it 'does not register an offense when using `include` in method definition inside class' do
expect_no_offenses(<<~RUBY)
class X
def foo
include M
end
end
RUBY
end
it 'does not register an offense when using `include` in method definition inside module' do
expect_no_offenses(<<~RUBY)
module X
def foo
include M
end
end
RUBY
end
context 'Multiple definition classes in one' do
it 'does not register an offense when using inside class' do
expect_no_offenses(<<~RUBY)
class C1
include M
end
class C2
include M
end
RUBY
end
end
context 'Nested module' do
it 'registers an offense when using outside class' do
expect_offense(<<~RUBY)
include M1::M2::M3
^^^^^^^^^^^^^^^^^^ `include` is used at the top level. Use inside `class` or `module`.
class C
end
RUBY
end
end
end
context 'extend' do
it 'registers an offense when using outside class' do
expect_offense(<<~RUBY)
extend M
^^^^^^^^ `extend` is used at the top level. Use inside `class` or `module`.
class C
end
RUBY
end
it 'does not register an offense when using inside class' do
expect_no_offenses(<<~RUBY)
class C
extend M
end
RUBY
end
end
context 'prepend' do
it 'registers an offense when using outside class' do
expect_offense(<<~RUBY)
prepend M
^^^^^^^^^ `prepend` is used at the top level. Use inside `class` or `module`.
class C
end
RUBY
end
it 'does not register an offense when using inside class' do
expect_no_offenses(<<~RUBY)
class C
prepend M
end
RUBY
end
end
it 'does not register an offense when using inside nested module' do
expect_no_offenses(<<~RUBY)
module M1
include M2
class C
include M3
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/class_equality_comparison_spec.rb | spec/rubocop/cop/style/class_equality_comparison_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ClassEqualityComparison, :config do
let(:cop_config) { { 'AllowedMethods' => [] } }
it 'registers an offense and corrects when comparing class using `==` for equality' do
expect_offense(<<~RUBY)
var.class == Date
^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing class using `equal?` for equality' do
expect_offense(<<~RUBY)
var.class.equal?(Date)
^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing class using `eql?` for equality' do
expect_offense(<<~RUBY)
var.class.eql?(Date)
^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
context 'when using `Class#name`' do
it 'registers an offense and corrects when comparing single quoted class name for equality' do
expect_offense(<<~RUBY)
var.class.name == 'Date'
^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing `Module#name` for equality' do
expect_offense(<<~RUBY)
var.class.name == Date.name
^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing double quoted class name for equality' do
expect_offense(<<~RUBY)
var.class.name == "Date"
^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'does not register an offense when comparing interpolated string class name for equality' do
expect_no_offenses(<<~'RUBY')
var.class.name == "String#{interpolation}"
RUBY
end
it 'registers an offense but does not correct when comparing local variable for equality' do
expect_offense(<<~RUBY)
class_name = 'Model'
var.class.name == class_name
^^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?` instead of comparing classes.
RUBY
expect_no_corrections
end
it 'registers an offense but does not correct when comparing instance variable for equality' do
expect_offense(<<~RUBY)
var.class.name == @class_name
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?` instead of comparing classes.
RUBY
expect_no_corrections
end
it 'registers an offense but does not correct when comparing method call for equality' do
expect_offense(<<~RUBY)
var.class.name == class_name
^^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?` instead of comparing classes.
RUBY
expect_no_corrections
end
it 'registers an offense but does not correct when comparing safe navigation method call for equality' do
expect_offense(<<~RUBY)
var.class.name == obj&.class_name
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?` instead of comparing classes.
RUBY
expect_no_corrections
end
end
context 'when using `Class#to_s`' do
it 'registers an offense and corrects when comparing single quoted class name for equality' do
expect_offense(<<~RUBY)
var.class.to_s == 'Date'
^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing `Module#name` for equality' do
expect_offense(<<~RUBY)
var.class.to_s == Date.to_s
^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing double quoted class name for equality' do
expect_offense(<<~RUBY)
var.class.to_s == "Date"
^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
end
context 'when using `Class#inspect`' do
it 'registers an offense and corrects when comparing single quoted class name for equality' do
expect_offense(<<~RUBY)
var.class.inspect == 'Date'
^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing `Module#name` for equality' do
expect_offense(<<~RUBY)
var.class.inspect == Date.inspect
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
it 'registers an offense and corrects when comparing double quoted class name for equality' do
expect_offense(<<~RUBY)
var.class.inspect == "Date"
^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Date)` instead of comparing classes.
RUBY
expect_correction(<<~RUBY)
var.instance_of?(Date)
RUBY
end
end
it 'does not register an offense when using `instance_of?`' do
expect_no_offenses(<<~RUBY)
var.instance_of?(Date)
RUBY
end
context 'when AllowedMethods is enabled' do
let(:cop_config) { { 'AllowedMethods' => ['=='] } }
it 'does not register an offense when comparing class for equality' do
expect_no_offenses(<<~RUBY)
def ==(other)
self.class == other.class &&
name == other.name
end
RUBY
end
end
context 'when AllowedPatterns is enabled' do
let(:cop_config) { { 'AllowedPatterns' => ['equal'] } }
it 'does not register an offense when comparing class for equality' do
expect_no_offenses(<<~RUBY)
def equal?(other)
self.class == other.class &&
name == other.name
end
RUBY
end
end
context 'with String comparison in module' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
module Foo
def bar?(value)
bar.class.name == 'Bar'
^^^^^^^^^^^^^^^^^^^ Use `instance_of?(::Bar)` instead of comparing classes.
end
class Bar
end
end
RUBY
expect_correction(<<~RUBY)
module Foo
def bar?(value)
bar.instance_of?(::Bar)
end
class Bar
end
end
RUBY
end
end
context 'with instance variable comparison in module' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
module Foo
def bar?(value)
bar.class.name == Model
^^^^^^^^^^^^^^^^^^^ Use `instance_of?(Model)` instead of comparing classes.
end
end
RUBY
expect_correction(<<~RUBY)
module Foo
def bar?(value)
bar.instance_of?(Model)
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/empty_case_condition_spec.rb | spec/rubocop/cop/style/empty_case_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyCaseCondition, :config do
shared_examples 'detect/correct empty case, accept non-empty case' do
it 'registers an offense and autocorrects' do
expect_offense(source)
expect_correction(corrected_source)
end
let(:source_with_case) { source.sub('case', 'case :a').sub(/^\s*\^.*\n/, '') }
it 'accepts the source with case' do
expect_no_offenses(source_with_case)
end
end
context 'given a case statement with an empty case' do
context 'with multiple when branches and an else' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when 1 == 2
foo
when 1 == 1
bar
else
baz
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if 1 == 2
foo
elsif 1 == 1
bar
else
baz
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'with multiple when branches and an `else` with code comments' do
let(:source) do
<<~RUBY
def example
# Comment before everything
case # first comment
^^^^ Do not use empty `case` condition, instead use an `if` expression.
# condition a
# This is a multi-line comment
when 1 == 2
foo
# condition b
when 1 == 1
bar
# condition c
else
baz
end
end
RUBY
end
let(:corrected_source) do
<<~RUBY
def example
# Comment before everything
# first comment
# condition a
# This is a multi-line comment
if 1 == 2
foo
# condition b
elsif 1 == 1
bar
# condition c
else
baz
end
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'with multiple when branches and no else' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when 1 == 2
foo
when 1 == 1
bar
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if 1 == 2
foo
elsif 1 == 1
bar
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'with a single when branch and an else' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when 1 == 2
foo
else
bar
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if 1 == 2
foo
else
bar
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'with a single when branch and no else' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when 1 == 2
foo
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if 1 == 2
foo
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'with a when branch including comma-delimited alternatives' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when false
foo
when nil, false, 1
bar
when false, 1
baz
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if false
foo
elsif nil || false || 1
bar
elsif false || 1
baz
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'with when branches using then' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when false then foo
when nil, false, 1 then bar
when false, 1 then baz
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if false then foo
elsif nil || false || 1 then bar
elsif false || 1 then baz
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'with first when branch including comma-delimited alternatives' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when my.foo?, my.bar?
something
when my.baz?
something_else
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if my.foo? || my.bar?
something
elsif my.baz?
something_else
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'when used as an argument of a method without comment' do
let(:source) do
<<~RUBY
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when object.nil?
Object.new
else
object
end
RUBY
end
let(:corrected_source) do
<<~RUBY
if object.nil?
Object.new
else
object
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'when used as an argument of a method with comment' do
let(:source) do
<<~RUBY
# example.rb
case
^^^^ Do not use empty `case` condition, instead use an `if` expression.
when object.nil?
Object.new
else
object
end
RUBY
end
let(:corrected_source) do
<<~RUBY
# example.rb
if object.nil?
Object.new
else
object
end
RUBY
end
it_behaves_like 'detect/correct empty case, accept non-empty case'
end
context 'when using `return` in `when` clause and assigning the return value of `case`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
v = case
when x.a
1
when x.b
return 2
end
RUBY
end
end
context 'when using `return ... if` in `when` clause and ' \
'assigning the return value of `case`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
v = case
when x.a
1
when x.b
return 2 if foo
end
RUBY
end
end
context 'when using `return` in `else` clause and assigning the return value of `case`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
v = case
when x.a
1
else
return 2
end
RUBY
end
end
context 'when using `return ... if` in `else` clause and ' \
'assigning the return value of `case`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
v = case
when x.a
1
else
return 2 if foo
end
RUBY
end
end
context 'when using `return` before empty case condition' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
return case
when foo
1
else
2
end
RUBY
end
end
context 'when using `break` before empty case condition', :ruby32, unsupported_on: :prism do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
break case
when foo
1
else
2
end
RUBY
end
end
context 'when using `next` before empty case condition', :ruby32, unsupported_on: :prism do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
next case
when foo
1
else
2
end
RUBY
end
end
context 'when using method call before empty case condition' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
do_something case
when foo
1
else
2
end
RUBY
end
end
context 'when using safe navigation method call before empty case condition' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
obj&.do_something case
when foo
1
else
2
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/colon_method_definition_spec.rb | spec/rubocop/cop/style/colon_method_definition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ColonMethodDefinition, :config do
it 'accepts a class method defined using .' do
expect_no_offenses(<<~RUBY)
class Foo
def self.bar
something
end
end
RUBY
end
context 'using self' do
it 'registers an offense for a class method defined using ::' do
expect_offense(<<~RUBY)
class Foo
def self::bar
^^ Do not use `::` for defining class methods.
something
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
def self.bar
something
end
end
RUBY
end
end
context 'using the class name' do
it 'registers an offense for a class method defined using ::' do
expect_offense(<<~RUBY)
class Foo
def Foo::bar
^^ Do not use `::` for defining class methods.
something
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
def Foo.bar
something
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/self_assignment_spec.rb | spec/rubocop/cop/style/self_assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SelfAssignment, :config do
%i[+ - * ** / % ^ << >> | & || &&].product(['x', '@x', '@@x']).each do |op, var|
it "registers an offense for non-shorthand assignment #{op} and #{var}" do
expect_offense(<<~RUBY, op: op, var: var)
%{var} = %{var} %{op} y
^{var}^^^^{var}^^{op}^^ Use self-assignment shorthand `#{op}=`.
RUBY
expect_correction(<<~RUBY)
#{var} #{op}= y
RUBY
end
end
%i[+ - * ** / % ^ << >> | &].product(['x', '@x', '@@x']).each do |op, var|
it 'registers an offense and corrects for a method call with parentheses' do
expect_offense(<<~RUBY, op: op, var: var)
%{var} = %{var}.%{op}(y)
^{var}^^^^{var}^^{op}^^^ Use self-assignment shorthand `#{op}=`.
RUBY
expect_correction(<<~RUBY)
#{var} #{op}= y
RUBY
end
it 'does not register an offense for a method call with multiple parameters' do
expect_no_offenses(<<~RUBY)
#{var} = #{var}.#{op}(y, z)
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/single_line_block_params_spec.rb | spec/rubocop/cop/style/single_line_block_params_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SingleLineBlockParams, :config do
let(:cop_config) { { 'Methods' => [{ 'reduce' => %w[a e] }, { 'test' => %w[x y] }] } }
it 'finds wrong argument names in calls with different syntax' do
expect_offense(<<~RUBY)
def m
[0, 1].reduce { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce{ |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce(5) { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce(5){ |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce (5) { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
[0, 1].reduce(5) { |c, d| c + d }
^^^^^^ Name `reduce` block params `|a, e|`.
ala.test { |x, z| bala }
^^^^^^ Name `test` block params `|x, y|`.
end
RUBY
expect_correction(<<~RUBY)
def m
[0, 1].reduce { |a, e| a + e }
[0, 1].reduce{ |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
[0, 1].reduce(5){ |a, e| a + e }
[0, 1].reduce (5) { |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
ala.test { |x, y| bala }
end
RUBY
end
it 'allows calls with proper argument names' do
expect_no_offenses(<<~RUBY)
def m
[0, 1].reduce { |a, e| a + e }
[0, 1].reduce{ |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
[0, 1].reduce(5){ |a, e| a + e }
[0, 1].reduce (5) { |a, e| a + e }
[0, 1].reduce(5) { |a, e| a + e }
ala.test { |x, y| bala }
end
RUBY
end
it 'allows an unused parameter to have a leading underscore' do
expect_no_offenses('File.foreach(filename).reduce(0) { |a, _e| a + 1 }')
end
it 'finds incorrectly named parameters with leading underscores' do
expect_offense(<<~RUBY)
File.foreach(filename).reduce(0) { |_x, _y| }
^^^^^^^^ Name `reduce` block params `|_a, _e|`.
RUBY
expect_correction(<<~RUBY)
File.foreach(filename).reduce(0) { |_a, _e| }
RUBY
end
it 'ignores do..end blocks' do
expect_no_offenses(<<~RUBY)
def m
[0, 1].reduce do |c, d|
c + d
end
end
RUBY
end
it 'ignores :reduce symbols' do
expect_no_offenses(<<~RUBY)
def m
call_method(:reduce) { |a, b| a + b}
end
RUBY
end
it 'does not report when destructuring is used' do
expect_no_offenses(<<~RUBY)
def m
test.reduce { |a, (id, _)| a + id}
end
RUBY
end
it 'does not report if no block arguments are present' do
expect_no_offenses(<<~RUBY)
def m
test.reduce { true }
end
RUBY
end
it 'reports an offense if the names are partially correct' do
expect_offense(<<~RUBY)
test.reduce(x) { |a, b| foo(a, b) }
^^^^^^ Name `reduce` block params `|a, e|`.
RUBY
expect_correction(<<~RUBY)
test.reduce(x) { |a, e| foo(a, e) }
RUBY
end
it 'reports an offense if the names are in reverse order' do
expect_offense(<<~RUBY)
test.reduce(x) { |e, a| foo(e, a) }
^^^^^^ Name `reduce` block params `|a, e|`.
RUBY
expect_correction(<<~RUBY)
test.reduce(x) { |a, e| foo(a, e) }
RUBY
end
it 'does not report if the right names are used but not all arguments are given' do
expect_no_offenses(<<~RUBY)
test.reduce(x) { |a| foo(a) }
RUBY
end
it 'reports an offense if the arguments names are wrong and not all arguments are given' do
expect_offense(<<~RUBY)
test.reduce(x) { |b| foo(b) }
^^^ Name `reduce` block params `|a|`.
RUBY
expect_correction(<<~RUBY)
test.reduce(x) { |a| foo(a) }
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/percent_q_literals_spec.rb | spec/rubocop/cop/style/percent_q_literals_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::PercentQLiterals, :config do
shared_examples 'accepts quote characters' do
it 'accepts single quotes' do
expect_no_offenses("'hi'")
end
it 'accepts double quotes' do
expect_no_offenses('"hi"')
end
end
shared_examples 'accepts any q string with backslash t' do
context 'with special characters' do
it 'accepts %q' do
expect_no_offenses('%q(\t)')
end
it 'accepts %Q' do
expect_no_offenses('%Q(\t)')
end
end
end
context 'when EnforcedStyle is lower_case_q' do
let(:cop_config) { { 'EnforcedStyle' => 'lower_case_q' } }
context 'without interpolation' do
it 'accepts %q' do
expect_no_offenses('%q(hi)')
end
it 'registers an offense for %Q' do
expect_offense(<<~RUBY)
%Q(hi)
^^^ Do not use `%Q` unless interpolation is needed. Use `%q`.
RUBY
expect_correction(<<~RUBY)
%q(hi)
RUBY
end
it_behaves_like 'accepts quote characters'
it_behaves_like 'accepts any q string with backslash t'
end
context 'with interpolation' do
it 'accepts %Q' do
expect_no_offenses('%Q(#{1 + 2})')
end
it 'accepts %q' do
# This is most probably a mistake, but not this cop's responsibility.
expect_no_offenses('%q(#{1 + 2})')
end
it_behaves_like 'accepts quote characters'
end
end
context 'when EnforcedStyle is upper_case_q' do
let(:cop_config) { { 'EnforcedStyle' => 'upper_case_q' } }
context 'without interpolation' do
it 'registers an offense for %q' do
expect_offense(<<~RUBY)
%q(hi)
^^^ Use `%Q` instead of `%q`.
RUBY
expect_correction(<<~RUBY)
%Q(hi)
RUBY
end
it 'accepts %Q' do
expect_no_offenses('%Q(hi)')
end
it 'does not register an offense when correcting leads to a parsing error' do
expect_no_offenses(<<~'RUBY')
%q(\u)
RUBY
end
it_behaves_like 'accepts quote characters'
it_behaves_like 'accepts any q string with backslash t'
end
context 'with interpolation' do
it 'accepts %Q' do
expect_no_offenses('%Q(#{1 + 2})')
end
it 'accepts %q' do
# It's strange if interpolation syntax appears inside a static string,
# but we can't be sure if it's a mistake or not. Changing it to %Q
# would alter semantics, so we leave it as it is.
expect_no_offenses('%q(#{1 + 2})')
end
it_behaves_like 'accepts quote characters'
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/signal_exception_spec.rb | spec/rubocop/cop/style/signal_exception_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SignalException, :config do
context 'when enforced style is `semantic`' do
let(:cop_config) { { 'EnforcedStyle' => 'semantic' } }
it 'registers an offense for raise in begin section' do
expect_offense(<<~RUBY)
begin
raise
^^^^^ Use `fail` instead of `raise` to signal exceptions.
rescue Exception
#do nothing
end
RUBY
expect_correction(<<~RUBY)
begin
fail
rescue Exception
#do nothing
end
RUBY
end
it 'registers an offense for raise in def body' do
expect_offense(<<~RUBY)
def test
raise
^^^^^ Use `fail` instead of `raise` to signal exceptions.
rescue Exception
#do nothing
end
RUBY
expect_correction(<<~RUBY)
def test
fail
rescue Exception
#do nothing
end
RUBY
end
it 'registers an offense for fail in rescue section' do
expect_offense(<<~RUBY)
begin
fail
rescue Exception
fail
^^^^ Use `raise` instead of `fail` to rethrow exceptions.
end
RUBY
expect_correction(<<~RUBY)
begin
fail
rescue Exception
raise
end
RUBY
end
it 'accepts raise in rescue section' do
expect_no_offenses(<<~RUBY)
begin
fail
rescue Exception
raise RuntimeError
end
RUBY
end
it 'accepts raise in def with multiple rescues' do
expect_no_offenses(<<~RUBY)
def test
fail
rescue StandardError
# handle error
rescue Exception
raise
end
RUBY
end
it 'registers an offense for fail in def rescue section' do
expect_offense(<<~RUBY)
def test
fail
rescue Exception
fail
^^^^ Use `raise` instead of `fail` to rethrow exceptions.
end
RUBY
expect_correction(<<~RUBY)
def test
fail
rescue Exception
raise
end
RUBY
end
it 'registers an offense for fail in second rescue' do
expect_offense(<<~RUBY)
def test
fail
rescue StandardError
# handle error
rescue Exception
fail
^^^^ Use `raise` instead of `fail` to rethrow exceptions.
end
RUBY
expect_correction(<<~RUBY)
def test
fail
rescue StandardError
# handle error
rescue Exception
raise
end
RUBY
end
it 'registers only offense for one raise that should be fail' do
# This is a special case that has caused double reporting.
expect_offense(<<~RUBY)
map do
raise 'I'
^^^^^ Use `fail` instead of `raise` to signal exceptions.
end.flatten.compact
RUBY
expect_correction(<<~RUBY)
map do
fail 'I'
end.flatten.compact
RUBY
end
it 'accepts raise in def rescue section' do
expect_no_offenses(<<~RUBY)
def test
fail
rescue Exception
raise
end
RUBY
end
it 'accepts `raise` and `fail` with explicit receiver' do
expect_no_offenses(<<~RUBY)
def test
test.raise
rescue Exception
test.fail
end
RUBY
end
it 'registers an offense for `raise` and `fail` with `Kernel` as explicit receiver' do
expect_offense(<<~RUBY)
def test
Kernel.raise
^^^^^ Use `fail` instead of `raise` to signal exceptions.
rescue Exception
Kernel.fail
^^^^ Use `raise` instead of `fail` to rethrow exceptions.
end
RUBY
expect_correction(<<~RUBY)
def test
Kernel.fail
rescue Exception
Kernel.raise
end
RUBY
end
it 'registers an offense for `raise` and `fail` with `::Kernel` as explicit receiver' do
expect_offense(<<~RUBY)
def test
::Kernel.raise
^^^^^ Use `fail` instead of `raise` to signal exceptions.
rescue Exception
::Kernel.fail
^^^^ Use `raise` instead of `fail` to rethrow exceptions.
end
RUBY
expect_correction(<<~RUBY)
def test
::Kernel.fail
rescue Exception
::Kernel.raise
end
RUBY
end
it 'registers an offense for raise not in a begin/rescue/end' do
expect_offense(<<~RUBY)
case cop_config['EnforcedStyle']
when 'single_quotes' then true
when 'double_quotes' then false
else raise 'Unknown StringLiterals style'
^^^^^ Use `fail` instead of `raise` to signal exceptions.
end
RUBY
expect_correction(<<~RUBY)
case cop_config['EnforcedStyle']
when 'single_quotes' then true
when 'double_quotes' then false
else fail 'Unknown StringLiterals style'
end
RUBY
end
it 'registers one offense for each raise' do
expect_offense(<<~RUBY)
cop.stub(:on_def) { raise RuntimeError }
^^^^^ Use `fail` instead of `raise` to signal exceptions.
cop.stub(:on_def) { raise RuntimeError }
^^^^^ Use `fail` instead of `raise` to signal exceptions.
RUBY
expect_correction(<<~RUBY)
cop.stub(:on_def) { fail RuntimeError }
cop.stub(:on_def) { fail RuntimeError }
RUBY
end
it 'is not confused by nested begin/rescue' do
expect_offense(<<~RUBY)
begin
raise
^^^^^ Use `fail` instead of `raise` to signal exceptions.
begin
raise
^^^^^ Use `fail` instead of `raise` to signal exceptions.
rescue
fail
^^^^ Use `raise` instead of `fail` to rethrow exceptions.
end
rescue Exception
#do nothing
end
RUBY
expect_correction(<<~RUBY)
begin
fail
begin
fail
rescue
raise
end
rescue Exception
#do nothing
end
RUBY
end
end
context 'when enforced style is `raise`' do
let(:cop_config) { { 'EnforcedStyle' => 'only_raise' } }
it 'registers an offense for fail in begin section' do
expect_offense(<<~RUBY)
begin
fail
^^^^ Always use `raise` to signal exceptions.
rescue Exception
#do nothing
end
RUBY
expect_correction(<<~RUBY)
begin
raise
rescue Exception
#do nothing
end
RUBY
end
it 'registers an offense for fail in def body' do
expect_offense(<<~RUBY)
def test
fail
^^^^ Always use `raise` to signal exceptions.
rescue Exception
#do nothing
end
RUBY
expect_correction(<<~RUBY)
def test
raise
rescue Exception
#do nothing
end
RUBY
end
it 'registers an offense for fail in rescue section' do
expect_offense(<<~RUBY)
begin
raise
rescue Exception
fail
^^^^ Always use `raise` to signal exceptions.
end
RUBY
expect_correction(<<~RUBY)
begin
raise
rescue Exception
raise
end
RUBY
end
it 'accepts `fail` if a custom `fail` instance method is defined' do
expect_no_offenses(<<~RUBY)
class A
def fail(arg)
end
def other_method
fail "message"
end
end
RUBY
end
it 'accepts `fail` if a custom `fail` singleton method is defined' do
expect_no_offenses(<<~RUBY)
class A
def self.fail(arg)
end
def self.other_method
fail "message"
end
end
RUBY
end
it 'accepts `fail` with explicit receiver' do
expect_no_offenses('test.fail')
end
it 'registers an offense for `fail` with `Kernel` as explicit receiver' do
expect_offense(<<~RUBY)
Kernel.fail
^^^^ Always use `raise` to signal exceptions.
RUBY
expect_correction(<<~RUBY)
Kernel.raise
RUBY
end
end
context 'when enforced style is `fail`' do
let(:cop_config) { { 'EnforcedStyle' => 'only_fail' } }
it 'registers an offense for raise in begin section' do
expect_offense(<<~RUBY)
begin
raise
^^^^^ Always use `fail` to signal exceptions.
rescue Exception
#do nothing
end
RUBY
expect_correction(<<~RUBY)
begin
fail
rescue Exception
#do nothing
end
RUBY
end
it 'registers an offense for raise in def body' do
expect_offense(<<~RUBY)
def test
raise
^^^^^ Always use `fail` to signal exceptions.
rescue Exception
#do nothing
end
RUBY
expect_correction(<<~RUBY)
def test
fail
rescue Exception
#do nothing
end
RUBY
end
it 'registers an offense for raise in rescue section' do
expect_offense(<<~RUBY)
begin
fail
rescue Exception
raise
^^^^^ Always use `fail` to signal exceptions.
end
RUBY
expect_correction(<<~RUBY)
begin
fail
rescue Exception
fail
end
RUBY
end
it 'accepts `raise` with explicit receiver' do
expect_no_offenses('test.raise')
end
it 'registers an offense for `raise` with `Kernel` as explicit receiver' do
expect_offense(<<~RUBY)
Kernel.raise
^^^^^ Always use `fail` to signal exceptions.
RUBY
expect_correction(<<~RUBY)
Kernel.fail
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_array_constructor_spec.rb | spec/rubocop/cop/style/redundant_array_constructor_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantArrayConstructor, :config do
it 'registers an offense when using an empty array literal argument for `Array.new`' do
expect_offense(<<~RUBY)
Array.new([])
^^^^^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
[]
RUBY
end
it 'registers an offense when using an empty array literal argument for `::Array.new`' do
expect_offense(<<~RUBY)
::Array.new([])
^^^^^^^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
[]
RUBY
end
it 'registers an offense when using an empty array literal argument for `Array[]`' do
expect_offense(<<~RUBY)
Array[]
^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
[]
RUBY
end
it 'registers an offense when using an empty array literal argument for `::Array[]`' do
expect_offense(<<~RUBY)
::Array[]
^^^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
[]
RUBY
end
it 'registers an offense when using an empty array literal argument for `Array([])`' do
expect_offense(<<~RUBY)
Array([])
^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
[]
RUBY
end
it 'registers an offense when using an array literal with some elements as an argument for `Array.new`' do
expect_offense(<<~RUBY)
Array.new(['foo', 'bar', 'baz'])
^^^^^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
['foo', 'bar', 'baz']
RUBY
end
it 'registers an offense when using an array literal with some elements as an argument for `Array[]`' do
expect_offense(<<~RUBY)
Array['foo', 'bar', 'baz']
^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
['foo', 'bar', 'baz']
RUBY
end
it 'registers an offense when using an array literal with some elements as an argument for `Array([])`' do
expect_offense(<<~RUBY)
Array(['foo', 'bar', 'baz'])
^^^^^ Remove the redundant `Array` constructor.
RUBY
expect_correction(<<~RUBY)
['foo', 'bar', 'baz']
RUBY
end
it 'does not register an offense when using an array literal' do
expect_no_offenses(<<~RUBY)
[]
RUBY
end
it 'does not register an offense when using single argument for `Array.new`' do
expect_no_offenses(<<~RUBY)
Array.new(array)
RUBY
end
it 'does not register an offense when using single argument for `Array()`' do
expect_no_offenses(<<~RUBY)
Array(array)
RUBY
end
it 'does not register an offense when using two argument for `Array.new`' do
expect_no_offenses(<<~RUBY)
Array.new(3, 'foo')
RUBY
end
it 'does not register an offense when using block argument for `Array.new`' do
expect_no_offenses(<<~RUBY)
Array.new(3) { '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/guard_clause_spec.rb | spec/rubocop/cop/style/guard_clause_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::GuardClause, :config do
let(:other_cops) do
{
'Layout/LineLength' => {
'Enabled' => line_length_enabled,
'Max' => 80
}
}
end
let(:line_length_enabled) { true }
shared_examples 'reports offense' do |body|
it 'reports an offense if method body is if / unless without else' do
expect_offense(<<~RUBY)
def func
if something
^^ Use a guard clause (`return unless something`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
def func
unless something
^^^^^^ Use a guard clause (`return if something`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
RUBY
expect_correction(<<~RUBY)
def func
return unless something
#{body}
#{trailing_whitespace}
end
def func
return if something
#{body}
#{trailing_whitespace}
end
RUBY
end
it 'reports an offense if method body ends with if / unless without else' do
expect_offense(<<~RUBY)
def func
test
if something
^^ Use a guard clause (`return unless something`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
def func
test
unless something
^^^^^^ Use a guard clause (`return if something`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
RUBY
expect_correction(<<~RUBY)
def func
test
return unless something
#{body}
#{trailing_whitespace}
end
def func
test
return if something
#{body}
#{trailing_whitespace}
end
RUBY
end
it 'reports an offense if `define_method` block body is if / unless without else' do
expect_offense(<<~RUBY)
define_method(:func) do
if _1
^^ Use a guard clause (`return unless _1`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
define_method(:func) do
unless _1
^^^^^^ Use a guard clause (`return if _1`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
RUBY
expect_correction(<<~RUBY)
define_method(:func) do
return unless _1
#{body}
#{trailing_whitespace}
end
define_method(:func) do
return if _1
#{body}
#{trailing_whitespace}
end
RUBY
end
it 'reports an offense if `define_method` block body is if / unless without else', :ruby34 do
expect_offense(<<~RUBY)
define_method(:func) do
if it
^^ Use a guard clause (`return unless it`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
define_method(:func) do
unless it
^^^^^^ Use a guard clause (`return if it`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
RUBY
expect_correction(<<~RUBY)
define_method(:func) do
return unless it
#{body}
#{trailing_whitespace}
end
define_method(:func) do
return if it
#{body}
#{trailing_whitespace}
end
RUBY
end
it 'reports an offense if `define_singleton_method` block body is if / unless without else' do
expect_offense(<<~RUBY)
define_singleton_method(:func) do
if _1
^^ Use a guard clause (`return unless _1`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
define_singleton_method(:func) do
unless _1
^^^^^^ Use a guard clause (`return if _1`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
RUBY
expect_correction(<<~RUBY)
define_singleton_method(:func) do
return unless _1
#{body}
#{trailing_whitespace}
end
define_singleton_method(:func) do
return if _1
#{body}
#{trailing_whitespace}
end
RUBY
end
it 'reports an offense if `define_method` numblock body is if / unless without else' do
expect_offense(<<~RUBY)
define_method(:func) do
if something
^^ Use a guard clause (`return unless something`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
define_method(:func) do
unless something
^^^^^^ Use a guard clause (`return if something`) instead of wrapping the code inside a conditional expression.
#{body}
end
end
RUBY
expect_correction(<<~RUBY)
define_method(:func) do
return unless something
#{body}
#{trailing_whitespace}
end
define_method(:func) do
return if something
#{body}
#{trailing_whitespace}
end
RUBY
end
it 'accepts an offense if block body ends with if / unless without else' do
expect_no_offenses(<<~RUBY)
foo do
test
if something
#{body}
end
end
foo do
test
unless something
#{body}
end
end
RUBY
end
end
it_behaves_like('reports offense', 'work')
it_behaves_like('reports offense', '# TODO')
it_behaves_like('reports offense', 'do_something(foo)')
it 'does not report an offense if body is if..elsif..end' do
expect_no_offenses(<<~RUBY)
def func
if something
a
elsif something_else
b
end
end
RUBY
end
it 'does not report an offense if block body is if..elsif..end' do
expect_no_offenses(<<~RUBY)
define_method(:func) do
if something
a
elsif something_else
b
end
end
RUBY
end
it "doesn't report an offense if condition has multiple lines" do
expect_no_offenses(<<~RUBY)
def func
if something &&
something_else
work
end
end
def func
unless something &&
something_else
work
end
end
RUBY
end
it 'accepts a method which body is if / unless with else' do
expect_no_offenses(<<~RUBY)
def func
if something
work
else
test
end
end
def func
unless something
work
else
test
end
end
RUBY
end
it 'registers an offense when using `|| raise` in `then` branch' do
expect_offense(<<~RUBY)
def func
if something
^^ Use a guard clause (`work || raise('message') if something`) instead of wrapping the code inside a conditional expression.
work || raise('message')
else
test
end
end
RUBY
expect_no_corrections
end
it 'registers an offense when using `|| raise` in `else` branch' do
expect_offense(<<~RUBY)
def func
if something
^^ Use a guard clause (`test || raise('message') unless something`) instead of wrapping the code inside a conditional expression.
work
else
test || raise('message')
end
end
RUBY
expect_no_corrections
end
it 'registers an offense when using `raise` in `else` branch in a one-liner with `then`' do
expect_offense(<<~RUBY)
if something then work else raise('message') end
^^ Use a guard clause (`raise('message') unless something`) instead of wrapping the code inside a conditional expression.
RUBY
expect_correction(<<~RUBY)
raise('message') unless something#{trailing_whitespace}
work#{trailing_whitespace * 3}
RUBY
end
it 'registers an offense when using `and return` in `then` branch' do
expect_offense(<<~RUBY)
def func
if something
^^ Use a guard clause (`work and return if something`) instead of wrapping the code inside a conditional expression.
work and return
else
test
end
end
RUBY
expect_no_corrections
end
it 'registers an offense when using `and return` in `else` branch' do
expect_offense(<<~RUBY)
def func
if something
^^ Use a guard clause (`test and return unless something`) instead of wrapping the code inside a conditional expression.
work
else
test and return
end
end
RUBY
expect_no_corrections
end
it 'accepts a method which body does not end with if / unless' do
expect_no_offenses(<<~RUBY)
def func
if something
work
end
test
end
def func
unless something
work
end
test
end
RUBY
end
it 'accepts a method whose body is a modifier if / unless' do
expect_no_offenses(<<~RUBY)
def func
work if something
end
def func
work unless something
end
RUBY
end
it 'accepts a method with empty parentheses as its body' do
expect_no_offenses(<<~RUBY)
def func
()
end
RUBY
end
it 'does not register an offense when assigning the result of a guard condition with `else`' do
expect_no_offenses(<<~RUBY)
def func
result = if something
work || raise('message')
else
test
end
end
RUBY
end
it 'does not register an offense when using a local variable assigned in a conditional expression in a branch' do
expect_no_offenses(<<~RUBY)
def func
if (foo = bar)
return foo
else
baz
end
end
RUBY
end
it 'does not register an offense when using local variables assigned in multiple conditional expressions in a branch' do
expect_no_offenses(<<~RUBY)
def func
if (foo = bar && baz = qux)
return [foo, baz]
else
quux
end
end
RUBY
end
it 'registers an offense when not using a local variable assigned in a conditional expression in a branch' do
expect_offense(<<~RUBY)
def func
if (foo = bar)
^^ Use a guard clause (`return baz if (foo = bar)`) instead of wrapping the code inside a conditional expression.
return baz
else
qux
end
end
RUBY
expect_correction(<<~RUBY)
def func
return baz if (foo = bar)
#{' '}
#{' '}
qux
#{' '}
end
RUBY
end
it 'registers an offense when using heredoc as an argument of raise in `then` branch' do
expect_offense(<<~RUBY)
def func
if condition
^^ Use a guard clause (`raise <<~MESSAGE unless condition`) instead of wrapping the code inside a conditional expression.
foo
else
raise <<~MESSAGE
oops
MESSAGE
end
end
RUBY
# NOTE: Let `Layout/HeredocIndentation`, `Layout/ClosingHeredocIndentation`, and
# `Layout/IndentationConsistency` cops autocorrect inconsistent indentations.
expect_correction(<<~RUBY)
def func
raise <<~MESSAGE unless condition
oops
MESSAGE
foo
end
RUBY
end
it 'registers an offense when using heredoc as an argument of raise in `else` branch' do
expect_offense(<<~RUBY)
def func
unless condition
^^^^^^ Use a guard clause (`raise <<~MESSAGE unless condition`) instead of wrapping the code inside a conditional expression.
raise <<~MESSAGE
oops
MESSAGE
else
foo
end
end
RUBY
# NOTE: Let `Layout/HeredocIndentation`, `Layout/ClosingHeredocIndentation`, and
# `Layout/IndentationConsistency` cops autocorrect inconsistent indentations.
expect_correction(<<~RUBY)
def func
raise <<~MESSAGE unless condition
oops
MESSAGE
foo
end
RUBY
end
it 'registers an offense when using heredoc as an argument of raise in `then` branch and it does not have `else` branch' do
expect_offense(<<~RUBY)
def func
if condition
^^ Use a guard clause (`return unless condition`) instead of wrapping the code inside a conditional expression.
raise <<~MESSAGE
oops
MESSAGE
end
end
RUBY
# NOTE: Let `Layout/HeredocIndentation`, `Layout/ClosingHeredocIndentation`, and
# `Layout/IndentationConsistency` cops autocorrect inconsistent indentations.
expect_correction(<<~RUBY)
def func
return unless condition
raise <<~MESSAGE
oops
MESSAGE
end
RUBY
end
it 'registers an offense when using xstr heredoc as an argument of raise in `else` branch' do
expect_offense(<<~RUBY)
def func
unless condition
^^^^^^ Use a guard clause (`raise <<~`MESSAGE` unless condition`) instead of wrapping the code inside a conditional expression.
raise <<~`MESSAGE`
oops
MESSAGE
else
foo
end
end
RUBY
# NOTE: Let `Layout/HeredocIndentation`, `Layout/ClosingHeredocIndentation`, and
# `Layout/IndentationConsistency` cops autocorrect inconsistent indentations.
expect_correction(<<~RUBY)
def func
raise <<~`MESSAGE` unless condition
oops
MESSAGE
foo
end
RUBY
end
it 'registers an offense when using lvar as an argument of raise in `else` branch' do
expect_offense(<<~RUBY)
if condition
^^ Use a guard clause (`raise e unless condition`) instead of wrapping the code inside a conditional expression.
do_something
else
raise e
end
RUBY
# NOTE: Let `Layout/TrailingWhitespace`, `Layout/EmptyLine`, and
# `Layout/EmptyLinesAroundMethodBody` cops autocorrect inconsistent indentations
# and blank lines.
expect_correction(<<~RUBY)
raise e unless condition
do_something
#{trailing_whitespace}
RUBY
end
context 'MinBodyLength: 1' do
let(:cop_config) { { 'MinBodyLength' => 1 } }
it 'reports an offense for if whose body has 1 line' do
expect_offense(<<~RUBY)
def func
if something
^^ Use a guard clause (`return unless something`) instead of wrapping the code inside a conditional expression.
work
end
end
def func
unless something
^^^^^^ Use a guard clause (`return if something`) instead of wrapping the code inside a conditional expression.
work
end
end
RUBY
expect_correction(<<~RUBY)
def func
return unless something
work
#{trailing_whitespace}
end
def func
return if something
work
#{trailing_whitespace}
end
RUBY
end
end
context 'MinBodyLength: 4' do
let(:cop_config) { { 'MinBodyLength' => 4 } }
it 'accepts a method whose body has 3 lines' do
expect_no_offenses(<<~RUBY)
def func
if something
work
work
work
end
end
def func
unless something
work
work
work
end
end
RUBY
end
end
context 'Invalid MinBodyLength' do
let(:cop_config) { { 'MinBodyLength' => -2 } }
it 'fails with an error' do
source = <<~RUBY
def func
if something
work
end
end
RUBY
expect { expect_no_offenses(source) }
.to raise_error('MinBodyLength needs to be a positive integer!')
end
end
context 'AllowConsecutiveConditionals: false' do
let(:cop_config) { { 'AllowConsecutiveConditionals' => false } }
it 'reports an offense when not allowed same depth multiple if statement and' \
'preceding expression is a conditional at the same depth' do
expect_offense(<<~RUBY)
def func
if foo?
work
end
if bar?
^^ Use a guard clause (`return unless bar?`) instead of wrapping the code inside a conditional expression.
work
end
end
RUBY
end
end
context 'AllowConsecutiveConditionals: true' do
let(:cop_config) { { 'AllowConsecutiveConditionals' => true } }
it 'does not register an offense when allowed same depth multiple if statement and' \
'preceding expression is not a conditional at the same depth' do
expect_no_offenses(<<~RUBY)
def func
if foo?
work
end
if bar?
work
end
end
RUBY
end
it 'reports an offense when allowed same depth multiple if statement and' \
'preceding expression is not a conditional at the same depth' do
expect_offense(<<~RUBY)
def func
if foo?
work
end
do_something
if bar?
^^ Use a guard clause (`return unless bar?`) instead of wrapping the code inside a conditional expression.
work
end
end
RUBY
end
end
shared_examples 'on if nodes which exit current scope' do |kw, options|
it "registers an offense with #{kw} in the if branch", *options do
expect_offense(<<~RUBY)
if something
^^ Use a guard clause (`#{kw} if something`) instead of wrapping the code inside a conditional expression.
#{kw}
else
puts "hello"
end
RUBY
expect_correction(<<~RUBY)
#{kw} if something
#{trailing_whitespace}
puts "hello"
RUBY
end
it "registers an offense with #{kw} in the else branch", *options do
expect_offense(<<~RUBY)
if something
^^ Use a guard clause (`#{kw} unless something`) instead of wrapping the code inside a conditional expression.
puts "hello"
else
#{kw}
end
RUBY
expect_correction(<<~RUBY)
#{kw} unless something
puts "hello"
#{trailing_whitespace}
RUBY
end
it "doesn't register an offense if condition has multiple lines", *options do
expect_no_offenses(<<~RUBY)
if something &&
something_else
#{kw}
else
puts "hello"
end
RUBY
end
it "does not report an offense if #{kw} is inside elsif", *options do
expect_no_offenses(<<~RUBY)
if something
a
elsif something_else
#{kw}
end
RUBY
end
it "does not report an offense if #{kw} is inside then body of if..elsif..end", *options do
expect_no_offenses(<<~RUBY)
if something
#{kw}
elsif something_else
a
end
RUBY
end
it "does not report an offense if #{kw} is inside if..elsif..else..end", *options do
expect_no_offenses(<<~RUBY)
if something
a
elsif something_else
b
else
#{kw}
end
RUBY
end
it "doesn't register an offense if control flow expr has multiple lines", *options do
expect_no_offenses(<<~RUBY)
if something
#{kw} 'blah blah blah' \\
'blah blah blah'
else
puts "hello"
end
RUBY
end
it 'registers an offense if non-control-flow branch has multiple lines', *options do
expect_offense(<<~RUBY)
if something
^^ Use a guard clause (`#{kw} if something`) instead of wrapping the code inside a conditional expression.
#{kw}
else
puts "hello" \\
"blah blah blah"
end
RUBY
expect_correction(<<~RUBY)
#{kw} if something
#{trailing_whitespace}
puts "hello" \\
"blah blah blah"
RUBY
end
end
context 'with Metrics/MaxLineLength enabled' do
context 'when the correction is too long for a single line' do
context 'with a trivial body' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def test
if something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line
work
end
end
RUBY
end
end
context 'with a nested `if` node' do
it 'does registers an offense' do
expect_offense(<<~RUBY)
def test
if something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line
^^ Use a guard clause (`unless something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line; return; end`) instead of wrapping the code inside a conditional expression.
if something_else
^^ Use a guard clause (`return unless something_else`) instead of wrapping the code inside a conditional expression.
work
end
end
end
RUBY
expect_correction(<<~RUBY)
def test
unless something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line
return
end
return unless something_else
work
#{trailing_whitespace}
#{trailing_whitespace}
end
RUBY
end
end
context 'with a nested `begin` node' do
it 'does registers an offense' do
expect_offense(<<~RUBY)
def test
if something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line
^^ Use a guard clause (`unless something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line; return; end`) instead of wrapping the code inside a conditional expression.
work
more_work
end
end
RUBY
expect_correction(<<~RUBY)
def test
unless something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line
return
end
work
more_work
#{trailing_whitespace}
end
RUBY
end
end
context 'with an empty `if` node and `raise` in else' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if foo?
^^ Use a guard clause (`unless foo?; raise 'very long and detailed description of the error that makes it too long to fit on one line'; end`) instead of wrapping the code inside a conditional expression.
else
raise 'very long and detailed description of the error that makes it too long to fit on one line'
end
RUBY
expect_correction(<<~RUBY)
unless foo?
raise 'very long and detailed description of the error that makes it too long to fit on one line'
end
#{trailing_whitespace}
RUBY
end
end
end
end
context 'with Metrics/MaxLineLength disabled' do
let(:line_length_enabled) { false }
it 'registers an offense with modifier example code regardless of length' do
expect_offense(<<~RUBY)
def test
if something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line
^^ Use a guard clause (`return unless something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line`) instead of wrapping the code inside a conditional expression.
work
end
end
RUBY
expect_correction(<<~RUBY)
def test
return unless something && something_that_makes_the_guard_clause_too_long_to_fit_on_one_line
work
#{trailing_whitespace}
end
RUBY
end
end
it_behaves_like('on if nodes which exit current scope', 'return')
it_behaves_like(
'on if nodes which exit current scope', 'next', [:ruby32, { unsupported_on: :prism }]
)
it_behaves_like(
'on if nodes which exit current scope', 'break', [:ruby32, { unsupported_on: :prism }]
)
it_behaves_like('on if nodes which exit current scope', 'raise "error"')
context 'method in module' do
it 'registers an offense for instance method' do
expect_offense(<<~RUBY)
module CopTest
def test
if something
^^ Use a guard clause (`return unless something`) instead of wrapping the code inside a conditional expression.
work
end
end
end
RUBY
expect_correction(<<~RUBY)
module CopTest
def test
return unless something
work
#{trailing_whitespace}
end
end
RUBY
end
it 'registers an offense for singleton methods' do
expect_offense(<<~RUBY)
module CopTest
def self.test
if something && something_else
^^ Use a guard clause (`return unless something && something_else`) instead of wrapping the code inside a conditional expression.
work
end
end
end
RUBY
expect_correction(<<~RUBY)
module CopTest
def self.test
return unless something && something_else
work
#{trailing_whitespace}
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/redundant_regexp_character_class_spec.rb | spec/rubocop/cop/style/redundant_regexp_character_class_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantRegexpCharacterClass, :config do
context 'with a character class containing a single character' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /[a]/
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = /a/
RUBY
end
end
context 'with multiple character classes containing single characters' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /[a]b[c]d/
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
^^^ Redundant single-element character class, `[c]` can be replaced with `c`.
RUBY
expect_correction(<<~RUBY)
foo = /abcd/
RUBY
end
end
context 'with a character class containing a single character inside a group' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /([a])/
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = /(a)/
RUBY
end
end
context 'with a character class containing a single character before `+` quantifier' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /[a]+/
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = /a+/
RUBY
end
end
context 'with a character class containing a single character before `{n,m}` quantifier' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /[a]{2,10}/
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = /a{2,10}/
RUBY
end
end
context 'with %r{} regexp' do
context 'with a character class containing a single character' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = %r{[a]}
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = %r{a}
RUBY
end
end
context 'with multiple character classes containing single characters' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = %r{[a]b[c]d}
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
^^^ Redundant single-element character class, `[c]` can be replaced with `c`.
RUBY
expect_correction(<<~RUBY)
foo = %r{abcd}
RUBY
end
end
context 'with a character class containing a single character inside a group' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = %r{([a])}
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = %r{(a)}
RUBY
end
end
context 'with a character class containing a single character before `+` quantifier' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = %r{[a]+}
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = %r{a+}
RUBY
end
end
context 'with a character class containing a single character before `{n,m}` quantifier' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = %r{[a]{2,10}}
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~RUBY)
foo = %r{a{2,10}}
RUBY
end
end
end
context 'with a character class containing a single range' do
it 'does not register an offense' do
expect_no_offenses('foo = /[a-z]/')
end
end
context 'with a character class containing a posix bracket expression' do
it 'does not register an offense' do
expect_no_offenses('foo = /[[:alnum:]]/')
end
end
context 'with a character class containing a negated posix bracket expression' do
it 'does not register an offense' do
expect_no_offenses('foo = /[[:^alnum:]]/')
end
end
context 'with a character class containing set intersection' do
it 'does not register an offense' do
expect_no_offenses('foo = /[[:alnum:]&&a-d]/')
end
end
context "with a regexp containing invalid \g escape" do
it 'registers an offense and corrects' do
# See https://ruby-doc.org/core-2.7.1/Regexp.html#class-Regexp-label-Subexpression+Calls
# \g should be \g<name>
expect_offense(<<~'RUBY')
foo = /[a]\g/
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~'RUBY')
foo = /a\g/
RUBY
end
end
context 'with a character class containing an escaped ]' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\]]/
^^^^ Redundant single-element character class, `[\]]` can be replaced with `\]`.
RUBY
expect_correction(<<~'RUBY')
foo = /\]/
RUBY
end
end
context 'with a character class containing an escaped [' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\[]/
^^^^ Redundant single-element character class, `[\[]` can be replaced with `\[`.
RUBY
expect_correction(<<~'RUBY')
foo = /\[/
RUBY
end
end
context 'with a character class containing a space meta-character' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\s]/
^^^^ Redundant single-element character class, `[\s]` can be replaced with `\s`.
RUBY
expect_correction(<<~'RUBY')
foo = /\s/
RUBY
end
end
context 'with a character class containing a negated-space meta-character' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\S]/
^^^^ Redundant single-element character class, `[\S]` can be replaced with `\S`.
RUBY
expect_correction(<<~'RUBY')
foo = /\S/
RUBY
end
end
context 'with a character class containing a single unicode code-point' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\u{06F2}]/
^^^^^^^^^^ Redundant single-element character class, `[\u{06F2}]` can be replaced with `\u{06F2}`.
RUBY
expect_correction(<<~'RUBY')
foo = /\u{06F2}/
RUBY
end
end
context 'with a character class containing multiple unicode code-points' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
foo = /[\u{0061 0062}]/
RUBY
end
end
context 'with a character class containing a single unicode character property' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\p{Digit}]/
^^^^^^^^^^^ Redundant single-element character class, `[\p{Digit}]` can be replaced with `\p{Digit}`.
RUBY
expect_correction(<<~'RUBY')
foo = /\p{Digit}/
RUBY
end
end
context 'with a character class containing a single negated unicode character property' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\P{Digit}]/
^^^^^^^^^^^ Redundant single-element character class, `[\P{Digit}]` can be replaced with `\P{Digit}`.
RUBY
expect_correction(<<~'RUBY')
foo = /\P{Digit}/
RUBY
end
end
context 'with a character class containing an escaped-#' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\#]/
^^^^ Redundant single-element character class, `[\#]` can be replaced with `\#`.
RUBY
expect_correction(<<~'RUBY')
foo = /\#/
RUBY
end
end
context 'with a character class containing an unescaped-#' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[#]{0}/
^^^ Redundant single-element character class, `[#]` can be replaced with `\#`.
RUBY
expect_correction(<<~'RUBY')
foo = /\#{0}/
RUBY
end
end
context 'with a character class containing an escaped-b' do
# See https://github.com/rubocop/rubocop/issues/8193 for details - in short \b != [\b] - the
# former matches a word boundary, the latter a backspace character.
it 'does not register an offense' do
expect_no_offenses('foo = /[\b]/')
end
end
context 'with a character class containing an octal escape sequence that also works outside' do
# See https://github.com/rubocop/rubocop/issues/11067 for details - in short "\0" != "0" - the
# former means an Unicode code point `"\u0000"`, the latter a number character `"0"`.
# Similarly "\032" means "\u001A".
# "\0" and "\" followed by *more* than one digit also work outside sets because they are
# not treated as backreferences by Onigmo.
it 'registers an offense for escapes that would work outside the class' do
expect_offense(<<~'RUBY')
foo = /[\032]/
^^^^^^ Redundant single-element character class, `[\032]` can be replaced with `\032`.
RUBY
expect_correction(<<~'RUBY')
foo = /\032/
RUBY
end
end
context 'with a character class containing an octal escape sequence that does not work outside' do
# The octal escapes \1 to \7 only work inside a character class
# because they would be a backreference outside it.
it 'does not register an offense' do
expect_no_offenses('foo = /[\1]/')
end
end
context 'with a character class containing a character requiring escape outside' do
# Not implemented for now, since we would have to escape on autocorrect, and the cop message
# would need to be dynamic to not be misleading.
it 'does not register an offense' do
expect_no_offenses('foo = /[+]/')
end
end
context 'with a character class containing escaped character requiring escape outside' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /[\+]/
^^^^ Redundant single-element character class, `[\+]` can be replaced with `\+`.
RUBY
expect_correction(<<~'RUBY')
foo = /\+/
RUBY
end
end
context 'with an interpolated unnecessary-character-class regexp' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /a#{/[b]/}c/
^^^ Redundant single-element character class, `[b]` can be replaced with `b`.
RUBY
expect_correction(<<~'RUBY')
foo = /a#{/b/}c/
RUBY
end
end
context 'with a character class with first element an escaped ]' do
it 'does not register an offense' do
expect_no_offenses('foo = /[\])]/')
end
end
context 'with a negated character class with a single element' do
it 'does not register an offense' do
expect_no_offenses('foo = /[^x]/')
end
end
context 'with a character class containing an interpolation' do
it 'does not register an offense' do
expect_no_offenses('foo = /[#{foo}]/')
end
end
context 'with consecutive escaped square brackets' do
it 'does not register an offense' do
expect_no_offenses('foo = /\[\]/')
end
end
context 'with consecutive escaped square brackets inside a character class' do
it 'does not register an offense' do
expect_no_offenses('foo = /[\[\]]/')
end
end
context 'with escaped square brackets surrounding a single character' do
it 'does not register an offense' do
expect_no_offenses('foo = /\[x\]/')
end
end
context 'with a character class containing two characters' do
it 'does not register an offense' do
expect_no_offenses('foo = /[ab]/')
end
end
context 'with an array index inside an interpolation' do
it 'does not register an offense' do
expect_no_offenses('foo = /a#{b[0]}c/')
end
end
context 'with a redundant character class after an interpolation' do
it 'registers an offense and corrects' do
expect_offense(<<~'RUBY')
foo = /#{x}[a]/
^^^ Redundant single-element character class, `[a]` can be replaced with `a`.
RUBY
expect_correction(<<~'RUBY')
foo = /#{x}a/
RUBY
end
end
context 'with a multi-line interpolation' do
it 'ignores offenses in the interpolated expression' do
expect_no_offenses(<<~'RUBY')
/#{Regexp.union(
%w"( ) { } [ ] < > $ ! ^ ` ... + * ? ,"
)}/o
RUBY
end
end
context 'with a character class containing a space' do
context 'when not using free-spaced mode' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /[ ]/
^^^ Redundant single-element character class, `[ ]` can be replaced with ` `.
RUBY
expect_correction(<<~RUBY)
foo = / /
RUBY
end
end
context 'with an unnecessary-character-class after a comment' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo = /
a # This comment shouldn't affect the position of the offense
[b]
^^^ Redundant single-element character class, `[b]` can be replaced with `b`.
/x
RUBY
expect_correction(<<~RUBY)
foo = /
a # This comment shouldn't affect the position of the offense
b
/x
RUBY
end
end
context 'when using free-spaced mode' do
context 'with a commented single-element character class' do
it 'does not register an offense' do
expect_no_offenses('foo = /foo # [a]/x')
end
end
context 'with a single space character class' do
it 'does not register an offense with only /x' do
expect_no_offenses('foo = /[ ]/x')
end
it 'does not register an offense with /ix' do
expect_no_offenses('foo = /[ ]/ix')
end
it 'does not register an offense with /iux' do
expect_no_offenses('foo = /[ ]/iux')
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/ambiguous_endless_method_definition_spec.rb | spec/rubocop/cop/style/ambiguous_endless_method_definition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::AmbiguousEndlessMethodDefinition, :config do
context 'Ruby >= 3.0', :ruby30 do
it 'does not register an offense for a non endless method' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
%i[and or if unless while until].each do |operator|
context "with #{operator}" do
it "does not register an offense for a non endless method followed by `#{operator}`" do
expect_no_offenses(<<~RUBY)
def foo
end #{operator} bar
RUBY
end
it 'does not register an offense when the operator is already wrapped in parens' do
expect_no_offenses(<<~RUBY)
def foo = (true #{operator} bar)
RUBY
end
it 'does not register an offense when the method definition is already wrapped in parens' do
expect_no_offenses(<<~RUBY)
(def foo = true) #{operator} bar
RUBY
end
unless %i[and or].include?(operator)
it "does not register an offense for non-modifier `#{operator}`" do
expect_no_offenses(<<~RUBY)
#{operator} bar
def foo = true
end
RUBY
end
end
it "registers an offense and corrects an endless method followed by `#{operator}`" do
expect_offense(<<~RUBY, operator: operator)
def foo = true #{operator} bar
^^^^^^^^^^^^^^^^{operator}^^^^ Avoid using `#{operator}` statements with endless methods.
RUBY
expect_correction(<<~RUBY)
def foo
true
end #{operator} bar
RUBY
end
end
end
it 'does not register an offense for `&&`' do
expect_no_offenses(<<~RUBY)
def foo = true && bar
RUBY
end
it 'does not register an offense for `||`' do
expect_no_offenses(<<~RUBY)
def foo = true || 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_string_escape_spec.rb | spec/rubocop/cop/style/redundant_string_escape_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantStringEscape, :config do
def wrap(contents)
[l, contents, r].join
end
RSpec.shared_examples 'common no offenses' do |l, r|
let(:l) { l }
let(:r) { r }
it 'does not register an offense without escapes' do
expect_no_offenses(wrap('a'))
end
it 'does not register an offense for an escaped backslash' do
expect_no_offenses(wrap('\\\\foo\\\\'))
end
it 'does not register an offense for an escaped gvar interpolation' do
expect_no_offenses(wrap('\#$foo'))
end
it 'does not register an offense for a $-escaped gvar interpolation' do
expect_no_offenses(wrap('#\$foo'))
end
it 'does not register an offense for an escaped ivar interpolation' do
expect_no_offenses(wrap('\#@foo'))
end
it 'does not register an offense for a @-escaped ivar interpolation' do
expect_no_offenses(wrap('#\@foo'))
end
it 'does not register an offense for an escaped cvar interpolation' do
expect_no_offenses(wrap('\#@@foo'))
end
it 'does not register an offense for a @-escaped cvar interpolation' do
expect_no_offenses(wrap('#\@@foo'))
end
it 'does not register an offense for an escaped interpolation' do
expect_no_offenses(wrap('\#{my_var}'))
end
it 'does not register an offense for a bracket-escaped interpolation' do
expect_no_offenses(wrap('#\{my_var}'))
end
it 'does not register an offense for an escaped # followed {' do
expect_no_offenses(wrap('\#{my_lvar}'))
end
it 'does not register a bracket-escaped lvar interpolation' do
expect_no_offenses(wrap('#\{my_lvar}'))
end
it 'does not register an offense for an escaped newline' do
expect_no_offenses(wrap("foo\\\nbar"))
end
it 'does not register an offense for a newline' do
expect_no_offenses(wrap('foo\n'))
end
it 'does not register an offense for a technically-unnecessary escape' do
expect_no_offenses(wrap('\d'))
end
it 'does not register an offense for an octal escape' do
expect_no_offenses(wrap('fo\157'))
end
it 'does not register an offense for a hex escape' do
expect_no_offenses(wrap('fo\x6f'))
end
it 'does not register an offense for a unicode escape' do
expect_no_offenses(wrap('fo\u006f'))
end
it 'does not register an offense for multiple unicode escapes' do
expect_no_offenses(wrap('f\u{006f 006f}'))
end
it 'does not register an offense for control characters' do
expect_no_offenses(wrap('\cc \C-c'))
end
it 'does not register an offense for a meta character' do
expect_no_offenses(wrap('\M-c'))
end
it 'does not register an offense for meta control characters' do
expect_no_offenses(wrap('\M-\C-c \M-\cc \c\M-c'))
end
it 'does not register an offense for an ascii DEL' do
expect_no_offenses(wrap('\c? \C-?'))
end
unless l.include?('<<') # HEREDOC delimiters can't be escaped
it 'does not register an offense for an escaped delimiter' do
expect_no_offenses(wrap("\\#{r}a\\#{r}"))
end
it 'does not register an offense for an escaped delimiter before interpolation' do
expect_no_offenses(wrap("\\#{r}\#{my_lvar}"))
end
end
end
RSpec.shared_examples 'a literal with interpolation' do |l, r|
# rubocop:disable RSpec/IncludeExamples
include_examples 'common no offenses', l, r
# rubocop:enable RSpec/IncludeExamples
it 'registers an offense and corrects an escaped # before interpolation' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}\##{whatever}%{r}
_{l}^^ Redundant escape of # inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}#\#{whatever}#{r}
RUBY
end
it 'registers an offense and corrects an escaped # without following {' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}\#whatever%{r}
_{l}^^ Redundant escape of # inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}#whatever#{r}
RUBY
end
it 'registers an offense and corrects an escaped } when escaping both brackets to avoid interpolation' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}#\{whatever\}%{r}
_{l} ^^ Redundant escape of } inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}#\\{whatever}#{r}
RUBY
end
it 'registers an offense and corrects an escaped `\{` when escaping `\#\{` to avoid interpolation' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}\#\{whatever}%{r}
_{l} ^^ Redundant escape of { inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}\\\#{whatever}#{r}
RUBY
end
it 'registers an offense and corrects an escaped # at end-of-string' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}\#%{r}
_{l}^^ Redundant escape of # inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}##{r}
RUBY
end
it 'registers an offense and corrects an escaped single quote' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}\'%{r}
_{l}^^ Redundant escape of ' inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}'#{r}
RUBY
end
if r != '"'
it 'registers an offense and corrects an escaped nested delimiter in a double quoted string' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}#{"\%{r}"}%{r}
_{l} ^^ Redundant escape of %{r} inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}\#{"#{r}"}#{r}
RUBY
end
it 'registers an offense and corrects an escaped double quote' do
expect_offense(<<~'RUBY', l: l, r: r)
%{l}\"%{r}
_{l}^^ Redundant escape of " inside string literal.
RUBY
expect_correction(<<~RUBY)
#{l}"#{r}
RUBY
end
end
end
RSpec.shared_examples 'a literal without interpolation' do |l, r|
# rubocop:disable RSpec/IncludeExamples
include_examples 'common no offenses', l, r
# rubocop:enable RSpec/IncludeExamples
it 'does not register an offense for an escaped # with following {' do
expect_no_offenses(wrap('\#{my_lvar}'))
end
it 'does not register an offense with escaped # without following {' do
expect_no_offenses(wrap('\#whatever'))
end
it 'does not register an offense with escaped # at end-of-string' do
expect_no_offenses(wrap('\#'))
end
it 'does not register an offense with escaped single quote' do
expect_no_offenses(wrap("\\'"))
end
it 'does not register an offense with escaped double quote' do
expect_no_offenses(wrap('\"'))
end
it 'does not register an offense for an allowed escape inside multi-line literal' do
expect_no_offenses(wrap("foo\\!\nbar"))
end
end
it 'does not register an offense for a `regexp` literal' do
expect_no_offenses('/\#/')
end
it 'does not register an offense for an `xstr` literal' do
expect_no_offenses('%x{\#}')
end
it 'does not register an offense for a `__FILE__` literal' do
expect_no_offenses('"__FILE__"')
end
it 'does not register an offense for a `__dir__` literal' do
expect_no_offenses('"__dir__"')
end
context 'with a double quoted string' do
it_behaves_like 'a literal with interpolation', '"', '"'
it 'does not register an offense with multiple escaped backslashes' do
expect_no_offenses(<<~'RUBY')
"\\\\ \\'foo\\' \\\\"
RUBY
end
it 'does not register an offense when escaping a quote in multi-line broken string' do
expect_no_offenses(<<~'RUBY')
"\""\
"\""
RUBY
end
it 'registers an offense and corrects an unnecessary escape in multi-line broken string' do
expect_offense(<<~'RUBY')
"\'"\
^^ Redundant escape of ' inside string literal.
"\'"
^^ Redundant escape of ' inside string literal.
RUBY
expect_correction(<<~'RUBY')
"'"\
"'"
RUBY
end
it 'does not register an offense with escaped double quote' do
expect_no_offenses('"\""')
end
it 'does not register an offense when an escaped double quote precedes interpolation in a symbol literal' do
expect_no_offenses(<<~'RUBY')
:"\"#{value}"
RUBY
end
end
context 'with a single quoted string' do
it_behaves_like 'a literal without interpolation', "'", "'"
end
context 'with a %q(...) literal' do
it_behaves_like 'a literal without interpolation', '%q(', ')'
end
context 'with a %Q(...) literal' do
it_behaves_like 'a literal with interpolation', '%Q(', ')'
end
context 'with a %Q!...! literal' do
it_behaves_like 'a literal with interpolation', '%Q!', '!'
end
context 'with a %(...) literal' do
it_behaves_like 'a literal with interpolation', '%(', ')'
end
context 'with a %w(...) literal' do
it_behaves_like 'a literal without interpolation', '%w(', ')'
it 'does not register an offense for escaped spaces' do
expect_no_offenses('%w[foo\ bar\ baz]')
end
end
context 'with a %W(...) literal' do
it_behaves_like 'a literal with interpolation', '%W[', ']'
it 'does not register an offense for escaped spaces' do
expect_no_offenses('%W[foo\ bar\ baz]')
end
end
context 'when using character literals' do
it 'does not register an offense for `?a`' do
expect_no_offenses(<<~RUBY)
?a
RUBY
end
it 'does not register an offense for `?\n`' do
expect_no_offenses(<<~'RUBY')
?\n
RUBY
end
end
context 'with an interpolation-enabled HEREDOC' do
# rubocop:disable RSpec/IncludeExamples
include_examples 'common no offenses', "<<~MYHEREDOC\n", "\nMYHEREDOC"
# rubocop:enable RSpec/IncludeExamples
it 'does not register an offense for a heredoc interpolating a string with an allowed escape' do
expect_no_offenses(<<~'RUBY')
<<~MYHEREDOC
#{foo.gsub(/[a-z]+/, '\"')}
MYHEREDOC
RUBY
end
it 'does not register an offense for a nested heredoc without interpolation' do
expect_no_offenses(<<~'RUBY')
<<~MYHEREDOC
#{
<<~'OTHERHEREDOC'
\#
OTHERHEREDOC
}
MYHEREDOC
RUBY
end
it 'registers an offense and corrects an escaped # before interpolation' do
expect_offense(<<~'RUBY')
<<~MYHEREDOC
\##{whatever}
^^ Redundant escape of # inside string literal.
MYHEREDOC
RUBY
expect_correction(<<~'RUBY')
<<~MYHEREDOC
##{whatever}
MYHEREDOC
RUBY
end
it 'registers an offense and corrects an escaped # without following {' do
expect_offense(<<~'RUBY')
<<~MYHEREDOC
\#whatever
^^ Redundant escape of # inside string literal.
MYHEREDOC
RUBY
expect_correction(<<~RUBY)
<<~MYHEREDOC
#whatever
MYHEREDOC
RUBY
end
it 'registers an offense and corrects an escaped # at end-of-string' do
expect_offense(<<~'RUBY')
<<~MYHEREDOC
\#
^^ Redundant escape of # inside string literal.
MYHEREDOC
RUBY
expect_correction(<<~RUBY)
<<~MYHEREDOC
#
MYHEREDOC
RUBY
end
it 'registers an offense and corrects an escaped single quote' do
expect_offense(<<~'RUBY')
<<~MYHEREDOC
\'
^^ Redundant escape of ' inside string literal.
MYHEREDOC
RUBY
expect_correction(<<~RUBY)
<<~MYHEREDOC
'
MYHEREDOC
RUBY
end
it 'does not register an offense an escaped space' do
expect_no_offenses(<<~'RUBY')
<<~MYHEREDOC
\ text
MYHEREDOC
RUBY
end
end
context 'with an interpolation-disabled HEREDOC' do
it_behaves_like 'a literal without interpolation', "<<~'MYHEREDOC'\n", "\nMYHEREDOC"
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/endless_method_spec.rb | spec/rubocop/cop/style/endless_method_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EndlessMethod, :config do
context 'Ruby >= 3.0', :ruby30 do
let(:other_cops) do
{
'Layout/LineLength' => {
'Enabled' => line_length_enabled,
'Max' => 80
}
}
end
let(:line_length_enabled) { true }
context 'EnforcedStyle: disallow' do
let(:cop_config) { { 'EnforcedStyle' => 'disallow' } }
it 'registers an offense for an endless method' do
expect_offense(<<~RUBY)
def my_method() = x
^^^^^^^^^^^^^^^^^^^ Avoid endless method definitions.
RUBY
expect_correction(<<~RUBY)
def my_method
x
end
RUBY
end
it 'registers an offense for an endless method with arguments' do
expect_offense(<<~RUBY)
def my_method(a, b) = x
^^^^^^^^^^^^^^^^^^^^^^^ Avoid endless method definitions.
RUBY
expect_correction(<<~RUBY)
def my_method(a, b)
x
end
RUBY
end
it 'does not register an offense for a single line method' do
expect_no_offenses(<<~RUBY)
def my_method
x
end
RUBY
end
end
context 'EnforcedStyle: allow_single_line' do
let(:cop_config) { { 'EnforcedStyle' => 'allow_single_line' } }
it 'does not register an offense for an endless method' do
expect_no_offenses(<<~RUBY)
def my_method() = x
RUBY
end
it 'does not register an offense for an endless method with arguments' do
expect_no_offenses(<<~RUBY)
def my_method(a, b) = x
RUBY
end
it 'does not register an offense for a single line method' do
expect_no_offenses(<<~RUBY)
def my_method
x
end
RUBY
end
it 'registers an offense and corrects for a multiline endless method' do
expect_offense(<<~RUBY)
def my_method() = x.foo
^^^^^^^^^^^^^^^^^^^^^^^ Avoid endless method definitions with multiple lines.
.bar
.baz
RUBY
expect_correction(<<~RUBY)
def my_method
x.foo
.bar
.baz
end
RUBY
end
it 'registers an offense and corrects for a multiline endless method with begin' do
expect_offense(<<~RUBY)
def my_method() = begin
^^^^^^^^^^^^^^^^^^^^^^^ Avoid endless method definitions with multiple lines.
foo && bar
end
RUBY
expect_correction(<<~RUBY)
def my_method
begin
foo && bar
end
end
RUBY
end
it 'registers an offense and corrects for a multiline endless method with arguments' do
expect_offense(<<~RUBY)
def my_method(a, b) = x.foo
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid endless method definitions with multiple lines.
.bar
.baz
RUBY
expect_correction(<<~RUBY)
def my_method(a, b)
x.foo
.bar
.baz
end
RUBY
end
end
context 'EnforcedStyle: allow_always' do
let(:cop_config) { { 'EnforcedStyle' => 'allow_always' } }
it 'does not register an offense for an endless method' do
expect_no_offenses(<<~RUBY)
def my_method() = x
RUBY
end
it 'does not register an offense for an endless method with arguments' do
expect_no_offenses(<<~RUBY)
def my_method(a, b) = x
RUBY
end
it 'does not register an offense for a single line method' do
expect_no_offenses(<<~RUBY)
def my_method
x
end
RUBY
end
it 'does not register an offense for a multiline endless method' do
expect_no_offenses(<<~RUBY)
def my_method() = x.foo
.bar
.baz
RUBY
end
it 'does not register an offense for a multiline endless method with begin' do
expect_no_offenses(<<~RUBY)
def my_method() = begin
foo && bar
end
RUBY
end
it 'does not register an offense for a multiline endless method with arguments' do
expect_no_offenses(<<~RUBY)
def my_method(a, b) = x.foo
.bar
.baz
RUBY
end
end
context 'EnforcedStyle: require_single_line' do
let(:cop_config) { { 'EnforcedStyle' => 'require_single_line' } }
it 'does not register an offense for a single line endless method' do
expect_no_offenses(<<~RUBY)
def my_method() = x
RUBY
end
it 'does not register an offense for a single line endless method with arguments' do
expect_no_offenses(<<~RUBY)
def my_method(a, b) = x
RUBY
end
it 'registers an offense and corrects for a multiline endless method' do
expect_offense(<<~RUBY)
def my_method() = x.foo
^^^^^^^^^^^^^^^^^^^^^^^ Avoid endless method definitions with multiple lines.
.bar
.baz
RUBY
expect_correction(<<~RUBY)
def my_method
x.foo
.bar
.baz
end
RUBY
end
it 'does not register an offense for no statements method' do
expect_no_offenses(<<~RUBY)
def my_method
end
RUBY
end
it 'does not register an offense for multiple statements method' do
expect_no_offenses(<<~RUBY)
def my_method
x.foo
x.bar
end
RUBY
end
it 'does not register an offense for multiple statements method with `begin`' do
expect_no_offenses(<<~RUBY)
def my_method
begin
foo && bar
end
end
RUBY
end
it 'does not register an offense when heredoc is used only in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
<<~HEREDOC
hello
HEREDOC
end
RUBY
end
it 'does not register an offense for heredoc is used in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
puts <<~HEREDOC
hello
HEREDOC
end
RUBY
end
it 'does not register an offense when multiline heredoc is used only in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
<<~HEREDOC
foo
bar
HEREDOC
end
RUBY
end
it 'does not register an offense when xstring heredoc is used only in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
<<~`HEREDOC`
command
HEREDOC
end
RUBY
end
it 'registers an offense and corrects for a single line method' do
expect_offense(<<~RUBY)
def my_method
^^^^^^^^^^^^^ Use endless method definitions for single line methods.
x
end
RUBY
expect_correction(<<~RUBY)
def my_method = x
RUBY
end
it 'registers an offense and corrects for a single line method with access modifier' do
expect_offense(<<~RUBY)
private def my_method
^^^^^^^^^^^^^ Use endless method definitions for single line methods.
x
end
RUBY
expect_correction(<<~RUBY)
private def my_method = x
RUBY
end
it 'does not register an offense for a single line setter method' do
expect_no_offenses(<<~RUBY)
def my_method=(arg)
arg.foo
end
RUBY
end
it 'does not register an offense when the endless version excess Metrics/MaxLineLength[Max]' do
expect_no_offenses(<<~RUBY)
def my_method
'this_string_ends_at_column_75_________________________________________'
end
RUBY
end
it 'does not register an offense when the endless with access modifier version excess Metrics/MaxLineLength[Max]' do
expect_no_offenses(<<~RUBY)
private def my_method
'this_string_ends_at_column_75_________________________________'
end
RUBY
end
context 'when Metrics/MaxLineLength is disabled' do
let(:line_length_enabled) { false }
it 'registers an offense and corrects for a long single line method that is long' do
expect_offense(<<~RUBY)
def my_method
^^^^^^^^^^^^^ Use endless method definitions for single line methods.
'this_string_ends_at_column_75_________________________________________'
end
RUBY
expect_correction(<<~RUBY)
def my_method = 'this_string_ends_at_column_75_________________________________________'
RUBY
end
it 'registers an offense and corrects for a long single line method with access modifier that is long' do
expect_offense(<<~RUBY)
private def my_method
^^^^^^^^^^^^^ Use endless method definitions for single line methods.
'this_string_ends_at_column_75_________________________________'
end
RUBY
expect_correction(<<~RUBY)
private def my_method = 'this_string_ends_at_column_75_________________________________'
RUBY
end
end
it 'registers an offense and corrects for a single line method with arguments' do
expect_offense(<<~RUBY)
def my_method(a, b)
^^^^^^^^^^^^^^^^^^^ Use endless method definitions for single line methods.
x
end
RUBY
expect_correction(<<~RUBY)
def my_method(a, b) = x
RUBY
end
it 'registers an offense and corrects for a multiline endless method with arguments' do
expect_offense(<<~RUBY)
def my_method(a, b) = x.foo
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid endless method definitions with multiple lines.
.bar
.baz
RUBY
expect_correction(<<~RUBY)
def my_method(a, b)
x.foo
.bar
.baz
end
RUBY
end
end
context 'EnforcedStyle: require_always' do
let(:cop_config) { { 'EnforcedStyle' => 'require_always' } }
it 'does not register an offense for an endless method' do
expect_no_offenses(<<~RUBY)
def my_method() = x
RUBY
end
it 'does not register an offense for an endless method with arguments' do
expect_no_offenses(<<~RUBY)
def my_method(a, b) = x
RUBY
end
it 'does not register an offense for an multiline endless method' do
expect_no_offenses(<<~RUBY)
def my_method = x.foo
.bar
.baz
RUBY
end
it 'does not register an offense for no statements method' do
expect_no_offenses(<<~RUBY)
def my_method
end
RUBY
end
it 'does not register an offense for multiple statements method' do
expect_no_offenses(<<~RUBY)
def my_method
x.foo
x.bar
end
RUBY
end
it 'does not register an offense for multiple statements method with `begin`' do
expect_no_offenses(<<~RUBY)
def my_method
begin
foo && bar
end
end
RUBY
end
it 'does not register an offense when heredoc is used only in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
<<~HEREDOC
hello
HEREDOC
end
RUBY
end
it 'does not register an offense for heredoc is used in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
puts <<~HEREDOC
hello
HEREDOC
end
RUBY
end
it 'does not register an offense when multiline heredoc is used only in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
<<~HEREDOC
foo
bar
HEREDOC
end
RUBY
end
it 'does not register an offense when xstring heredoc is used only in regular method definition' do
expect_no_offenses(<<~RUBY)
def my_method
<<~`HEREDOC`
command
HEREDOC
end
RUBY
end
it 'registers an offense and corrects for a single line method' do
expect_offense(<<~RUBY)
def my_method
^^^^^^^^^^^^^ Use endless method definitions.
x
end
RUBY
expect_correction(<<~RUBY)
def my_method = x
RUBY
end
it 'registers an offense and corrects for a single line method with arguments' do
expect_offense(<<~RUBY)
def my_method(a, b)
^^^^^^^^^^^^^^^^^^^ Use endless method definitions.
x
end
RUBY
expect_correction(<<~RUBY)
def my_method(a, b) = x
RUBY
end
it 'registers an offense and corrects for a multiline method' do
expect_offense(<<~RUBY)
def my_method
^^^^^^^^^^^^^ Use endless method definitions.
x.foo
.bar
.baz
end
RUBY
expect_correction(<<~RUBY)
def my_method = x.foo
.bar
.baz
RUBY
end
it 'does not register an offense for a multiline setter method' do
expect_no_offenses(<<~RUBY)
def my_method=(arg)
x.foo
.bar
.baz
end
RUBY
end
it 'does not register an offense when the endless version excess Metrics/MaxLineLength[Max]' do
expect_no_offenses(<<~RUBY)
def my_method
'this_string_ends_at_column_75_________________________________________'
end
RUBY
end
context 'when Metrics/MaxLineLength is disabled' do
let(:line_length_enabled) { false }
it 'registers an offense and corrects for a long single line method that is long' do
expect_offense(<<~RUBY)
def my_method
^^^^^^^^^^^^^ Use endless method definitions.
'this_string_ends_at_column_75_________________________________________'
end
RUBY
expect_correction(<<~RUBY)
def my_method = 'this_string_ends_at_column_75_________________________________________'
RUBY
end
end
it 'registers an offense and corrects for a multiline method with arguments' do
expect_offense(<<~RUBY)
def my_method(a, b)
^^^^^^^^^^^^^^^^^^^ Use endless method definitions.
x.foo
.bar
.baz
end
RUBY
expect_correction(<<~RUBY)
def my_method(a, b) = x.foo
.bar
.baz
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/case_like_if_spec.rb | spec/rubocop/cop/style/case_like_if_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CaseLikeIf, :config do
let(:cop_config) { { 'MinBranchesCount' => 2 } }
it 'registers an offense and corrects when using `===`' do
expect_offense(<<~RUBY)
if Integer === x
^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif /foo/ === x
elsif (1..10) === x
else
end
RUBY
expect_correction(<<~RUBY)
case x
when Integer
when /foo/
when (1..10)
else
end
RUBY
end
it 'registers an offense and corrects when using `==` with literal' do
expect_offense(<<~RUBY)
if x == 1
^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif 'str' == x
else
end
RUBY
expect_correction(<<~RUBY)
case x
when 1
when 'str'
else
end
RUBY
end
it 'registers an offense and corrects when using `==` with constant' do
expect_offense(<<~RUBY)
if x == CONSTANT1
^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif CONSTANT2 == x
else
end
RUBY
expect_correction(<<~RUBY)
case x
when CONSTANT1
when CONSTANT2
else
end
RUBY
end
it 'registers an offense when using `==` with literal and using ternary operator' do
expect_offense(<<~RUBY)
if foo == 1
^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif foo == 2
else
foo == 3 ? bar : baz
end
RUBY
expect_correction(<<~RUBY)
case foo
when 1
when 2
else
foo == 3 ? bar : baz
end
RUBY
end
it 'does not register an offense when using `==` with method call with arguments' do
expect_no_offenses(<<~RUBY)
if x == foo(1)
elsif bar(1) == x
else
end
RUBY
end
it 'does not register an offense when using `==` with class reference' do
expect_no_offenses(<<~RUBY)
if x == Foo
elsif Bar == x
else
end
RUBY
end
it 'does not register an offense when one of the branches contains `==` with class reference' do
expect_no_offenses(<<~RUBY)
if x == 1
elsif x == Foo
else
end
RUBY
end
it 'does not register an offense when using `==` with constant containing 1 letter in name' do
expect_no_offenses(<<~RUBY)
if x == F
elsif B == x
else
end
RUBY
end
it 'does not register an offense when using `equal?` without a receiver' do
expect_no_offenses(<<~RUBY)
if equal?(Foo)
elsif Bar == x
else
end
RUBY
end
it 'registers an offense and corrects when using `is_a?`' do
expect_offense(<<~RUBY)
if x.is_a?(Foo)
^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif x.is_a?(Bar)
else
end
RUBY
expect_correction(<<~RUBY)
case x
when Foo
when Bar
else
end
RUBY
end
it 'registers an offense and corrects when using `match?` with regexp' do
expect_offense(<<~RUBY)
if /foo/.match?(x)
^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif x.match?(/bar/)
else
end
RUBY
expect_correction(<<~RUBY)
case x
when /foo/
when /bar/
else
end
RUBY
end
it 'does not register an offense when using `match?` with non regexp' do
expect_no_offenses(<<~RUBY)
if y.match?(x)
elsif x.match?('str')
else
end
RUBY
end
it 'does not register an offense when using `match?` without a receiver' do
expect_no_offenses(<<~RUBY)
if match?(/foo/)
elsif x.match?(/bar/)
else
end
RUBY
end
it 'does not register an offense when using `include?` without a receiver' do
expect_no_offenses(<<~RUBY)
if include?(Foo)
elsif include?(Bar)
else
end
RUBY
end
it 'does not register an offense when using `cover?` without a receiver' do
expect_no_offenses(<<~RUBY)
if x == 1
elsif cover?(Bar)
else
end
RUBY
end
it 'registers an offense and corrects when using `=~`' do
expect_offense(<<~RUBY)
if /foo/ =~ x
^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif x =~ returns_regexp(arg)
else
end
RUBY
expect_correction(<<~RUBY)
case x
when /foo/
when returns_regexp(arg)
else
end
RUBY
end
it 'does not register an offense when using `=~` in first branch with non regexp' do
expect_no_offenses(<<~RUBY)
if x =~ returns_regexp(arg)
elsif x =~ /foo/
else
end
RUBY
end
it 'does not register an offense when using `match?` in first branch with non regexp' do
expect_no_offenses(<<~RUBY)
if returns_regexp(arg).match?(x)
elsif x.match?(/bar/)
else
end
RUBY
end
it 'registers an offense and corrects when using `match?` with non regexp in other branches except first' do
expect_offense(<<~RUBY)
if /foo/.match?(x)
^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif returns_regexp(arg).match?(x)
else
end
RUBY
expect_correction(<<~RUBY)
case x
when /foo/
when returns_regexp(arg)
else
end
RUBY
end
it 'registers an offense and corrects when using `include?` with range' do
expect_offense(<<~RUBY)
if (1..10).include?(x)
^^^^^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif (11...100).include?(x)
else
end
RUBY
expect_correction(<<~RUBY)
case x
when 1..10
when 11...100
else
end
RUBY
end
it 'registers an offense and corrects when using `||` within conditions' do
expect_offense(<<~RUBY)
if Integer === x || x == 2
^^^^^^^^^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif 1 == x || (1..10) === x || x.match?(/foo/)
else
end
RUBY
expect_correction(<<~RUBY)
case x
when Integer, 2
when 1, (1..10), /foo/
else
end
RUBY
end
it 'does not register an offense when one of `||` subconditions is not convertible' do
expect_no_offenses(<<~RUBY)
if Integer === x || (x == 2 && x == 3)
elsif 1 == x || (1..10) === x || x.match?(/foo/)
else
end
RUBY
end
it 'registers an offense and corrects when using nested conditions with `||`' do
expect_offense(<<~RUBY)
if Integer === x || ((x == 2) || (3 == x)) || x =~ /foo/
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif 1 == x || (1..10) === x || x.match?(/bar/)
else
end
RUBY
expect_correction(<<~RUBY)
case x
when Integer, 2, 3, /foo/
when 1, (1..10), /bar/
else
end
RUBY
end
it 'registers an offense and corrects when target is a method call' do
expect_offense(<<~RUBY)
if x.type == 1 || x.type == 2
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif /foo/ === x.type
else
end
RUBY
expect_correction(<<~RUBY)
case x.type
when 1, 2
when /foo/
else
end
RUBY
end
it 'does not register an offense when not all conditions contain target' do
expect_no_offenses(<<~RUBY)
if x == 2
elsif 3 == y
else
end
RUBY
end
it 'does not register an offense when only single `if`' do
expect_no_offenses(<<~RUBY)
if x == 1
end
RUBY
end
it 'does not register an offense when only `if-else`' do
expect_no_offenses(<<~RUBY)
if x == 1
else
end
RUBY
end
it 'does not register an offense when using `unless`' do
expect_no_offenses(<<~RUBY)
unless x == 1
else
end
RUBY
end
it 'does not register an offense when using ternary operator' do
expect_no_offenses(<<~RUBY)
x == 1 ? y : z
RUBY
end
it 'does not register an offense when using modifier `if`' do
expect_no_offenses(<<~RUBY)
foo if x == 1
RUBY
end
it 'does not register an offense when an object overrides `equal?` with no arity' do
expect_no_offenses(<<~RUBY)
if x.equal?
elsif y
end
RUBY
end
context 'when using regexp with named captures' do
it 'does not register an offense with =~ and regexp on lhs' do
expect_no_offenses(<<~RUBY)
if /(?<name>.*)/ =~ foo
elsif foo == 123
end
RUBY
end
it 'registers and corrects an offense with =~ and regexp on rhs' do
expect_offense(<<~RUBY)
if foo =~ /(?<name>.*)/
^^^^^^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif foo == 123
end
RUBY
expect_correction(<<~RUBY)
case foo
when /(?<name>.*)/
when 123
end
RUBY
end
it 'does not register an offense with match and regexp on lhs' do
expect_no_offenses(<<~RUBY)
if /(?<name>.*)/.match(foo)
elsif foo == 123
end
RUBY
end
it 'does not register an offense with match and regexp on rhs' do
expect_no_offenses(<<~RUBY)
if foo.match(/(?<name>.*)/)
elsif foo == 123
end
RUBY
end
it 'registers and corrects an offense with match? and regexp on lhs' do
expect_offense(<<~RUBY)
if /(?<name>.*)/.match?(foo)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif foo == 123
end
RUBY
expect_correction(<<~RUBY)
case foo
when /(?<name>.*)/
when 123
end
RUBY
end
it 'registers and corrects an offense with match? and regexp on rhs' do
expect_offense(<<~RUBY)
if foo.match?(/(?<name>.*)/)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Convert `if-elsif` to `case-when`.
elsif foo == 123
end
RUBY
expect_correction(<<~RUBY)
case foo
when /(?<name>.*)/
when 123
end
RUBY
end
end
context 'MinBranchesCount: 3' do
let(:cop_config) { { 'MinBranchesCount' => 3 } }
it 'does not register an offense when branches count is less than required' do
expect_no_offenses(<<~RUBY)
if x == 1
elsif x == 2
else
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/raise_args_spec.rb | spec/rubocop/cop/style/raise_args_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RaiseArgs, :config do
context 'when enforced style is compact' do
let(:cop_config) { { 'EnforcedStyle' => 'compact' } }
context 'with a raise with 2 args' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise RuntimeError, msg
^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
raise RuntimeError.new(msg)
RUBY
end
end
context 'with a raise with 2 args and exception object is assigned to a local variable' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise error_class, msg
^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
raise error_class.new(msg)
RUBY
end
end
context 'with a raise with exception instantiation and message arguments' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise FooError.new, message
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
raise FooError.new(message)
RUBY
end
end
context 'when used in a ternary expression' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
foo ? raise(Ex, 'error') : bar
^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
foo ? raise(Ex.new('error')) : bar
RUBY
end
end
context 'when used in a logical and expression' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
bar && raise(Ex, 'error')
^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
bar && raise(Ex.new('error'))
RUBY
end
end
context 'when used in a logical or expression' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
bar || raise(Ex, 'error')
^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
bar || raise(Ex.new('error'))
RUBY
end
end
context 'with correct + opposite' do
it 'reports an offense' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
else
raise Ex.new(msg)
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError.new(msg)
else
raise Ex.new(msg)
end
RUBY
end
it 'reports multiple offenses' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
elsif b
raise Ex.new(msg)
else
raise ArgumentError, msg
^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError.new(msg)
elsif b
raise Ex.new(msg)
else
raise ArgumentError.new(msg)
end
RUBY
end
end
context 'with a raise with 3 args' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise RuntimeError, msg, caller
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_no_corrections
end
end
it 'accepts a raise with msg argument' do
expect_no_offenses('raise msg')
end
it 'accepts a raise with an exception argument' do
expect_no_offenses('raise Ex.new(msg)')
end
it 'accepts exception constructor with keyword arguments and message argument' do
expect_no_offenses('raise MyKwArgError.new(a: 1, b: 2), message')
end
end
context 'when enforced style is exploded' do
let(:cop_config) { { 'EnforcedStyle' => 'exploded' } }
context 'with a raise with exception object' do
context 'with one argument' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise Ex.new(msg)
^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
raise Ex, msg
RUBY
end
end
context 'with no arguments' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise Ex.new
^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
raise Ex
RUBY
end
end
context 'when used in a ternary expression' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
foo ? raise(Ex.new('error')) : bar
^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
foo ? raise(Ex, 'error') : bar
RUBY
end
end
context 'when used in a logical and expression' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
bar && raise(Ex.new('error'))
^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
bar && raise(Ex, 'error')
RUBY
end
end
context 'when used in a logical or expression' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
bar || raise(Ex.new('error'))
^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
bar || raise(Ex, 'error')
RUBY
end
end
end
context 'with opposite + correct' do
it 'reports an offense for opposite + correct' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
else
raise Ex.new(msg)
^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError, msg
else
raise Ex, msg
end
RUBY
end
it 'reports multiple offenses' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
elsif b
raise Ex.new(msg)
^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
else
raise ArgumentError.new(msg)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError, msg
elsif b
raise Ex, msg
else
raise ArgumentError, msg
end
RUBY
end
end
context 'when an exception object is assigned to a local variable' do
it 'autocorrects to exploded style' do
expect_offense(<<~RUBY)
def do_something
klass = RuntimeError
raise klass.new('hi')
^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
end
RUBY
expect_correction(<<~RUBY)
def do_something
klass = RuntimeError
raise klass, 'hi'
end
RUBY
end
end
context 'when exception type is in AllowedCompactTypes' do
before do
stub_const('Ex1', StandardError)
stub_const('Ex2', StandardError)
end
let(:cop_config) { { 'EnforcedStyle' => 'exploded', 'AllowedCompactTypes' => ['Ex1'] } }
it 'accepts exception constructor with no arguments' do
expect_no_offenses('raise Ex1.new')
end
context 'with one argument' do
it 'accepts exception constructor' do
expect_no_offenses('raise Ex1.new(msg)')
end
end
context 'with more than one argument' do
it 'accepts exception constructor' do
expect_no_offenses('raise Ex1.new(arg1, arg2)')
end
end
end
it 'accepts exception constructor with more than 1 argument' do
expect_no_offenses('raise MyCustomError.new(a1, a2, a3)')
end
it 'accepts exception constructor with keyword arguments' do
expect_no_offenses('raise MyKwArgError.new(a: 1, b: 2)')
end
it 'accepts a raise with splatted arguments' do
expect_no_offenses('raise MyCustomError.new(*args)')
end
context 'when Ruby >= 3.2', :ruby32 do
it 'accepts a raise with anonymous splatted arguments' do
expect_no_offenses('def foo(*) raise MyCustomError.new(*) end')
end
it 'accepts a raise with anonymous keyword splatted arguments' do
expect_no_offenses('def foo(**) raise MyCustomError.new(**) end')
end
end
context 'when Ruby >= 27', :ruby27 do
it 'accepts a raise with triple dot forwarding' do
expect_no_offenses('def foo(...) raise MyCustomError.new(...) end')
end
end
it 'ignores a raise with an exception argument' do
expect_no_offenses('raise Ex.new(entity), message')
end
it 'accepts a raise with 3 args' do
expect_no_offenses('raise RuntimeError, msg, caller')
end
it 'accepts a raise with 2 args' do
expect_no_offenses('raise RuntimeError, msg')
end
it 'accepts a raise when exception object is assigned to a local variable' do
expect_no_offenses('raise error_class, msg')
end
it 'accepts a raise with msg argument' do
expect_no_offenses('raise msg')
end
it 'accepts a raise with `new` method without receiver' do
expect_no_offenses('raise new')
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_touch_spec.rb | spec/rubocop/cop/style/file_touch_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FileTouch, :config do
it 'registers an offense when using `File.open` in append mode with empty block' do
expect_offense(<<~RUBY)
File.open(filename, 'a') {}
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `FileUtils.touch(filename)` instead of `File.open` in append mode with empty block.
RUBY
expect_correction(<<~RUBY)
FileUtils.touch(filename)
RUBY
end
it 'does not register an offense when using `File.open` in append mode without a block' do
expect_no_offenses(<<~RUBY)
File.open(filename, 'a')
RUBY
end
it 'does not register an offense when using `File.open` in write mode' do
expect_no_offenses(<<~RUBY)
File.open(filename, 'w') {}
RUBY
end
it 'does not register an offense when using `File.open` without an access mode' do
expect_no_offenses(<<~RUBY)
File.open(filename) {}
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/auto_resource_cleanup_spec.rb | spec/rubocop/cop/style/auto_resource_cleanup_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::AutoResourceCleanup, :config do
it 'registers an offense for File.open without block' do
expect_offense(<<~RUBY)
File.open("filename")
^^^^^^^^^^^^^^^^^^^^^ Use the block version of `File.open`.
RUBY
end
it 'registers an offense for Tempfile.open without block' do
expect_offense(<<~RUBY)
Tempfile.open("filename")
^^^^^^^^^^^^^^^^^^^^^^^^^ Use the block version of `Tempfile.open`.
RUBY
end
it 'registers an offense for ::File.open without block' do
expect_offense(<<~RUBY)
::File.open("filename")
^^^^^^^^^^^^^^^^^^^^^^^ Use the block version of `::File.open`.
RUBY
end
it 'registers an offense for ::Tempfile.open without block' do
expect_offense(<<~RUBY)
::Tempfile.open("filename")
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the block version of `::Tempfile.open`.
RUBY
end
it 'does not register an offense for File.open with block' do
expect_no_offenses('File.open("file") { |f| something }')
end
it 'does not register an offense for File.open with block-pass' do
expect_no_offenses('File.open("file", &:read)')
end
it 'does not register an offense for File.open with immediate close' do
expect_no_offenses('File.open("file", "w", 0o777).close')
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/numbered_parameters_limit_spec.rb | spec/rubocop/cop/style/numbered_parameters_limit_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NumberedParametersLimit, :config do
let(:cop_config) { { 'Max' => max } }
let(:max) { 2 }
context 'with Ruby >= 2.7', :ruby27 do
it 'does not register an offense for a normal block with too many parameters' do
expect_no_offenses(<<~RUBY)
foo { |a, b, c, d, e, f, g| do_something(a,b,c,d,e,f,g) }
RUBY
end
it 'does not register an offense for a numblock with fewer than `Max` parameters' do
expect_no_offenses(<<~RUBY)
foo { do_something(_1) }
RUBY
end
it 'does not register an offense for a numblock with exactly `Max` parameters' do
expect_no_offenses(<<~RUBY)
foo { do_something(_1, _2) }
RUBY
end
context 'when there are more than `Max` numbered parameters' do
it 'registers an offense for a single line `numblock`' do
expect_offense(<<~RUBY)
foo { do_something(_1, _2, _3, _4, _5) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using more than 2 numbered parameters; 5 detected.
RUBY
end
it 'registers an offense for a multiline `numblock`' do
expect_offense(<<~RUBY)
foo do
^^^^^^ Avoid using more than 2 numbered parameters; 5 detected.
do_something(_1, _2, _3, _4, _5)
end
RUBY
end
end
context 'when configuring Max' do
let(:max) { 5 }
it 'does not register an offense when there are not too many numbered params' do
expect_no_offenses(<<~RUBY)
foo { do_something(_1, _2, _3, _4, _5) }
RUBY
end
end
context 'when Max is 1' do
let(:max) { 1 }
it 'does not register an offense when only numbered parameter `_1` is used once' do
expect_no_offenses(<<~RUBY)
foo { do_something(_1) }
RUBY
end
it 'does not register an offense when only numbered parameter `_1` is used twice' do
expect_no_offenses(<<~RUBY)
foo { do_something(_1, _1) }
RUBY
end
it 'does not register an offense when only numbered parameter `_9` is used once' do
expect_no_offenses(<<~RUBY)
foo { do_something(_9) }
RUBY
end
it 'does not register an offense when using numbered parameter with underscored local variable' do
expect_no_offenses(<<~RUBY)
_lvar = 42
foo { do_something(_2, _lvar) }
RUBY
end
it 'uses the right offense message' do
expect_offense(<<~RUBY)
foo { do_something(_1, _2, _3, _4, _5) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using more than 1 numbered parameter; 5 detected.
RUBY
end
end
it 'sets Max properly for auto-gen-config' do
expect_offense(<<~RUBY)
foo { do_something(_1, _2, _3, _4, _5) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using more than 2 numbered parameters; 5 detected.
RUBY
expect(cop.config_to_allow_offenses).to eq(exclude_limit: { 'Max' => 5 })
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_if_then_spec.rb | spec/rubocop/cop/style/multiline_if_then_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineIfThen, :config do
it 'does not get confused by empty elsif branch' do
expect_no_offenses(<<~RUBY)
if cond
elsif cond
end
RUBY
end
it 'registers an offense for then in multiline if' do
expect_offense(<<~RUBY)
if cond then
^^^^ Do not use `then` for multi-line `if`.
end
if cond then\t
^^^^ Do not use `then` for multi-line `if`.
end
if cond then
^^^^ Do not use `then` for multi-line `if`.
end
if cond
then
^^^^ Do not use `then` for multi-line `if`.
end
if cond then # bad
^^^^ Do not use `then` for multi-line `if`.
end
RUBY
expect_correction(<<~RUBY)
if cond
end
if cond\t
end
if cond
end
if cond
end
if cond # bad
end
RUBY
end
it 'registers an offense for then in multiline elsif' do
expect_offense(<<~RUBY)
if cond1
a
elsif cond2 then
^^^^ Do not use `then` for multi-line `elsif`.
b
end
RUBY
expect_correction(<<~RUBY)
if cond1
a
elsif cond2
b
end
RUBY
end
it 'accepts table style if/then/elsif/ends' do
expect_no_offenses(<<~RUBY)
if @io == $stdout then str << "$stdout"
elsif @io == $stdin then str << "$stdin"
elsif @io == $stderr then str << "$stderr"
else str << @io.class.to_s
end
RUBY
end
it 'does not get confused by a then in a when' do
expect_no_offenses(<<~RUBY)
if a
case b
when c then
end
end
RUBY
end
it 'does not get confused by a commented-out then' do
expect_no_offenses(<<~RUBY)
if a # then
b
end
if c # then
end
RUBY
end
it 'does not raise an error for an implicit match if' do
expect do
expect_no_offenses(<<~RUBY)
if //
end
RUBY
end.not_to raise_error
end
# unless
it 'registers an offense for then in multiline unless' do
expect_offense(<<~RUBY)
unless cond then
^^^^ Do not use `then` for multi-line `unless`.
end
RUBY
expect_correction(<<~RUBY)
unless cond
end
RUBY
end
it 'does not get confused by a postfix unless' do
expect_no_offenses('two unless one')
end
it 'does not get confused by a nested postfix unless' do
expect_no_offenses(<<~RUBY)
if two
puts 1
end unless two
RUBY
end
it 'does not raise an error for an implicit match unless' do
expect do
expect_no_offenses(<<~RUBY)
unless //
end
RUBY
end.not_to raise_error
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/case_equality_spec.rb | spec/rubocop/cop/style/case_equality_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CaseEquality, :config do
shared_examples 'offenses' do
it 'does not fail when the receiver is implicit' do
expect_no_offenses(<<~RUBY)
puts "No offense"
RUBY
end
it 'does not register an offense for === when the receiver is not a camel cased constant' do
expect_no_offenses(<<~RUBY)
REGEXP_CONSTANT === var
RUBY
end
it 'does not register an offense for === when the receiver is a regexp' do
# This detection is expected to be supported by `Performance/RegexpMatch`.
expect_no_offenses(<<~RUBY)
/OMG/ === var
RUBY
end
it 'registers an offense and corrects for === when the receiver is a range' do
expect_offense(<<~RUBY)
(1..10) === var
^^^ Avoid the use of the case equality operator `===`.
RUBY
expect_correction(<<~RUBY)
(1..10).include?(var)
RUBY
end
it 'registers an offense and does not correct for === when receiver is of some other type' do
expect_offense(<<~RUBY)
foo === var
^^^ Avoid the use of the case equality operator `===`.
RUBY
expect_no_corrections
end
end
context 'when AllowOnConstant is false' do
let(:cop_config) { { 'AllowOnConstant' => false } }
it 'registers an offense and corrects for === when the receiver is a constant' do
expect_offense(<<~RUBY)
Array === var
^^^ Avoid the use of the case equality operator `===`.
RUBY
expect_correction(<<~RUBY)
var.is_a?(Array)
RUBY
end
it_behaves_like 'offenses'
end
context 'when AllowOnConstant is true' do
let(:cop_config) { { 'AllowOnConstant' => true } }
it 'does not register an offense for === when the receiver is a constant' do
expect_no_offenses(<<~RUBY)
Array === var
RUBY
end
it_behaves_like 'offenses'
end
context 'when AllowOnSelfClass is false' do
let(:cop_config) { { 'AllowOnSelfClass' => false } }
it 'registers an offense and corrects for === when the receiver is self.class' do
expect_offense(<<~RUBY)
self.class === var
^^^ Avoid the use of the case equality operator `===`.
RUBY
expect_correction(<<~RUBY)
var.is_a?(self.class)
RUBY
end
it_behaves_like 'offenses'
end
context 'when AllowOnSelfClass is true' do
let(:cop_config) { { 'AllowOnSelfClass' => true } }
it 'does not register an offense for === when the receiver is self.class' do
expect_no_offenses(<<~RUBY)
self.class === var
RUBY
end
it 'registers an offense but does not correct for === when the receiver is self.klass' do
expect_offense(<<~RUBY)
self.klass === var
^^^ Avoid the use of the case equality operator `===`.
RUBY
expect_no_corrections
end
it_behaves_like 'offenses'
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_each_methods_spec.rb | spec/rubocop/cop/style/hash_each_methods_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashEachMethods, :config do
context 'when node matches a keys#each or values#each' do
context 'when receiver is a send' do
it 'registers an offense autocorrects foo#keys.each to foo#each_key' do
expect_offense(<<~RUBY)
foo.keys.each { |k| p k }
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY
expect_correction(<<~RUBY)
foo.each_key { |k| p k }
RUBY
end
it 'registers an offense autocorrects `foo&.keys&.each` to `foo&.each_key`' do
expect_offense(<<~RUBY)
foo&.keys&.each { |k| p k }
^^^^^^^^^^ Use `each_key` instead of `keys&.each`.
RUBY
expect_correction(<<~RUBY)
foo&.each_key { |k| p k }
RUBY
end
it 'registers an offense autocorrects foo#values.each to foo#each_value' do
expect_offense(<<~RUBY)
foo.values.each { |v| p v }
^^^^^^^^^^^ Use `each_value` instead of `values.each`.
RUBY
expect_correction(<<~RUBY)
foo.each_value { |v| p v }
RUBY
end
it 'registers an offense autocorrects `foo&.values&.each` to `foo&.each_value`' do
expect_offense(<<~RUBY)
foo&.values&.each { |v| p v }
^^^^^^^^^^^^ Use `each_value` instead of `values&.each`.
RUBY
expect_correction(<<~RUBY)
foo&.each_value { |v| p v }
RUBY
end
it 'registers an offense autocorrects foo#keys.each to foo#each_key with a symbol proc argument' do
expect_offense(<<~RUBY)
foo.keys.each(&:bar)
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY
expect_correction(<<~RUBY)
foo.each_key(&:bar)
RUBY
end
it 'registers an offense autocorrects foo#values.each to foo#each_value with a symbol proc argument' do
expect_offense(<<~RUBY)
foo.values.each(&:bar)
^^^^^^^^^^^ Use `each_value` instead of `values.each`.
RUBY
expect_correction(<<~RUBY)
foo.each_value(&:bar)
RUBY
end
it 'does not register an offense when the key and value block arguments of `Enumerable#each` method are used' do
expect_no_offenses('foo.each { |k, v| do_something(k, v) }')
end
it 'does not register an offense when the destructed value block arguments of `Enumerable#each` method are used' do
expect_no_offenses('foo.each { |k, (_, v)| do_something(k, v) }')
end
it 'does not register an offense when the destructed key block arguments of `Enumerable#each` method are used' do
expect_no_offenses('foo.each { |(_, k), v| do_something(k, v) }')
end
it 'does not register an offense when the destructed rest value block arguments of `Enumerable#each` method are used' do
expect_no_offenses('foo.each { |k, (_, *v)| do_something(k, *v) }')
end
it 'does not register an offense when the destructed rest key block arguments of `Enumerable#each` method are used' do
expect_no_offenses('foo.each { |(_, *k), v| do_something(*k, v) }')
end
it 'does not register an offense when the single block argument of `Enumerable#each` method is used' do
expect_no_offenses('foo.each { |e| do_something(e) }')
end
it 'does not register an offense when the parenthesized key and value block arguments of `Enumerable#each` method are unused' do
expect_no_offenses('foo.each { |(k, v)| do_something(e) }')
end
it 'does not register an offense when the rest value block argument of `Enumerable#each` method is used' do
expect_no_offenses('foo.each { |k, *v| do_something(k, *v) }')
end
it 'does not register an offense when the rest key block argument of `Enumerable#each` method is used' do
expect_no_offenses('foo.each { |*k, v| do_something(*k, v) }')
end
it 'does not register an offense when both arguments of `Enumerable#each` are unused' do
expect_no_offenses('foo.each { |k, v| do_something }')
end
it 'does not register an offense when the body of `Enumerable#each` is empty' do
expect_no_offenses('foo.each { |k, v| }')
end
it 'registers an offense when the rest value block argument of `Enumerable#each` method is unused' do
expect_offense(<<~RUBY)
foo.each { |k, *v| do_something(*v) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `each_value` instead of `each` and remove the unused `k` block argument.
RUBY
expect_correction(<<~RUBY)
foo.each_value { |*v| do_something(*v) }
RUBY
end
it 'registers an offense when the rest key block argument of `Enumerable#each` method is unused' do
expect_offense(<<~RUBY)
foo.each { |*k, v| do_something(*k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `each_key` instead of `each` and remove the unused `v` block argument.
RUBY
expect_correction(<<~RUBY)
foo.each_key { |*k| do_something(*k) }
RUBY
end
it 'registers an offense when the value block argument of `Enumerable#each` method is unused' do
expect_offense(<<~RUBY)
foo.each { |k, unused_value| do_something(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `each_key` instead of `each` and remove the unused `unused_value` block argument.
RUBY
expect_correction(<<~RUBY)
foo.each_key { |k| do_something(k) }
RUBY
end
it 'registers an offense when the value block argument of `Enumerable#each` method with safe navigation call is unused' do
expect_offense(<<~RUBY)
foo&.each { |k, unused_value| do_something(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `each_key` instead of `each` and remove the unused `unused_value` block argument.
RUBY
expect_correction(<<~RUBY)
foo&.each_key { |k| do_something(k) }
RUBY
end
it 'registers an offense when the destructed value block argument of `Enumerable#each` method is unused' do
expect_offense(<<~RUBY)
foo.each { |k, (_, unused_value)| do_something(k) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `each_key` instead of `each` and remove the unused `(_, unused_value)` block argument.
RUBY
expect_correction(<<~RUBY)
foo.each_key { |k| do_something(k) }
RUBY
end
it 'registers an offense when the key block argument of `Enumerable#each` method is unused' do
expect_offense(<<~RUBY)
foo.each { |unused_key, v| do_something(v) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `each_value` instead of `each` and remove the unused `unused_key` block argument.
RUBY
expect_correction(<<~RUBY)
foo.each_value { |v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `assoc`' do
expect_no_offenses(<<~RUBY)
foo.assoc(key).each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `chunk`' do
expect_no_offenses(<<~RUBY)
foo.chunk { |i| i.do_something }.each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `flatten`' do
expect_no_offenses(<<~RUBY)
foo.flatten.each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `rassoc`' do
expect_no_offenses(<<~RUBY)
foo.rassoc(value).each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `sort`' do
expect_no_offenses(<<~RUBY)
foo.sort.each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `sort_by`' do
expect_no_offenses(<<~RUBY)
foo.sort_by { |k, v| v }.each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `sort_by` with numblock' do
expect_no_offenses(<<~RUBY)
foo.sort_by { _2 }.each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `to_a`' do
expect_no_offenses(<<~RUBY)
foo.to_a.each { |unused_key, v| do_something(v) }
RUBY
end
it 'does not register an offense when the key block argument of `Enumerable#each` method is unused after `to_a` with safe navigation' do
expect_no_offenses(<<~RUBY)
foo&.to_a.each { |unused_key, v| do_something(v) }
RUBY
end
it 'registers an offense when the destructed key block argument of `Enumerable#each` method is unused' do
expect_offense(<<~RUBY)
foo.each { |(_, unused_key), v| do_something(v) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `each_value` instead of `each` and remove the unused `(_, unused_key)` block argument.
RUBY
expect_correction(<<~RUBY)
foo.each_value { |v| do_something(v) }
RUBY
end
it 'registers an offense and corrects when `{hash: :literal}.keys.each`' do
expect_offense(<<~RUBY)
{hash: :literal}.keys.each { |k| p k }
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY
expect_correction(<<~RUBY)
{hash: :literal}.each_key { |k| p k }
RUBY
end
it 'does not register an offense when `[[1, 2, 3], [4 ,5, 6]].each`' do
expect_no_offenses(<<~RUBY)
[[1, 2, 3], [4, 5, 6]].each { |a, _| p a }
RUBY
end
it 'does not register an offense for foo#each_key' do
expect_no_offenses('foo.each_key { |k| p k }')
end
it 'does not register an offense for Hash#each_value' do
expect_no_offenses('foo.each_value { |v| p v }')
end
it 'does not register an offense if the hash is written to in `keys.each`' do
expect_no_offenses(<<~'RUBY')
foo.keys.each do |key|
foo["#{key}_copy"] = value
end
RUBY
end
it 'does not register an offense if the hash is written to in `values.each`' do
expect_no_offenses(<<~'RUBY')
foo.values.each do |value|
foo["#{value}_copy"] = value
end
RUBY
end
it 'registers an offense and corrects if another hash is written to in `keys.each`' do
expect_offense(<<~'RUBY')
foo.keys.each do |key|
^^^^^^^^^ Use `each_key` instead of `keys.each`.
bar["#{key}_copy"] = value
end
RUBY
expect_correction(<<~'RUBY')
foo.each_key do |key|
bar["#{key}_copy"] = value
end
RUBY
end
it 'registers an offense and corrects if another hash is written to in `values.each`' do
expect_offense(<<~'RUBY')
foo.values.each do |value|
^^^^^^^^^^^ Use `each_value` instead of `values.each`.
bar["#{value}_copy"] = value
end
RUBY
expect_correction(<<~'RUBY')
foo.each_value do |value|
bar["#{value}_copy"] = value
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense autocorrects foo#keys.each to foo#each_key with numblock' do
expect_offense(<<~RUBY)
foo.keys.each { p _1 }
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY
expect_correction(<<~RUBY)
foo.each_key { p _1 }
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense autocorrects foo#keys.each to foo#each_key with itblock' do
expect_offense(<<~RUBY)
foo.keys.each { p it }
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY
expect_correction(<<~RUBY)
foo.each_key { p it }
RUBY
end
end
end
context 'when receiver is a hash literal' do
it 'registers an offense autocorrects {}#keys.each with {}#each_key' do
expect_offense(<<~RUBY)
{}.keys.each { |k| p k }
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY
expect_correction(<<~RUBY)
{}.each_key { |k| p k }
RUBY
end
it 'registers an offense autocorrects {}#values.each with {}#each_value' do
expect_offense(<<~RUBY)
{}.values.each { |k| p k }
^^^^^^^^^^^ Use `each_value` instead of `values.each`.
RUBY
expect_correction(<<~RUBY)
{}.each_value { |k| p k }
RUBY
end
it 'registers an offense autocorrects {}#keys.each to {}#each_key with a symbol proc argument' do
expect_offense(<<~RUBY)
{}.keys.each(&:bar)
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY
expect_correction(<<~RUBY)
{}.each_key(&:bar)
RUBY
end
it 'registers an offense autocorrects `{}&.keys&.each` to `{}&.each_key` with a symbol proc argument' do
expect_offense(<<~RUBY)
{}&.keys&.each(&:bar)
^^^^^^^^^^ Use `each_key` instead of `keys&.each`.
RUBY
expect_correction(<<~RUBY)
{}&.each_key(&:bar)
RUBY
end
it 'registers an offense autocorrects {}#values.each to {}#each_value with a symbol proc argument' do
expect_offense(<<~RUBY)
{}.values.each(&:bar)
^^^^^^^^^^^ Use `each_value` instead of `values.each`.
RUBY
expect_correction(<<~RUBY)
{}.each_value(&:bar)
RUBY
end
it 'registers an offense autocorrects `{}&.values.each` to `{}&.each_value` with a symbol proc argument' do
expect_offense(<<~RUBY)
{}&.values&.each(&:bar)
^^^^^^^^^^^^ Use `each_value` instead of `values&.each`.
RUBY
expect_correction(<<~RUBY)
{}&.each_value(&:bar)
RUBY
end
it 'does not register an offense for {}#each_key' do
expect_no_offenses('{}.each_key { |k| p k }')
end
it 'does not register an offense for {}#each_value' do
expect_no_offenses('{}.each_value { |v| p v }')
end
end
context 'when receiver is implicit' do
it 'does not register an offense for `keys.each`' do
expect_no_offenses(<<~RUBY)
keys.each { |k| p k }
RUBY
end
it 'does not register an offense for `values.each`' do
expect_no_offenses(<<~RUBY)
values.each { |v| p v }
RUBY
end
it 'does not register an offense for `keys.each` with a symbol proc argument' do
expect_no_offenses(<<~RUBY)
keys.each(&:bar)
RUBY
end
it 'does not register an offense for `values.each` with a symbol proc argument' do
expect_no_offenses(<<~RUBY)
values.each(&:bar)
RUBY
end
it 'does not register an offense for each_key' do
expect_no_offenses('each_key { |k| p k }')
end
it 'does not register an offense for each_value' do
expect_no_offenses('each_value { |v| p v }')
end
end
context "when `AllowedReceivers: ['execute']`" do
let(:cop_config) { { 'AllowedReceivers' => ['execute'] } }
it 'does not register an offense when receiver is `execute` method' do
expect_no_offenses(<<~RUBY)
execute(sql).values.each { |v| p v }
RUBY
end
it 'does not register an offense when receiver is `execute` variable' do
expect_no_offenses(<<~RUBY)
execute = do_something(argument)
execute.values.each { |v| p v }
RUBY
end
it 'does not register an offense when receiver is `execute` method with a symbol proc argument' do
expect_no_offenses(<<~RUBY)
execute(sql).values.each(&:bar)
RUBY
end
it 'registers an offense when receiver is not allowed name' do
expect_offense(<<~RUBY)
do_something(arg).values.each { |v| p v }
^^^^^^^^^^^ Use `each_value` instead of `values.each`.
RUBY
end
end
context "when `AllowedReceivers: ['Thread.current']`" do
let(:cop_config) { { 'AllowedReceivers' => ['Thread.current'] } }
it 'does not register an offense when receiver is `Thread.current` method' do
expect_no_offenses(<<~RUBY)
Thread.current.keys.each { |k| p k }
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/method_call_with_args_parentheses_spec.rb | spec/rubocop/cop/style/method_call_with_args_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MethodCallWithArgsParentheses, :config do
shared_examples 'endless methods' do |omit: false|
context 'endless methods', :ruby30 do
context 'with arguments' do
it 'requires method calls to have parens' do
expect_no_offenses(<<~RUBY)
def x() = foo("bar")
RUBY
end
end
context 'without arguments' do
if omit
it 'registers an offense when there are parens' do
expect_offense(<<~RUBY)
def x() = foo()
^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
def x() = foo#{trailing_whitespace}
RUBY
end
it 'registers an offense for `defs` when there are parens' do
expect_offense(<<~RUBY)
def self.x() = foo()
^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
def self.x() = foo#{trailing_whitespace}
RUBY
end
else
it 'does not register an offense when there are parens' do
expect_no_offenses(<<~RUBY)
def x() = foo()
RUBY
end
it 'does not register an offense for `defs` when there are parens' do
expect_no_offenses(<<~RUBY)
def self.x() = foo()
RUBY
end
end
it 'does not register an offense when there are no parens' do
expect_no_offenses(<<~RUBY)
def x() = foo
RUBY
end
it 'does not register an offense when there are arguments' do
expect_no_offenses(<<~RUBY)
def x() = foo(y)
RUBY
end
it 'does not register an offense for `defs` when there are arguments' do
expect_no_offenses(<<~RUBY)
def self.x() = foo(y)
RUBY
end
end
end
end
context 'when EnforcedStyle is require_parentheses (default)' do
it_behaves_like 'endless methods'
it 'accepts no parens in method call without args' do
expect_no_offenses('top.test')
end
it 'accepts parens in method call with args' do
expect_no_offenses('top.test(a, b)')
end
it 'accepts parens in method call with do-end blocks' do
expect_no_offenses(<<~RUBY)
foo(:arg) do
bar
end
RUBY
end
it 'registers an offense for method call without parens' do
expect_offense(<<~RUBY)
top.test a, b
^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
top.test(a, b)
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense for method call without parens' do
expect_offense(<<~RUBY)
top&.test a, b
^^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
top&.test(a, b)
RUBY
end
end
it 'registers an offense for non-receiver method call without parens' do
expect_offense(<<~RUBY)
def foo
test a, b
^^^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def foo
test(a, b)
end
RUBY
end
it 'registers an offense for methods starting with capital without parens' do
expect_offense(<<~RUBY)
def foo
Test a, b
^^^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def foo
Test(a, b)
end
RUBY
end
it 'does not register an offense for superclass call without parens' do
expect_no_offenses(<<~RUBY)
def foo
super a
end
RUBY
end
it 'registers no offense for superclass call without args' do
expect_no_offenses('super')
end
it 'registers no offense for yield without args' do
expect_no_offenses('yield')
end
it 'registers no offense for superclass call with parens' do
expect_no_offenses('super(a)')
end
it 'registers an offense for yield without parens' do
expect_offense(<<~RUBY)
def foo
yield a
^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def foo
yield(a)
end
RUBY
end
it 'accepts no parens for operators' do
expect_no_offenses('top.test + a')
end
it 'accepts no parens for setter methods' do
expect_no_offenses('top.test = a')
end
it 'accepts no parens for unary operators' do
expect_no_offenses('!test')
end
it 'autocorrects fully parenthesized args by removing space' do
expect_offense(<<~RUBY)
top.eq (1 + 2)
^^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
top.eq(1 + 2)
RUBY
end
it 'autocorrects parenthesized args for local methods by removing space' do
expect_offense(<<~RUBY)
def foo
eq (1 + 2)
^^^^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def foo
eq(1 + 2)
end
RUBY
end
it 'autocorrects call with multiple args by adding braces' do
expect_offense(<<~RUBY)
def foo
eq 1, (2 + 3)
^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
eq 1, 2, 3
^^^^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def foo
eq(1, (2 + 3))
eq(1, 2, 3)
end
RUBY
end
it 'autocorrects partially parenthesized args by adding needed braces' do
expect_offense(<<~RUBY)
top.eq (1 + 2) + 3
^^^^^^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
top.eq((1 + 2) + 3)
RUBY
end
it 'autocorrects calls with multiple args by adding needed braces' do
expect_offense(<<~RUBY)
top.eq (1 + 2), 3
^^^^^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
top.eq((1 + 2), 3)
RUBY
end
it 'autocorrects calls where arg is method call' do
expect_offense(<<~RUBY)
def my_method
foo bar.baz(abc, xyz)
^^^^^^^^^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def my_method
foo(bar.baz(abc, xyz))
end
RUBY
end
it 'autocorrects calls where multiple args are method calls' do
expect_offense(<<~RUBY)
def my_method
foo bar.baz(abc, xyz), foo(baz)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def my_method
foo(bar.baz(abc, xyz), foo(baz))
end
RUBY
end
it 'autocorrects calls where the argument node is a constant' do
expect_offense(<<~RUBY)
def my_method
raise NotImplementedError
^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def my_method
raise(NotImplementedError)
end
RUBY
end
it 'autocorrects calls where the argument node is a number' do
expect_offense(<<~RUBY)
def my_method
sleep 1
^^^^^^^ Use parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def my_method
sleep(1)
end
RUBY
end
context 'with AllowedMethods' do
let(:cop_config) { { 'AllowedMethods' => %w[puts] } }
it 'allow method listed in AllowedMethods' do
expect_no_offenses('puts :test')
end
end
context 'when inspecting macro methods' do
let(:cop_config) { { 'IgnoreMacros' => 'true' } }
context 'in a class body' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Foo
bar :baz
end
RUBY
end
end
context 'in a module body' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
module Foo
bar :baz
end
RUBY
end
end
end
context 'AllowedPatterns' do
let(:cop_config) { { 'AllowedPatterns' => %w[^assert ^refute] } }
it 'ignored methods listed in AllowedPatterns' do
expect_no_offenses('assert 2 == 2')
expect_no_offenses('assert_equal 2, 2')
expect_no_offenses('assert_match /^yes/i, result')
expect_no_offenses('refute 2 == 3')
expect_no_offenses('refute_equal 2, 3')
expect_no_offenses('refute_match /^no/i, result')
end
end
end
context 'when EnforcedStyle is omit_parentheses' do
let(:cop_config) { { 'EnforcedStyle' => 'omit_parentheses' } }
it_behaves_like 'endless methods', omit: true
context 'forwarded arguments in 2.7', :ruby27 do
it 'accepts parens for forwarded arguments' do
expect_no_offenses(<<~RUBY)
def delegated_call(...)
@proxy.call(...)
end
RUBY
end
end
context 'forwarded arguments in 3.0', :ruby30 do
it 'accepts parens for forwarded arguments' do
expect_no_offenses(<<~RUBY)
def method_missing(name, ...)
@proxy.call(name, ...)
end
RUBY
end
end
context 'numbered parameters in 2.7', :ruby27 do
it 'accepts parens for braced numeric block calls' do
expect_no_offenses(<<~RUBY)
numblock.call(:arg) { _1 }
RUBY
end
end
context 'hash value omission in 3.1', :ruby31 do
it 'registers an offense when last argument is a hash value omission' do
expect_offense(<<~RUBY)
foo(bar:, baz:)
^^^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
foo bar:, baz:
RUBY
end
it 'does not register an offense when hash value omission with parentheses and using modifier form' do
expect_no_offenses(<<~RUBY)
do_something(value:) if condition
RUBY
end
it 'registers and corrects an offense when explicit hash value with parentheses and using modifier form' do
expect_offense(<<~RUBY)
do_something(value: value) if condition
^^^^^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
do_something value: value if condition
RUBY
end
it 'does not register an offense when without parentheses call expr follows' do
expect_no_offenses(<<~RUBY)
foo value:
RUBY
end
it 'registers an offense when with parentheses call expr follows' do
# Require hash value omission be enclosed in parentheses to prevent the following issue:
# https://bugs.ruby-lang.org/issues/18396.
expect_offense(<<~RUBY)
foo(value:)
foo(arg)
^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
foo(value:)
foo arg
RUBY
end
it 'registers an offense using assignment with parentheses call expr follows' do
# Require hash value omission be enclosed in parentheses to prevent the following issue:
# https://bugs.ruby-lang.org/issues/18396.
expect_offense(<<~RUBY)
var = foo(value:)
foo(arg)
^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
var = foo(value:)
foo arg
RUBY
end
it 'does not register an offense in conditionals' do
expect_no_offenses(<<~RUBY)
var =
unless object.action(value:, other:)
condition || other_condition
end
RUBY
end
it 'registers an offense in case_match multi-line branches' do
expect_offense(<<~RUBY)
case match
in :pattern1
foo(value:)
^^^^^^^^ Omit parentheses for method calls with arguments.
in :pattern2
bar(value:)
^^^^^^^^ Omit parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
case match
in :pattern1
foo value:
in :pattern2
bar value:
end
RUBY
end
it 'does not register an offense in case_match single-line branches' do
expect_no_offenses(<<~RUBY)
case match
in :pattern1 then foo(value:)
in :pattern2 then bar(value:)
end
RUBY
end
it 'does not register an offense in case single-line branches' do
expect_no_offenses(<<~RUBY)
case match
when /pattern1/ then foo(value:)
when /pattern2/ then bar(value:)
end
RUBY
end
end
context 'anonymous rest arguments in 3.2', :ruby32 do
it 'does not register an offense when method calls to have parens' do
expect_no_offenses(<<~RUBY)
def foo(*)
foo(*)
do_something
end
RUBY
end
end
context 'anonymous keyword rest arguments in 3.2', :ruby32 do
it 'does not register an offense when method calls to have parens' do
expect_no_offenses(<<~RUBY)
def foo(**)
foo(**)
end
RUBY
end
it 'does not register an offense when forwarded keyword argument has additional nodes' do
expect_no_offenses(<<~RUBY)
def foo(**)
foo(name: value, **)
end
RUBY
end
end
it 'registers an offense for parens in method call without args' do
trailing_whitespace = ' '
expect_offense(<<~RUBY)
top.test()
^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
top.test#{trailing_whitespace}
RUBY
end
it 'registers an offense for multi-line method calls' do
expect_offense(<<~RUBY)
test(
^ Omit parentheses for method calls with arguments.
foo: bar
)
RUBY
expect_correction(<<~RUBY)
test \\
foo: bar
RUBY
end
it 'does not register an offense for superclass call with parens' do
expect_no_offenses(<<~RUBY)
def foo
super(a)
end
RUBY
end
it 'registers an offense for yield call with parens' do
expect_offense(<<~RUBY)
def foo
yield(a)
^^^ Omit parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
def foo
yield a
end
RUBY
end
it 'registers an offense for parens in the last chain' do
expect_offense(<<~RUBY)
foo().bar(3).wait(4)
^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
foo().bar(3).wait 4
RUBY
end
it 'registers an offense for parens in do-end blocks' do
expect_offense(<<~RUBY)
foo(:arg) do
^^^^^^ Omit parentheses for method calls with arguments.
bar
end
RUBY
expect_correction(<<~RUBY)
foo :arg do
bar
end
RUBY
end
it 'registers an offense for hashes in keyword values' do
expect_offense(<<~RUBY)
method_call(hash: {foo: :bar})
^^^^^^^^^^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
method_call hash: {foo: :bar}
RUBY
end
it 'registers an offense for %r regex literal as arguments' do
expect_offense(<<~RUBY)
method_call(%r{foo})
^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
method_call %r{foo}
RUBY
end
it 'registers an offense for parens in string interpolation' do
expect_offense(<<~'RUBY')
"#{t('no.parens')}"
^^^^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~'RUBY')
"#{t 'no.parens'}"
RUBY
end
it 'registers an offense in complex conditionals' do
expect_offense(<<~RUBY)
def foo
if cond.present? && verify?(:something)
h.do_with(kw: value)
^^^^^^^^^^^ Omit parentheses for method calls with arguments.
elsif cond.present? || verify?(:something_else)
h.do_with(kw: value)
^^^^^^^^^^^ Omit parentheses for method calls with arguments.
elsif whatevs?
h.do_with(kw: value)
^^^^^^^^^^^ Omit parentheses for method calls with arguments.
end
end
RUBY
expect_correction(<<~RUBY)
def foo
if cond.present? && verify?(:something)
h.do_with kw: value
elsif cond.present? || verify?(:something_else)
h.do_with kw: value
elsif whatevs?
h.do_with kw: value
end
end
RUBY
end
it 'registers an offense in assignments' do
expect_offense(<<~RUBY)
foo = A::B.new(c)
^^^ Omit parentheses for method calls with arguments.
bar.foo = A::B.new(c)
^^^ Omit parentheses for method calls with arguments.
bar.foo(42).quux = A::B.new(c)
^^^ Omit parentheses for method calls with arguments.
bar.foo(42).quux &&= A::B.new(c)
^^^ Omit parentheses for method calls with arguments.
bar.foo(42).quux += A::B.new(c)
^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
foo = A::B.new c
bar.foo = A::B.new c
bar.foo(42).quux = A::B.new c
bar.foo(42).quux &&= A::B.new c
bar.foo(42).quux += A::B.new c
RUBY
end
it 'registers an offense for camel-case methods with arguments' do
expect_offense(<<~RUBY)
Array(:arg)
^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
Array :arg
RUBY
end
it 'registers an offense in multi-line inheritance' do
expect_offense(<<~RUBY)
class Point < Struct.new(:x, :y)
^^^^^^^^ Omit parentheses for method calls with arguments.
end
RUBY
expect_correction(<<~RUBY)
class Point < Struct.new :x, :y
end
RUBY
end
it 'registers an offense in calls inside braced blocks' do
expect_offense(<<~RUBY)
client.images(page: page) { |resource| Image.new(resource) }
^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
client.images(page: page) { |resource| Image.new resource }
RUBY
end
it 'registers an offense in calls inside braced numblocks', :ruby27 do
expect_offense(<<~RUBY)
client.images(page: page) { Image.new(_1) }
^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
client.images(page: page) { Image.new _1 }
RUBY
end
it 'accepts parenthesized method calls before constant resolution' do
expect_no_offenses(<<~RUBY)
do_something(arg)::CONST
RUBY
end
it 'accepts parens in single-line inheritance' do
expect_no_offenses(<<-RUBY)
class Point < Struct.new(:x, :y); end
RUBY
end
it 'accepts no parens in method call without args' do
expect_no_offenses('top.test')
end
it 'accepts no parens in method call with args' do
expect_no_offenses('top.test 1, 2, foo: bar')
end
it 'accepts parens in default argument value calls' do
expect_no_offenses(<<~RUBY)
def regular(arg = default(42))
nil
end
def seatle_style arg = default(42)
nil
end
RUBY
end
it 'accepts parens in default keyword argument value calls' do
expect_no_offenses(<<~RUBY)
def regular(arg: default(42))
nil
end
def seatle_style arg: default(42)
nil
end
RUBY
end
it 'accepts parens in method args' do
expect_no_offenses('top.test 1, 2, foo: bar(3)')
end
it 'accepts parens in nested method args' do
expect_no_offenses('top.test 1, 2, foo: [bar(3)]')
end
it 'accepts parens in calls with hash as arg' do
expect_no_offenses('top.test({foo: :bar})')
expect_no_offenses('top.test({foo: :bar}.merge(baz: :maz))')
expect_no_offenses('top.test(:first, {foo: :bar}.merge(baz: :maz))')
end
it 'accepts special lambda call syntax' do
expect_no_offenses('thing.()')
end
it 'accepts parens in chained method calls' do
expect_no_offenses('foo().bar(3).wait(4).it')
end
it 'accepts parens in chaining with operators' do
expect_no_offenses('foo().bar(3).wait(4) + 4')
end
it 'accepts parens in blocks with braces' do
expect_no_offenses('foo(1) { 2 }')
end
it 'accepts parens around argument values with blocks' do
expect_no_offenses(<<~RUBY)
Foo::Bar.find(pending.things.map { |t| t['code'] }.first)
RUBY
end
it 'accepts parens around argument values with numblocks', :ruby27 do
expect_no_offenses(<<~RUBY)
Foo::Bar.find(pending.things.map { _1['code'] })
RUBY
end
it 'accepts parens in array literal calls with blocks' do
expect_no_offenses(<<~RUBY)
[
foo.bar.quux(:args) do
pass
end,
]
RUBY
end
it 'accepts parens in array literal calls with numblocks' do
expect_no_offenses(<<~RUBY)
[
foo.bar.quux(:args) do
pass _1
end,
]
RUBY
end
it 'accepts parens in calls with logical operators' do
expect_no_offenses('foo(a) && bar(b)')
expect_no_offenses('foo(a) || bar(b)')
expect_no_offenses(<<~RUBY)
foo(a) || bar(b) do
pass
end
RUBY
end
it 'accepts parens in calls with logical operator and numblock' do
expect_no_offenses(<<~RUBY)
foo(a) || bar(b) do
pass _1
end
RUBY
end
it 'accepts parens in calls with args with logical operators' do
expect_no_offenses('foo(a, b || c)')
expect_no_offenses('foo a, b || c')
expect_no_offenses('foo a, b(1) || c(2, d(3))')
end
it 'accepts parens in literals with unary operators as first argument' do
expect_no_offenses('foo(-1)')
expect_no_offenses('foo(+1)')
expect_no_offenses('foo(+"")')
expect_no_offenses('foo(-"")')
expect_no_offenses('foo(-1 + 3i)')
expect_no_offenses('foo(+1 + 3i)')
expect_no_offenses('foo(-3i)')
expect_no_offenses('foo(+3i)')
expect_no_offenses('foo(-1.3i)')
expect_no_offenses('foo(+1.3i)')
end
it 'accepts parens in args splat' do
expect_no_offenses('foo(*args)')
expect_no_offenses('foo *args')
expect_no_offenses('foo(**kwargs)')
expect_no_offenses('foo **kwargs')
end
it 'accepts parens in slash regexp literal as argument' do
expect_no_offenses('foo(/regexp/)')
end
it 'accepts parens in argument calls with braced blocks' do
expect_no_offenses('foo(bar(:arg) { 42 })')
end
it 'accepts parens in implicit #to_proc' do
expect_no_offenses('foo(&block)')
expect_no_offenses('foo &block')
end
it 'accepts parens in yield argument method calls' do
expect_no_offenses('yield File.basepath(path)')
expect_no_offenses('yield path, File.basepath(path)')
end
it 'accepts parens in super calls with braced blocks' do
expect_no_offenses('super(foo(bar)) { yield }')
end
it 'accepts parens in super without args' do
expect_no_offenses('super()')
end
it 'accepts parens in super method calls as arguments' do
expect_no_offenses('super foo(bar)')
end
it 'accepts parens in camel case method without args' do
expect_no_offenses('Array()')
end
it 'accepts parens in ternary condition calls' do
expect_no_offenses(<<-RUBY)
foo.include?(bar) ? bar : quux
RUBY
end
it 'accepts parens in args with ternary conditions' do
expect_no_offenses(<<-RUBY)
foo.include?(bar ? baz : quux)
RUBY
end
it 'accepts parens in splat calls' do
expect_no_offenses(<<-RUBY)
foo(*bar(args))
foo(**quux(args))
RUBY
end
it 'accepts parens in block passing calls' do
expect_no_offenses(<<-RUBY)
foo(&method(:args))
RUBY
end
it 'accepts parens in range literals' do
expect_no_offenses(<<-RUBY)
1..limit(n)
1...limit(n)
RUBY
end
context 'range literals' do
it 'accepts parens when no end node and last argument' do
expect_no_offenses(<<~RUBY)
foo(2..)
foo(1, 2...)
RUBY
end
it 'registers an offense no end node and not last argument' do
expect_offense(<<~RUBY)
foo(2.., 1)
^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
foo 2.., 1
RUBY
end
it 'accepts parens when no begin node and first argument' do
expect_no_offenses(<<~RUBY)
foo(..2, 1)
foo(...2)
RUBY
end
it 'registers an offense no begin node and not first argument' do
expect_offense(<<~RUBY)
foo(1, ..2)
^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
foo 1, ..2
RUBY
end
end
it 'accepts parens in assignment in conditions' do
expect_no_offenses(<<-RUBY)
case response = get("server/list")
when server = response.take(1)
if @size ||= server.take(:size)
pass
elsif @@image &&= server.take(:image)
pass
end
end
RUBY
end
it 'accepts parens in `when` clause is used to pass an argument' do
expect_no_offenses(<<-RUBY)
case condition
when do_something(arg)
end
RUBY
end
it 'autocorrects single-line calls' do
expect_offense(<<~RUBY)
top.test(1, 2, foo: bar(3))
^^^^^^^^^^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
top.test 1, 2, foo: bar(3)
RUBY
end
it 'autocorrects multi-line calls with trailing whitespace' do
trailing_whitespace = ' '
expect_offense(<<~RUBY)
foo(#{trailing_whitespace}
^^ Omit parentheses for method calls with arguments.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
foo \\
bar: 3
RUBY
end
it 'autocorrects complex multi-line calls' do
expect_offense(<<~RUBY)
foo(arg,
^^^^^ Omit parentheses for method calls with arguments.
option: true
)
RUBY
expect_correction(<<~RUBY)
foo arg,
option: true
RUBY
end
it 'accepts parens in chaining with safe operators' do
expect_no_offenses('Something.find(criteria: given)&.field')
end
it 'accepts parens in operator method calls' do
expect_no_offenses(<<~RUBY)
data.[](value)
data&.[](value)
string.<<(even_more_string)
ruby.==(good)
ruby&.===(better)
RUBY
end
# Ruby 2.7's one-line `in` pattern node type is `match-pattern`.
it 'accepts parens in one-line `in` pattern matching', :ruby27 do
expect_no_offenses(<<~RUBY)
execute(query) in {elapsed:, sql_count:}
RUBY
end
# Ruby 3.0's one-line `in` pattern node type is `match-pattern-p`.
it 'accepts parens in one-line `in` pattern matching', :ruby30 do
expect_no_offenses(<<~RUBY)
execute(query) in {elapsed:, sql_count:}
RUBY
end
# Ruby 3.0's one-line `=>` pattern node type is `match-pattern`.
it 'accepts parens in one-line `=>` pattern matching', :ruby30 do
expect_no_offenses(<<~RUBY)
execute(query) => {elapsed:, sql_count:}
RUBY
end
context 'allowing parenthesis in chaining' do
let(:cop_config) do
{
'EnforcedStyle' => 'omit_parentheses',
'AllowParenthesesInChaining' => true
}
end
it 'registers an offense for single-line chaining without previous parens' do
expect_offense(<<~RUBY)
Rails.convoluted.example.logger.error("something")
^^^^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
Rails.convoluted.example.logger.error "something"
RUBY
end
it 'registers an offense for multi-line chaining without previous parens' do
expect_offense(<<~RUBY)
Rails
.convoluted
.example
.logger
.error("something")
^^^^^^^^^^^^^ Omit parentheses for method calls with arguments.
RUBY
expect_correction(<<~RUBY)
Rails
.convoluted
.example
.logger
.error "something"
RUBY
end
it 'accepts no parens in the last call if previous calls with parens' do
expect_no_offenses('foo().bar(3).wait 4')
end
it 'accepts parens when previously chained sends have numblocks', :ruby27 do
expect_no_offenses(<<~RUBY)
[a, b].map { _1.call 'something' }.uniq.join(' - ')
RUBY
end
it 'accepts parens in the last call if any previous calls with parentheses' do
expect_no_offenses('foo().bar(3).quux.wait(4)')
end
it 'accepts parens in empty hashes for arguments calls' do
expect_no_offenses(<<~RUBY)
params.should eq({})
RUBY
end
end
context 'allowing parens in multi-line calls' do
let(:cop_config) do
{
'EnforcedStyle' => 'omit_parentheses',
'AllowParenthesesInMultilineCall' => true
}
end
it 'accepts parens for multi-line calls' do
expect_no_offenses(<<~RUBY)
test(
foo: bar
)
RUBY
end
it 'accepts parens in argument calls with blocks' do
expect_no_offenses(<<~RUBY)
foo(
bar.new(quux) do
pass
end
)
RUBY
end
it 'accepts parens in argument calls with numblocks' do
expect_no_offenses(<<~RUBY)
foo(
bar.new(quux) do
pass _1
end
)
RUBY
end
it 'accepts parens in argument csend with blocks' do
expect_no_offenses(<<~RUBY)
foo(
bar&.new(quux) do
pass
end
)
RUBY
end
it 'accepts parens in super argument call with blocks' do
expect_no_offenses(<<~RUBY)
super(
bar.new(quux) do
pass
end
)
RUBY
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/constant_visibility_spec.rb | spec/rubocop/cop/style/constant_visibility_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ConstantVisibility, :config do
context 'when defining a constant in a class' do
context 'with a single-statement body' do
it 'registers an offense when not using a visibility declaration' do
expect_offense(<<~RUBY)
class Foo
BAR = 42
^^^^^^^^ Explicitly make `BAR` public or private using either `#public_constant` or `#private_constant`.
end
RUBY
end
it 'registers an offense when no arguments are used in the visibility declaration' do
expect_offense(<<~RUBY)
class Foo
BAR = 42
^^^^^^^^ Explicitly make `BAR` public or private using either `#public_constant` or `#private_constant`.
private_constant
end
RUBY
end
end
context 'with a multi-statement body' do
it 'registers an offense when not using a visibility declaration' do
expect_offense(<<~RUBY)
class Foo
include Bar
BAR = 42
^^^^^^^^ Explicitly make `BAR` public or private using either `#public_constant` or `#private_constant`.
end
RUBY
end
it 'registers an offense when there is no matching visibility declaration' do
expect_offense(<<~RUBY)
class Foo
include Bar
BAR = 42
^^^^^^^^ Explicitly make `BAR` public or private using either `#public_constant` or `#private_constant`.
private_constant :FOO
end
RUBY
end
it 'does not register an offense when using a visibility declaration' do
expect_no_offenses(<<~RUBY)
class Foo
BAR = 42
private_constant :BAR
end
RUBY
end
end
end
context 'when defining a constant in a module' do
it 'registers an offense when not using a visibility declaration' do
expect_offense(<<~RUBY)
module Foo
BAR = 42
^^^^^^^^ Explicitly make `BAR` public or private using either `#public_constant` or `#private_constant`.
end
RUBY
end
it 'does not register an offense when using a visibility declaration' do
expect_no_offenses(<<~RUBY)
class Foo
BAR = 42
public_constant :BAR
end
RUBY
end
it 'does not register an offense when multiple constants are specified in the visibility declaration' do
expect_no_offenses(<<~RUBY)
class Foo
BAR = 42
BAZ = 43
public_constant :BAR, :BAZ
end
RUBY
end
end
it 'registers an offense for module definitions' do
expect_offense(<<~RUBY)
module Foo
MyClass = Class.new()
^^^^^^^^^^^^^^^^^^^^^ Explicitly make `MyClass` public or private using either `#public_constant` or `#private_constant`.
end
RUBY
end
context 'IgnoreModules' do
let(:cop_config) { { 'IgnoreModules' => true } }
it 'does not register an offense for class definitions' do
expect_no_offenses(<<~RUBY)
class Foo
SomeClass = Class.new()
SomeModule = Module.new()
SomeStruct = Struct.new()
end
RUBY
end
it 'registers an offense for constants' do
expect_offense(<<~RUBY)
module Foo
BAR = 42
^^^^^^^^ Explicitly make `BAR` public or private using either `#public_constant` or `#private_constant`.
end
RUBY
end
end
it 'does not register an offense when passing a string to the visibility declaration' do
expect_no_offenses(<<~RUBY)
class Foo
BAR = 42
private_constant "BAR"
end
RUBY
end
it 'registers an offense when passing an array with multiple elements to the visibility declaration' do
expect_offense(<<~RUBY)
class Foo
BAR = 42
^^^^^^^^ Explicitly make `BAR` public or private using either `#public_constant` or `#private_constant`.
BAZ = 43
^^^^^^^^ Explicitly make `BAZ` public or private using either `#public_constant` or `#private_constant`.
private_constant ["BAR", "BAZ"]
end
RUBY
end
it 'does not register an offense when passing a splatted array with multiple elements to the visibility declaration' do
expect_no_offenses(<<~RUBY)
class Foo
BAR = 42
BAZ = 43
private_constant *["BAR", "BAZ"]
end
RUBY
end
it 'does not register an offense in the top level scope' do
expect_no_offenses(<<~RUBY)
BAR = 42
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/dir_spec.rb | spec/rubocop/cop/style/dir_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Dir, :config do
context 'when using `#expand_path` and `#dirname`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
File.expand_path(File.dirname(__FILE__))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `__dir__` to get an absolute path to the current file's directory.
RUBY
expect_correction(<<~RUBY)
__dir__
RUBY
end
it 'registers an offense with ::File' do
expect_offense(<<~RUBY)
::File.expand_path(::File.dirname(__FILE__))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `__dir__` to get an absolute path to the current file's directory.
RUBY
expect_correction(<<~RUBY)
__dir__
RUBY
end
end
context 'when using `#dirname` and `#realpath`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
File.dirname(File.realpath(__FILE__))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `__dir__` to get an absolute path to the current file's directory.
RUBY
expect_correction(<<~RUBY)
__dir__
RUBY
end
it 'registers an offense with ::File' do
expect_offense(<<~RUBY)
::File.dirname(::File.realpath(__FILE__))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `__dir__` to get an absolute path to the current file's directory.
RUBY
expect_correction(<<~RUBY)
__dir__
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/stderr_puts_spec.rb | spec/rubocop/cop/style/stderr_puts_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StderrPuts, :config do
it "registers an offense when using `$stderr.puts('hello')`" do
expect_offense(<<~RUBY)
$stderr.puts('hello')
^^^^^^^^^^^^ Use `warn` instead of `$stderr.puts` to allow such output to be disabled.
RUBY
expect_correction(<<~RUBY)
warn('hello')
RUBY
end
it 'registers no offense when using `$stderr.puts` with no arguments' do
expect_no_offenses(<<~RUBY)
$stderr.puts
RUBY
end
it "registers an offense when using `STDERR.puts('hello')`" do
expect_offense(<<~RUBY)
STDERR.puts('hello')
^^^^^^^^^^^ Use `warn` instead of `STDERR.puts` to allow such output to be disabled.
RUBY
expect_correction(<<~RUBY)
warn('hello')
RUBY
end
it "registers an offense when using `::STDERR.puts('hello')`" do
expect_offense(<<~RUBY)
::STDERR.puts('hello')
^^^^^^^^^^^^^ Use `warn` instead of `::STDERR.puts` to allow such output to be disabled.
RUBY
expect_correction(<<~RUBY)
warn('hello')
RUBY
end
it 'registers no offense when using `STDERR.puts` with no arguments' do
expect_no_offenses(<<~RUBY)
STDERR.puts
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/string_literals_spec.rb | spec/rubocop/cop/style/string_literals_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StringLiterals, :config do
context 'configured with single quotes preferred' do
let(:cop_config) { { 'EnforcedStyle' => 'single_quotes' } }
it 'registers an offense for double quotes when single quotes suffice' do
expect_offense(<<~'RUBY')
s = "abc"
^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
x = "a\\b"
^^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
y ="\\b"
^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
z = "a\\"
^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
t = "{\"[\\\"*\\\"]\""
^^^^^^^^^^^^^^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
RUBY
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'double_quotes')
expect_correction(<<~'RUBY')
s = 'abc'
x = 'a\\b'
y ='\\b'
z = 'a\\'
t = '{"[\"*\"]"'
RUBY
end
it 'registers an offense for correct + opposite' do
expect_offense(<<~RUBY)
s = "abc"
^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
x = 'abc'
RUBY
expect_correction(<<~RUBY)
s = 'abc'
x = 'abc'
RUBY
end
it 'accepts single quotes' do
expect_no_offenses("a = 'x'")
end
it 'accepts single quotes in interpolation' do
expect_no_offenses(%q("hello#{hash['there']}"))
end
it 'accepts %q and %Q quotes' do
expect_no_offenses('a = %q(x) + %Q[x]')
end
it 'accepts % quotes' do
expect_no_offenses('a = %(x)')
end
it 'accepts heredocs' do
expect_no_offenses(<<~RUBY)
execute <<-SQL
SELECT name from users
SQL
RUBY
end
it 'accepts double quotes when new line is used' do
expect_no_offenses('"\n"')
end
it 'accepts double quotes when interpolating & quotes in multiple lines' do
expect_no_offenses(<<~'RUBY')
"#{encode_severity}:#{sprintf('%3d', line_number)}: #{m}"
RUBY
end
it 'accepts double quotes when single quotes are used' do
expect_no_offenses('"\'"')
end
it 'accepts double quotes when interpolating an instance variable' do
expect_no_offenses('"#@test"')
end
it 'accepts double quotes when interpolating a global variable' do
expect_no_offenses('"#$test"')
end
it 'accepts double quotes when interpolating a class variable' do
expect_no_offenses('"#@@test"')
end
it 'accepts double quotes when control characters are used' do
expect_no_offenses('"\e"')
end
it 'accepts double quotes when unicode control sequence is used' do
expect_no_offenses('"Espa\u00f1a"')
end
it 'accepts double quotes at the start of regexp literals' do
expect_no_offenses('s = /"((?:[^\\"]|\\.)*)"/')
end
it 'accepts double quotes with some other special symbols' do
# "Substitutions in double-quoted strings"
# http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html
expect_no_offenses(<<~'RUBY')
g = "\xf9"
copyright = "\u00A9"
RUBY
end
it 'accepts " in a %w' do
expect_no_offenses('%w(")')
end
it 'accepts \\\\\n in a string' do # this would be: "\\\n"
expect_no_offenses('"foo \\\\\n bar"')
end
it 'accepts double quotes in interpolation' do
expect_no_offenses("\"\#{\"A\"}\"")
end
it 'detects unneeded double quotes within concatenated string' do
expect_offense(<<~'RUBY')
"#{x}" \
"y"
^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~'RUBY')
"#{x}" \
'y'
RUBY
end
it 'can handle a built-in constant parsed as string' do
# Parser will produce str nodes for constants such as __FILE__.
expect_no_offenses(<<~RUBY)
if __FILE__ == $PROGRAM_NAME
end
RUBY
end
it 'can handle character literals' do
expect_no_offenses('a = ?/')
end
it 'registers an offense for "\""' do
expect_offense(<<~'RUBY')
"\""
^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~RUBY)
'"'
RUBY
end
it 'registers an offense for "\\"' do
expect_offense(<<~'RUBY')
"\\"
^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~'RUBY')
'\\'
RUBY
end
it 'registers an offense for words with non-ascii chars' do
expect_offense(<<~RUBY)
"España"
^^^^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~RUBY)
'España'
RUBY
end
it 'does not register an offense for words with non-ascii chars and other control sequences' do
expect_no_offenses('"España\n"')
end
end
context 'configured with double quotes preferred' do
let(:cop_config) { { 'EnforcedStyle' => 'double_quotes' } }
it 'registers an offense for single quotes when double quotes would be equivalent' do
expect_offense(<<~RUBY)
s = 'abc'
^^^^^ Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'single_quotes')
expect_correction(<<~RUBY)
s = "abc"
RUBY
end
it 'registers an offense for opposite + correct' do
expect_offense(<<~RUBY)
s = "abc"
x = 'abc'
^^^^^ Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
s = "abc"
x = "abc"
RUBY
end
it 'registers an offense for escaped single quote in single quotes' do
expect_offense(<<~'RUBY')
'\''
^^^^ Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
'\\'
^^^^ Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect_correction(<<~'RUBY')
"'"
"\\"
RUBY
end
it 'does not accept multiple escaped single quotes in single quotes' do
expect_offense(<<~'RUBY')
'This \'string\' has \'multiple\' escaped quotes'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect_correction(<<~RUBY)
"This 'string' has 'multiple' escaped quotes"
RUBY
end
it 'accepts double quotes' do
expect_no_offenses('a = "x"')
end
it 'accepts single quotes in interpolation' do
expect_no_offenses(%q("hello#{hash['there']}"))
end
it 'accepts %q and %Q quotes' do
expect_no_offenses('a = %q(x) + %Q[x]')
end
it 'accepts % quotes' do
expect_no_offenses('a = %(x)')
end
it 'accepts single quoted string with backslash' do
expect_no_offenses(<<~'RUBY')
'\,'
'100\%'
'(\)'
RUBY
end
it 'accepts heredocs' do
expect_no_offenses(<<~RUBY)
execute <<-SQL
SELECT name from users
SQL
RUBY
end
it 'accepts single quotes in string with escaped non-\' character' do
expect_no_offenses(%q('\n'))
end
it 'accepts escaped single quote in string with escaped non-\' character' do
expect_no_offenses(%q('\'\n'))
end
it 'accepts single quotes when they are needed' do
expect_no_offenses(<<~'RUBY')
a = '\n'
b = '"'
c = '#{x}'
d = '#@x'
e = '#$x'
f = '\s'
g = '\z'
RUBY
end
it 'flags single quotes with plain # (not #@var or #{interpolation} or #$global' do
expect_offense(<<~RUBY)
a = 'blah #'
^^^^^^^^ Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect_correction(<<~RUBY)
a = "blah #"
RUBY
end
it 'accepts single quotes at the start of regexp literals' do
expect_no_offenses("s = /'((?:[^\\']|\\.)*)'/")
end
it "accepts ' in a %w" do
expect_no_offenses("%w(')")
end
it 'can handle a built-in constant parsed as string' do
# Parser will produce str nodes for constants such as __FILE__.
expect_no_offenses(<<~RUBY)
if __FILE__ == $PROGRAM_NAME
end
RUBY
end
end
context 'when configured with a bad value' do
let(:cop_config) { { 'EnforcedStyle' => 'other' } }
it 'fails' do
expect { expect_no_offenses('a = "b"') }.to raise_error(RuntimeError)
end
end
context 'when ConsistentQuotesInMultiline is true' do
context 'and EnforcedStyle is single_quotes' do
let(:cop_config) do
{
'ConsistentQuotesInMultiline' => true,
'EnforcedStyle' => 'single_quotes'
}
end
it 'registers an offense for strings with line breaks in them' do
expect_offense(<<~RUBY)
"--
^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
SELECT *
LEFT JOIN X on Y
FROM Models"
RUBY
expect_no_corrections
end
it 'accepts continued strings using all single quotes' do
expect_no_offenses(<<~'RUBY')
'abc' \
'def'
RUBY
end
it 'registers an offense for mixed quote styles in a continued string' do
expect_offense(<<~'RUBY')
'abc' \
^^^^^^^ Inconsistent quote style.
"def"
RUBY
expect_no_corrections
end
it 'registers an offense for unneeded double quotes in continuation' do
expect_offense(<<~'RUBY')
"abc" \
^^^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols.
"def"
RUBY
expect_no_corrections
end
it "doesn't register offense for double quotes with interpolation" do
expect_no_offenses(<<~'RUBY')
"abc" \
"def#{1}"
RUBY
end
it "doesn't register offense for double quotes with embedded single" do
expect_no_offenses(<<~'RUBY')
"abc'" \
"def"
RUBY
end
it 'accepts for double quotes with an escaped special character' do
expect_no_offenses(<<~'RUBY')
"abc\t" \
"def"
RUBY
end
it 'accepts for double quotes with an escaped normal character' do
expect_no_offenses(<<~'RUBY')
"abc\!" \
"def"
RUBY
end
it "doesn't choke on heredocs with inconsistent indentation" do
expect_no_offenses(<<~RUBY)
<<-QUERY_STRING
DEFINE
BLAH
QUERY_STRING
RUBY
end
end
context 'and EnforcedStyle is double_quotes' do
let(:cop_config) do
{
'ConsistentQuotesInMultiline' => true,
'EnforcedStyle' => 'double_quotes'
}
end
it 'accepts continued strings using all double quotes' do
expect_no_offenses(<<~'RUBY')
"abc" \
"def"
RUBY
end
it 'registers an offense for mixed quote styles in a continued string' do
expect_offense(<<~'RUBY')
'abc' \
^^^^^^^ Inconsistent quote style.
"def"
RUBY
expect_no_corrections
end
it 'registers an offense for unneeded single quotes in continuation' do
expect_offense(<<~'RUBY')
'abs' \
^^^^^^^ Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
'def'
RUBY
expect_no_corrections
end
it "doesn't register offense for single quotes with embedded double" do
expect_no_offenses(<<~'RUBY')
'abc"' \
'def'
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/hash_fetch_chain_spec.rb | spec/rubocop/cop/style/hash_fetch_chain_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashFetchChain, :config do
context 'ruby >= 2.3' do
context 'with chained `fetch` methods' do
shared_examples 'fetch chain' do |argument|
context "when the 2nd argument is `#{argument}`" do
it 'does not register an offense when not chained' do
expect_no_offenses(<<~RUBY)
hash.fetch('foo', #{argument})
RUBY
end
it 'registers an offense and corrects when the first argument is a string' do
expect_offense(<<~RUBY, argument: argument)
hash.fetch('foo', %{argument})&.fetch('bar', nil)
^^^^^^^^^^^^^^{argument}^^^^^^^^^^^^^^^^^^^^ Use `dig('foo', 'bar')` instead.
RUBY
expect_correction(<<~RUBY)
hash.dig('foo', 'bar')
RUBY
end
it 'registers an offense and corrects when the first argument is a symbol' do
expect_offense(<<~RUBY, argument: argument)
hash.fetch(:foo, %{argument})&.fetch(:bar, nil)
^^^^^^^^^^^^^{argument}^^^^^^^^^^^^^^^^^^^ Use `dig(:foo, :bar)` instead.
RUBY
expect_correction(<<~RUBY)
hash.dig(:foo, :bar)
RUBY
end
it 'registers an offense and corrects for `send` arguments' do
expect_offense(<<~RUBY, argument: argument)
hash.fetch(foo, %{argument})&.fetch(bar, nil)
^^^^^^^^^^^^{argument}^^^^^^^^^^^^^^^^^^ Use `dig(foo, bar)` instead.
RUBY
expect_correction(<<~RUBY)
hash.dig(foo, bar)
RUBY
end
it 'registers an offense and corrects for mixed arguments' do
expect_offense(<<~RUBY, argument: argument)
hash.fetch('foo', %{argument})&.fetch(:bar, %{argument})&.fetch(baz, nil)
^^^^^^^^^^^^^^{argument}^^^^^^^^^^^^^^^^{argument}^^^^^^^^^^^^^^^^^^ Use `dig('foo', :bar, baz)` instead.
RUBY
expect_correction(<<~RUBY)
hash.dig('foo', :bar, baz)
RUBY
end
it 'registers an offense and corrects with safe navigation' do
expect_offense(<<~RUBY, argument: argument)
hash&.fetch('foo', %{argument})&.fetch('bar', nil)
^^^^^^^^^^^^^^{argument}^^^^^^^^^^^^^^^^^^^^ Use `dig('foo', 'bar')` instead.
RUBY
expect_correction(<<~RUBY)
hash&.dig('foo', 'bar')
RUBY
end
it 'registers an offense and corrects when chained onto other methods' do
expect_offense(<<~RUBY, argument: argument)
x.hash.fetch('foo', %{argument})&.fetch('bar', nil)
^^^^^^^^^^^^^^{argument}^^^^^^^^^^^^^^^^^^^^ Use `dig('foo', 'bar')` instead.
RUBY
expect_correction(<<~RUBY)
x.hash.dig('foo', 'bar')
RUBY
end
end
end
context 'when there is only 1 argument' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
hash.fetch('foo').fetch('bar')
RUBY
end
end
context 'when a block is given to `fetch`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
hash.fetch('foo') { :default }.fetch('bar') { :default }
RUBY
end
end
context 'when no arguments are given to `fetch`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
hash.fetch
RUBY
end
end
context 'when the 2nd argument is not `nil` or `{}`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
hash.fetch('foo', bar).fetch('baz', quux)
RUBY
end
end
context 'when the chain ends with a non-nil value' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
hash.fetch('foo', {}).fetch('bar', {})
RUBY
end
end
it_behaves_like 'fetch chain', 'nil'
it_behaves_like 'fetch chain', '{}'
it_behaves_like 'fetch chain', 'Hash.new'
it_behaves_like 'fetch chain', '::Hash.new'
end
context 'when split on multiple lines' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
hash
.fetch('foo', nil)
^^^^^^^^^^^^^^^^^ Use `dig('foo', 'bar')` instead.
.fetch('bar', nil)
RUBY
expect_correction(<<~RUBY)
hash
.dig('foo', 'bar')
RUBY
end
end
end
context 'ruby 2.2', :ruby22, unsupported_on: :prism do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
hash.fetch('foo', {}).fetch('bar', nil)
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_method_spec.rb | spec/rubocop/cop/style/documentation_method_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DocumentationMethod, :config do
let(:require_for_non_public_methods) { false }
let(:config) do
RuboCop::Config.new(
'Style/CommentAnnotation' => {
'Keywords' => %w[TODO FIXME OPTIMIZE HACK REVIEW]
},
'Style/DocumentationMethod' => {
'RequireForNonPublicMethods' => require_for_non_public_methods
}
)
end
context 'when declaring methods outside a class' do
context 'without documentation comment' do
context 'when method is public' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def foo
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
RUBY
end
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
def method; end
^^^^^^^^^^^^^^^ Missing method documentation comment.
RUBY
end
it 'registers an offense when method is public, but there were private methods before' do
expect_offense(<<~RUBY)
class Foo
private
def baz
end
public
def foo
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
end
RUBY
end
end
context 'when `initialize` method' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def initialize
end
RUBY
end
end
context 'when method is private' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
private
def foo
puts 'bar'
end
RUBY
end
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
private
def foo; end
RUBY
end
it 'does not register an offense with inline `private`' do
expect_no_offenses(<<~RUBY)
private def foo
puts 'bar'
end
RUBY
end
it 'does not register an offense with inline `private` and `end`' do
expect_no_offenses('private def method; end')
end
it 'does not register an offense with inline `private_class_method`' do
expect_no_offenses(<<~RUBY)
private_class_method def self.foo
puts 'bar'
end
RUBY
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
private
def foo
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
RUBY
end
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
private
def foo; end
^^^^^^^^^^^^ Missing method documentation comment.
RUBY
end
it 'registers an offense with inline `private`' do
expect_offense(<<~RUBY)
private def foo
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
RUBY
end
it 'registers an offense with inline `private` and `end`' do
expect_offense(<<~RUBY)
private def method; end
^^^^^^^^^^^^^^^ Missing method documentation comment.
RUBY
end
it 'registers an offense with inline `private_class_method`' do
expect_offense(<<~RUBY)
private_class_method def self.foo
^^^^^^^^^^^^ Missing method documentation comment.
puts 'bar'
end
RUBY
end
end
end
context 'when method is protected' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
protected
def foo
puts 'bar'
end
RUBY
end
it 'does not register an offense with inline `protected`' do
expect_no_offenses(<<~RUBY)
protected def foo
puts 'bar'
end
RUBY
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
protected
def foo
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
RUBY
end
it 'registers an offense with inline `protected`' do
expect_offense(<<~RUBY)
protected def foo
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
RUBY
end
end
end
end
context 'with documentation comment' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
# Documentation
def foo
puts 'bar'
end
RUBY
end
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
# Documentation
def foo; end
RUBY
end
end
context 'with both public and private methods' do
context 'when the public method has no documentation' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def foo
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
private
def baz
puts 'bar'
end
RUBY
end
end
context 'when the public method has documentation' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
# Documentation
def foo
puts 'bar'
end
private
def baz
puts 'bar'
end
RUBY
end
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
# Documentation
def foo
puts 'bar'
end
private
def baz
^^^^^^^ Missing method documentation comment.
puts 'bar'
end
RUBY
end
end
end
context 'when declaring methods in a class' do
context 'without documentation comment' do
context 'when method is public' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
class Foo
def method; end
^^^^^^^^^^^^^^^ Missing method documentation comment.
end
RUBY
end
end
context 'when method is private' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Foo
private
def bar
puts 'baz'
end
end
RUBY
end
it 'does not register an offense with inline `private`' do
expect_no_offenses(<<~RUBY)
class Foo
private def bar
puts 'baz'
end
end
RUBY
end
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
class Foo
private
def bar; end
end
RUBY
end
it 'does not register an offense with inline `private` and `end`' do
expect_no_offenses(<<~RUBY)
class Foo
private def bar; end
end
RUBY
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo
private
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
it 'registers an offense with inline `private`' do
expect_offense(<<~RUBY)
class Foo
private def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
class Foo
private
def bar; end
^^^^^^^^^^^^ Missing method documentation comment.
end
RUBY
end
it 'registers an offense with inline `private` and `end`' do
expect_offense(<<~RUBY)
class Foo
private def bar; end
^^^^^^^^^^^^ Missing method documentation comment.
end
RUBY
end
end
end
end
context 'with documentation comment' do
context 'when method is public' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Foo
# Documentation
def bar
puts 'baz'
end
end
RUBY
end
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
class Foo
# Documentation
def bar; end
end
RUBY
end
end
end
context 'with annotation comment' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo
# FIXME: offense
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
end
context 'with directive comment' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo
# rubocop:disable Style/For
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
end
context 'with both public and private methods' do
context 'when the public method has no documentation' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
private
def baz
puts 'baz'
end
end
RUBY
end
end
context 'when the public method has documentation' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Foo
# Documentation
def bar
puts 'baz'
end
private
def baz
puts 'baz'
end
end
RUBY
end
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo
# Documentation
def bar
puts 'baz'
end
private
def baz
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
end
end
end
context 'when declaring methods in a module' do
context 'without documentation comment' do
context 'when method is public' do
it 'registers an offense' do
expect_offense(<<~RUBY)
module Foo
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
module Foo
def method; end
^^^^^^^^^^^^^^^ Missing method documentation comment.
end
RUBY
end
end
context 'when method is private' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
module Foo
private
def bar
puts 'baz'
end
end
RUBY
end
it 'does not register an offense with inline `private`' do
expect_no_offenses(<<~RUBY)
module Foo
private def bar
puts 'baz'
end
end
RUBY
end
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
module Foo
private
def bar; end
end
RUBY
end
it 'does not register an offense with inline `private` and `end`' do
expect_no_offenses(<<~RUBY)
module Foo
private def bar; end
end
RUBY
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
module Foo
private
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
it 'registers an offense with inline `private`' do
expect_offense(<<~RUBY)
module Foo
private def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
module Foo
private
def bar; end
^^^^^^^^^^^^ Missing method documentation comment.
end
RUBY
end
it 'registers an offense with inline `private` and `end`' do
expect_offense(<<~RUBY)
module Foo
private def bar; end
^^^^^^^^^^^^ Missing method documentation comment.
end
RUBY
end
end
end
context 'when method is module_function' do
it 'registers an offense for inline def' do
expect_offense(<<~RUBY)
module Foo
module_function def bar
^^^^^^^^^^^^^^^^^^^^^^^ Missing method documentation comment.
end
end
RUBY
end
it 'registers an offense for separate def' do
expect_offense(<<~RUBY)
module Foo
def bar
^^^^^^^ Missing method documentation comment.
end
module_function :bar
end
RUBY
end
end
it 'registers an offense for inline def with ruby2_keywords' do
expect_offense(<<~RUBY)
module Foo
ruby2_keywords def bar
^^^^^^^^^^^^^^^^^^^^^^ Missing method documentation comment.
end
end
RUBY
end
end
context 'with documentation comment' do
context 'when method is public' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
module Foo
# Documentation
def bar
puts 'baz'
end
end
RUBY
end
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
module Foo
# Documentation
def bar; end
end
RUBY
end
end
context 'when method is module_function' do
it 'does not register an offense for inline def' do
expect_no_offenses(<<~RUBY)
module Foo
# Documentation
module_function def bar; end
end
RUBY
end
it 'does not register an offense for separate def' do
expect_no_offenses(<<~RUBY)
module Foo
# Documentation
def bar; end
module_function :bar
end
RUBY
end
end
it 'does not register an offense for inline def with ruby2_keywords' do
expect_no_offenses(<<~RUBY)
module Foo
# Documentation
ruby2_keywords def bar
end
end
RUBY
end
end
context 'with both public and private methods' do
context 'when the public method has no documentation' do
it 'registers an offense' do
expect_offense(<<~RUBY)
module Foo
def bar
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
private
def baz
puts 'baz'
end
end
RUBY
end
end
context 'when the public method has documentation' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
module Foo
# Documentation
def bar
puts 'baz'
end
private
def baz
puts 'baz'
end
end
RUBY
end
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
module Foo
# Documentation
def bar
puts 'baz'
end
private
def baz
^^^^^^^ Missing method documentation comment.
puts 'baz'
end
end
RUBY
end
end
end
end
context 'when declaring methods for class instance' do
context 'without documentation comment' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.new
def foo.bar
^^^^^^^^^^^ Missing method documentation comment.
puts 'baz'
end
RUBY
end
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.new
def foo.bar; end
^^^^^^^^^^^^^^^^ Missing method documentation comment.
RUBY
end
end
context 'with documentation comment' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Foo; end
foo = Foo.new
# Documentation
def foo.bar
puts 'baz'
end
RUBY
end
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
class Foo; end
foo = Foo.new
# Documentation
def foo.bar; end
RUBY
end
context 'when method is private' do
it 'does not register an offense with `end` on the same line' do
expect_no_offenses(<<~RUBY)
class Foo; end
foo = Foo.bar
private
def foo.bar; end
RUBY
end
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Foo; end
foo = Foo.new
private
def foo.bar
puts 'baz'
end
RUBY
end
it 'does not register an offense with inline `private` and `end`' do
expect_no_offenses(<<~RUBY)
class Foo; end
foo = Foo.new
private def foo.bar; end
RUBY
end
it 'does not register an offense with inline `private`' do
expect_no_offenses(<<~RUBY)
class Foo; end
foo = Foo.new
private def foo.bar
puts 'baz'
end
RUBY
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense with `end` on the same line' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.bar
private
def foo.bar; end
^^^^^^^^^^^^^^^^ Missing method documentation comment.
RUBY
end
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.new
private
def foo.bar
^^^^^^^^^^^ Missing method documentation comment.
puts 'baz'
end
RUBY
end
it 'registers an offense with inline `private` and `end`' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.new
private def foo.bar; end
^^^^^^^^^^^^^^^^ Missing method documentation comment.
RUBY
end
it 'registers an offense with inline `private`' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.new
private def foo.bar
^^^^^^^^^^^ Missing method documentation comment.
puts 'baz'
end
RUBY
end
end
end
context 'with both public and private methods' do
context 'when the public method has no documentation' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.new
def foo.bar
^^^^^^^^^^^ Missing method documentation comment.
puts 'baz'
end
private
def foo.baz
puts 'baz'
end
RUBY
end
end
context 'when the public method has documentation' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
class Foo; end
foo = Foo.new
# Documentation
def foo.bar
puts 'baz'
end
private
def foo.baz
puts 'baz'
end
RUBY
end
end
context 'when required for non-public methods' do
let(:require_for_non_public_methods) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
class Foo; end
foo = Foo.new
# Documentation
def foo.bar
puts 'baz'
end
private
def foo.baz
^^^^^^^^^^^ Missing method documentation comment.
puts 'baz'
end
RUBY
end
end
end
end
describe 'when AllowedMethods is configured' do
before { config['Style/DocumentationMethod'] = { 'AllowedMethods' => ['method_missing'] } }
it 'ignores the methods in the config' do
expect_no_offenses(<<~RUBY)
class Foo
def method_missing(name, *args)
end
end
RUBY
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.