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/yoda_expression_spec.rb | spec/rubocop/cop/style/yoda_expression_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::YodaExpression, :config do
let(:cop_config) { { 'SupportedOperators' => ['*', '+'] } }
it 'registers an offense when numeric literal on left' do
expect_offense(<<~RUBY)
1 + x
^^^^^ Non-literal operand (`x`) should be first.
RUBY
expect_correction(<<~RUBY)
x + 1
RUBY
end
it 'registers an offense when constant on left' do
expect_offense(<<~RUBY)
CONST + x
^^^^^^^^^ Non-literal operand (`x`) should be first.
RUBY
expect_correction(<<~RUBY)
x + CONST
RUBY
end
it 'registers an offense and corrects when using complex use of numeric literals' do
expect_offense(<<~RUBY)
2 + (1 + x)
^^^^^^^^^^^ Non-literal operand (`(1 + x)`) should be first.
RUBY
expect_correction(<<~RUBY)
(x + 1) + 2
RUBY
end
it 'registers an offense and corrects when using complex use of constants' do
expect_offense(<<~RUBY)
TWO + (ONE + x)
^^^^^^^^^^^^^^^ Non-literal operand (`(ONE + x)`) should be first.
RUBY
expect_correction(<<~RUBY)
(x + ONE) + TWO
RUBY
end
it 'accepts numeric literal on the right' do
expect_no_offenses(<<~RUBY)
x + 42
RUBY
end
it 'accepts constant on the right' do
expect_no_offenses(<<~RUBY)
x + FORTY_TWO
RUBY
end
it 'accepts neither numeric literal nor constant' do
expect_no_offenses(<<~RUBY)
x + y
RUBY
end
it 'accepts `|`' do
expect_no_offenses(<<~RUBY)
1 | x
RUBY
end
it 'registers an offense and corrects when using suffix form of operator with constant receiver' do
expect_offense(<<~RUBY)
1 + CONST.+(ary)
^^^^^^^^^^^^^^^^ Non-literal operand (`CONST.+(ary)`) should be first.
RUBY
expect_correction(<<~RUBY)
ary.+(CONST) + 1
RUBY
end
it 'registers an offense and corrects when using suffix form of nullary operator with constant receiver' do
expect_offense(<<~RUBY)
1 + CONST.*
^^^^^^^^^^^ Non-literal operand (`CONST.*`) should be first.
RUBY
expect_correction(<<~RUBY)
CONST.* + 1
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/quoted_symbols_spec.rb | spec/rubocop/cop/style/quoted_symbols_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::QuotedSymbols, :config do
shared_examples 'enforce single quotes' do
it 'accepts unquoted symbols' do
expect_no_offenses(<<~RUBY)
:a
RUBY
end
it 'accepts single quotes' do
expect_no_offenses(<<~RUBY)
:'a'
RUBY
end
it 'accepts double quotes with interpolation' do
expect_no_offenses(<<~'RUBY')
:"#{a}"
RUBY
end
it 'accepts double quotes when interpolating an instance variable' do
expect_no_offenses(<<~'RUBY')
:"#@test"
RUBY
end
it 'accepts double quotes when interpolating a global variable' do
expect_no_offenses(<<~'RUBY')
:"#$test"
RUBY
end
it 'accepts double quotes when interpolating a class variable' do
expect_no_offenses(<<~'RUBY')
:"#@@test"
RUBY
end
it 'accepts double quotes with escape sequences' do
expect_no_offenses(<<~'RUBY')
:"a\nb"
RUBY
end
it 'accepts single quotes with double quotes' do
expect_no_offenses(<<~RUBY)
:'"'
RUBY
end
it 'accepts double quotes with single quotes' do
expect_no_offenses(<<~RUBY)
:"'"
RUBY
end
it 'accepts single quotes with line breaks' do
expect_no_offenses(<<~RUBY)
:'a
bc'
RUBY
end
it 'accepts double quotes with line breaks' do
expect_no_offenses(<<~RUBY)
:"a
bc"
RUBY
end
it 'accepts double quotes when control characters are used' do
expect_no_offenses(<<~'RUBY')
:"\e"
RUBY
end
it 'accepts double quotes when unicode control sequence is used' do
expect_no_offenses(<<~'RUBY')
:"Espa\u00f1a"
RUBY
end
it 'accepts double quotes with some other special symbols' do
# "Substitutions in double-quoted symbols"
# http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html
expect_no_offenses(<<~'RUBY')
g = :"\x3D"
copyright = :"\u00A9"
RUBY
end
it 'registers an offense and corrects for double quotes without interpolation' do
expect_offense(<<~RUBY)
:"a"
^^^^ Prefer single-quoted symbols when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~RUBY)
:'a'
RUBY
end
it 'registers an offense and corrects for double quotes in hash keys' do
expect_offense(<<~RUBY)
{ "a": value }
^^^ Prefer single-quoted symbols when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~RUBY)
{ 'a': value }
RUBY
end
it 'registers an offense and corrects for an escaped quote within double quotes' do
expect_offense(<<~'RUBY')
:"my\"quote"
^^^^^^^^^^^^ Prefer single-quoted symbols when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~RUBY)
:'my"quote'
RUBY
end
it 'registers an offense and corrects escape characters properly' do
expect_offense(<<~'RUBY')
:"foo\\bar"
^^^^^^^^^^^ Prefer single-quoted symbols when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~'RUBY')
:'foo\\bar'
RUBY
end
it 'accepts single quoted symbol with an escaped quote' do
expect_no_offenses(<<~'RUBY')
:'o\'clock'
RUBY
end
context 'hash with hash rocket style' do
it 'accepts properly quoted symbols' do
expect_no_offenses(<<~RUBY)
{ :'a' => value }
RUBY
end
it 'corrects wrong quotes' do
expect_offense(<<~RUBY)
{ :"a" => value }
^^^^ Prefer single-quoted symbols when you don't need string interpolation or special symbols.
RUBY
expect_correction(<<~RUBY)
{ :'a' => value }
RUBY
end
end
end
shared_examples 'enforce double quotes' do
it 'accepts unquoted symbols' do
expect_no_offenses(<<~RUBY)
:a
RUBY
end
it 'accepts double quotes' do
expect_no_offenses(<<~RUBY)
:"a"
RUBY
end
it 'accepts double quotes with interpolation' do
expect_no_offenses(<<~'RUBY')
:"#{a}"
RUBY
end
it 'accepts double quotes when interpolating an instance variable' do
expect_no_offenses(<<~'RUBY')
:"#@test"
RUBY
end
it 'accepts double quotes when interpolating a global variable' do
expect_no_offenses(<<~'RUBY')
:"#$test"
RUBY
end
it 'accepts double quotes when interpolating a class variable' do
expect_no_offenses(<<~'RUBY')
:"#@@test"
RUBY
end
it 'accepts double quotes with escape sequences' do
expect_no_offenses(<<~'RUBY')
:"a\nb"
RUBY
end
it 'accepts single quotes with double quotes' do
expect_no_offenses(<<~RUBY)
:'"'
RUBY
end
it 'accepts double quotes with single quotes' do
expect_no_offenses(<<~RUBY)
:"'"
RUBY
end
it 'accepts single quotes with line breaks' do
expect_no_offenses(<<~RUBY)
:'a
bc'
RUBY
end
it 'accepts double quotes with line breaks' do
expect_no_offenses(<<~RUBY)
:'a
bc'
RUBY
end
it 'registers an offense for single quotes' do
expect_offense(<<~RUBY)
:'a'
^^^^ Prefer double-quoted symbols unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect_correction(<<~RUBY)
:"a"
RUBY
end
it 'registers an offense and corrects for an escaped quote within single quotes' do
expect_offense(<<~'RUBY')
:'o\'clock'
^^^^^^^^^^^ Prefer double-quoted symbols unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect_correction(<<~RUBY)
:"o'clock"
RUBY
end
it 'registers an offense and corrects escape characters properly' do
expect_offense(<<~'RUBY')
:'foo\\bar'
^^^^^^^^^^^ Prefer double-quoted symbols unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect_correction(<<~'RUBY')
:"foo\\bar"
RUBY
end
it 'accepts double quoted symbol with an escaped quote' do
expect_no_offenses(<<~'RUBY')
:"my\"quote"
RUBY
end
context 'hash with hash rocket style' do
it 'accepts properly quoted symbols' do
expect_no_offenses(<<~RUBY)
{ :"a" => value }
RUBY
end
it 'corrects wrong quotes' do
expect_offense(<<~RUBY)
{ :'a' => value }
^^^^ Prefer double-quoted symbols unless you need single quotes to avoid extra backslashes for escaping.
RUBY
expect_correction(<<~RUBY)
{ :"a" => value }
RUBY
end
end
end
context 'configured with `same_as_string_literals`' do
let(:cop_config) { { 'EnforcedStyle' => 'same_as_string_literals' } }
context 'when Style/StringLiterals is configured with single_quotes' do
let(:other_cops) { { 'Style/StringLiterals' => { 'EnforcedStyle' => 'single_quotes' } } }
it_behaves_like 'enforce single quotes'
end
context 'when Style/StringLiterals is configured with double_quotes' do
let(:other_cops) { { 'Style/StringLiterals' => { 'EnforcedStyle' => 'double_quotes' } } }
it_behaves_like 'enforce double quotes'
end
context 'when Style/StringLiterals is disabled' do
let(:other_cops) { { 'Style/StringLiterals' => { 'Enabled' => false } } }
it_behaves_like 'enforce single quotes'
end
end
context 'configured with `single_quotes`' do
let(:cop_config) { { 'EnforcedStyle' => 'single_quotes' } }
it_behaves_like 'enforce single quotes'
end
context 'configured with `double_quotes`' do
let(:cop_config) { { 'EnforcedStyle' => 'double_quotes' } }
it_behaves_like 'enforce double quotes'
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/symbol_literal_spec.rb | spec/rubocop/cop/style/symbol_literal_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SymbolLiteral, :config do
it 'registers an offense for word-line symbols using string syntax' do
expect_offense(<<~RUBY)
x = { :"test" => 0, :"other" => 1 }
^^^^^^^^ Do not use strings for word-like symbol literals.
^^^^^^^ Do not use strings for word-like symbol literals.
RUBY
expect_correction(<<~RUBY)
x = { :test => 0, :other => 1 }
RUBY
end
it 'accepts string syntax when symbols have whitespaces in them' do
expect_no_offenses('x = { :"t o" => 0 }')
end
it 'accepts string syntax when symbols have special chars in them' do
expect_no_offenses('x = { :"\\tab" => 1 }')
end
it 'accepts string syntax when symbol start with a digit' do
expect_no_offenses('x = { :"1" => 1 }')
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/def_with_parentheses_spec.rb | spec/rubocop/cop/style/def_with_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DefWithParentheses, :config do
it 'reports an offense for def with empty parens' do
expect_offense(<<~RUBY)
def func()
^^ Omit the parentheses in defs when the method doesn't accept any arguments.
end
RUBY
expect_correction(<<~RUBY)
def func
end
RUBY
end
it 'reports an offense for class def with empty parens' do
expect_offense(<<~RUBY)
def Test.func()
^^ Omit the parentheses in defs when the method doesn't accept any arguments.
something
end
RUBY
expect_correction(<<~RUBY)
def Test.func
something
end
RUBY
end
context 'Ruby >= 3.0', :ruby30 do
it 'reports an offense for endless method definition with empty parens' do
expect_offense(<<~RUBY)
def foo() = do_something
^^ Omit the parentheses in defs when the method doesn't accept any arguments.
RUBY
expect_correction(<<~RUBY)
def foo = do_something
RUBY
end
it 'reports an offense for endless method definition with empty parens followed by a space before `=`' do
expect_offense(<<~RUBY)
def foo() =do_something
^^ Omit the parentheses in defs when the method doesn't accept any arguments.
RUBY
expect_correction(<<~RUBY)
def foo =do_something
RUBY
end
it 'does not register an offense for endless method definition with empty parens followed by no space before `=`' do
expect_no_offenses(<<~RUBY)
def foo()= do_something
RUBY
end
it 'does not register an offense for endless method definition with empty parens followed by no spaces around `=`' do
expect_no_offenses(<<~RUBY)
def foo()=do_something
RUBY
end
end
it 'accepts def with arg and parens' do
expect_no_offenses(<<~RUBY)
def func(a)
end
RUBY
end
it 'accepts def without arguments' do
expect_no_offenses(<<~RUBY)
def func
end
RUBY
end
it 'accepts empty parentheses in one liners' do
expect_no_offenses("def to_s() join '/' 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_argument_spec.rb | spec/rubocop/cop/style/redundant_regexp_argument_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantRegexpArgument, :config do
described_class::RESTRICT_ON_SEND.each do |method|
it "registers an offense and corrects when the method is `#{method}`" do
expect_offense(<<~RUBY, method: method)
'foo'.#{method}(/f/)
_{method} ^^^ Use string `'f'` as argument instead of regexp `/f/`.
RUBY
expect_correction(<<~RUBY)
'foo'.#{method}('f')
RUBY
end
it "registers an offense and corrects when the method with safe navigation operator is `#{method}`" do
expect_offense(<<~RUBY, method: method)
'foo'&.#{method}(/f/)
_{method} ^^^ Use string `'f'` as argument instead of regexp `/f/`.
RUBY
expect_correction(<<~RUBY)
'foo'&.#{method}('f')
RUBY
end
end
it 'registers an offense and corrects when using double quote and single quote characters' do
expect_offense(<<~RUBY)
str.gsub(/"''/, '')
^^^^^ Use string `'"\\'\\''` as argument instead of regexp `/"''/`.
RUBY
expect_correction(<<~RUBY)
str.gsub('"\\'\\'', '')
RUBY
end
it 'registers an offense and corrects when using double quote character' do
expect_offense(<<~RUBY)
str.gsub(/"/)
^^^ Use string `'"'` as argument instead of regexp `/"/`.
RUBY
expect_correction(<<~RUBY)
str.gsub('"')
RUBY
end
it 'registers an offense and corrects when using single quote character' do
expect_offense(<<~'RUBY')
str.gsub(/'/)
^^^ Use string `'\''` as argument instead of regexp `/'/`.
RUBY
expect_correction(<<~'RUBY')
str.gsub('\'')
RUBY
end
it 'registers an offense and corrects when using escaped single quote character' do
expect_offense(<<~'RUBY')
str.gsub(/\'/)
^^^^ Use string `'\''` as argument instead of regexp `/\'/`.
RUBY
expect_correction(<<~'RUBY')
str.gsub('\'')
RUBY
end
context 'single quote with escape character(s)' do
it 'registers an offense and corrects when using single backslash and single quote' do
expect_offense(<<~'RUBY')
str.gsub!(/\\'/, "'")
^^^^^ Use string `'\\\''` as argument instead of regexp `/\\'/`.
RUBY
expect_correction(<<~'RUBY')
str.gsub!('\\\'', "'")
RUBY
end
it 'registers an offense and corrects when using single backslash and escaped single quote' do
expect_offense(<<~'RUBY')
str.gsub!(/\\\'/, "'")
^^^^^^ Use string `'\\\''` as argument instead of regexp `/\\\'/`.
RUBY
expect_correction(<<~'RUBY')
str.gsub!('\\\'', "'")
RUBY
end
it 'registers an offense and corrects when using double backslash and single quote' do
expect_offense(<<~'RUBY')
str.gsub!(/\\\\'/, "'")
^^^^^^^ Use string `'\\\\\''` as argument instead of regexp `/\\\\'/`.
RUBY
expect_correction(<<~'RUBY')
str.gsub!('\\\\\'', "'")
RUBY
end
it 'registers an offense and corrects when using double backslash and escaped single quote' do
expect_offense(<<~'RUBY')
str.gsub!(/\\\\\'/, "'")
^^^^^^^^ Use string `'\\\\\''` as argument instead of regexp `/\\\\\'/`.
RUBY
expect_correction(<<~'RUBY')
str.gsub!('\\\\\'', "'")
RUBY
end
end
it 'registers an offense and corrects when using escaped double quote character' do
expect_offense(<<~'RUBY')
str.gsub(/\"/)
^^^^ Use string `'"'` as argument instead of regexp `/\"/`.
RUBY
expect_correction(<<~RUBY)
str.gsub('"')
RUBY
end
it 'registers an offense and corrects when using escape character with double quote character' do
expect_offense(<<~'RUBY')
str.gsub(/\\"/)
^^^^^ Use string `'\"'` as argument instead of regexp `/\\"/`.
RUBY
expect_correction(<<~'RUBY')
str.gsub('\"')
RUBY
end
it 'registers an offense and corrects when using escaping characters' do
expect_offense(<<~'RUBY')
'a,b,c'.split(/\./)
^^^^ Use string `'.'` as argument instead of regexp `/\./`.
RUBY
expect_correction(<<~RUBY)
'a,b,c'.split('.')
RUBY
end
it 'registers an offense and corrects when using special string chars' do
expect_offense(<<~'RUBY')
"foo\nbar\nbaz\n".split(/\n/)
^^^^ Use string `"\n"` as argument instead of regexp `/\n/`.
RUBY
expect_correction(<<~'RUBY')
"foo\nbar\nbaz\n".split("\n")
RUBY
end
it 'registers an offense and corrects when using consecutive special string chars' do
expect_offense(<<~'RUBY')
"foo\n\nbar\n\nbaz\n\n".split(/\n\n/)
^^^^^^ Use string `"\n\n"` as argument instead of regexp `/\n\n/`.
RUBY
expect_correction(<<~'RUBY')
"foo\n\nbar\n\nbaz\n\n".split("\n\n")
RUBY
end
it 'registers an offense and corrects when using unicode chars' do
expect_offense(<<~'RUBY')
"foo\nbar\nbaz\n".split(/\u3000/)
^^^^^^^^ Use string `"\u3000"` as argument instead of regexp `/\u3000/`.
RUBY
expect_correction(<<~'RUBY')
"foo\nbar\nbaz\n".split("\u3000")
RUBY
end
it 'registers an offense and corrects when using consecutive backslash escape chars' do
expect_offense(<<~'RUBY')
"foo\\\.bar".split(/\\\./)
^^^^^^ Use string `"\\."` as argument instead of regexp `/\\\./`.
RUBY
expect_correction(<<~'RUBY')
"foo\\\.bar".split("\\.")
RUBY
end
it 'registers an offense and corrects when using complex special string chars' do
expect_offense(<<~'RUBY')
"foo\nbar\nbaz\n".split(/foo\n\.\n/)
^^^^^^^^^^^ Use string `"foo\n.\n"` as argument instead of regexp `/foo\n\.\n/`.
RUBY
expect_correction(<<~'RUBY')
"foo\nbar\nbaz\n".split("foo\n.\n")
RUBY
end
it 'registers an offense and corrects when using two or more spaces regexp' do
expect_offense(<<~RUBY)
'foo bar'.split(/ /)
^^^^ Use string `' '` as argument instead of regexp `/ /`.
RUBY
expect_correction(<<~RUBY)
'foo bar'.split(' ')
RUBY
end
it 'accepts methods other than pattern argument method' do
expect_no_offenses("'a,b,c'.insert(2, 'a')")
end
it 'accepts when using `[]` method' do
expect_no_offenses('hash[/regexp/]')
end
it 'accepts when using `[]=` method' do
expect_no_offenses('hash[/regexp/] = value')
end
it 'accepts when not receiving a regexp' do
expect_no_offenses("'a,b,c'.split(',')")
end
it 'accepts when not receiving a deterministic regexp' do
expect_no_offenses("'a,b,c'.split(/,+/)")
end
it 'accepts when using regexp argument with ignorecase regexp option' do
expect_no_offenses("'fooSplitbar'.split(/split/i)")
end
it 'accepts when using regexp argument with extended regexp option' do
expect_no_offenses("'fooSplitbar'.split(/split/x)")
end
it 'accepts when using method argument is exactly one space regexp `/ /`' do
expect_no_offenses(<<~RUBY)
'foo bar'.split(/ /)
RUBY
end
context 'when `Style/StringLiterals` is configured with `single_quotes`' do
let(:other_cops) { { 'Style/StringLiterals' => { 'EnforcedStyle' => 'single_quotes' } } }
it 'registers an offense and corrects to single quoted string when using non-backquoted regexp' do
expect_offense(<<~RUBY)
'foo'.split(/f/)
^^^ Use string `'f'` as argument instead of regexp `/f/`.
RUBY
expect_correction(<<~RUBY)
'foo'.split('f')
RUBY
end
it 'registers an offense and corrects to double quoted string when using backquoted regexp' do
expect_offense(<<~'RUBY')
'foo'.split(/\n/)
^^^^ Use string `"\n"` as argument instead of regexp `/\n/`.
RUBY
expect_correction(<<~'RUBY')
'foo'.split("\n")
RUBY
end
end
context 'when `Style/StringLiterals` is configured with `double_quotes`' do
let(:other_cops) { { 'Style/StringLiterals' => { 'EnforcedStyle' => 'double_quotes' } } }
it 'registers an offense and corrects to double quoted string when using non-backquoted regexp' do
expect_offense(<<~RUBY)
'foo'.split(/f/)
^^^ Use string `"f"` as argument instead of regexp `/f/`.
RUBY
expect_correction(<<~RUBY)
'foo'.split("f")
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/block_comments_spec.rb | spec/rubocop/cop/style/block_comments_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::BlockComments, :config do
it 'registers an offense for block comments' do
expect_offense(<<~RUBY)
=begin
^^^^^^ Do not use block comments.
comment
=end
RUBY
expect_correction(<<~RUBY)
# comment
RUBY
end
it 'accepts regular comments' do
expect_no_offenses('# comment')
end
it 'autocorrects a block comment into a regular comment' do
expect_offense(<<~RUBY)
=begin
^^^^^^ Do not use block comments.
comment line 1
comment line 2
=end
def foo
end
RUBY
expect_correction(<<~RUBY)
# comment line 1
#
# comment line 2
def foo
end
RUBY
end
it 'autocorrects an empty block comment by removing it' do
expect_offense(<<~RUBY)
=begin
^^^^^^ Do not use block comments.
=end
def foo
end
RUBY
expect_correction(<<~RUBY)
def foo
end
RUBY
end
it 'autocorrects a block comment into a regular comment (without trailing newline)' do
expect_offense(<<~RUBY)
=begin
^^^^^^ Do not use block comments.
comment line 1
comment line 2
=end
RUBY
expect_correction(<<~RUBY)
# comment line 1
#
# comment line 2
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/bisected_attr_accessor_spec.rb | spec/rubocop/cop/style/bisected_attr_accessor_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::BisectedAttrAccessor, :config do
it 'registers an offense and corrects when both accessors of the name exists' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar
^^^^ Combine both accessors into `attr_accessor :bar`.
attr_writer :bar
^^^^ Combine both accessors into `attr_accessor :bar`.
other_macro :something
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :bar
other_macro :something
end
RUBY
end
it 'registers an offense and corrects when attr and attr_writer exists' do
expect_offense(<<~RUBY)
class Foo
attr :bar
^^^^ Combine both accessors into `attr_accessor :bar`.
attr_writer :bar
^^^^ Combine both accessors into `attr_accessor :bar`.
other_macro :something
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :bar
other_macro :something
end
RUBY
end
it 'registers an offense and corrects when both accessors of the splat exists' do
expect_offense(<<~RUBY)
class Foo
ATTRIBUTES = %i[foo bar]
attr_reader *ATTRIBUTES
^^^^^^^^^^^ Combine both accessors into `attr_accessor *ATTRIBUTES`.
attr_writer *ATTRIBUTES
^^^^^^^^^^^ Combine both accessors into `attr_accessor *ATTRIBUTES`.
other_macro :something
end
RUBY
expect_correction(<<~RUBY)
class Foo
ATTRIBUTES = %i[foo bar]
attr_accessor *ATTRIBUTES
other_macro :something
end
RUBY
end
it 'registers an offense and corrects when both accessors of the name exists and accessor contains multiple names' do
expect_offense(<<~RUBY)
class Foo
attr_reader :baz, :bar, :quux
^^^^ Combine both accessors into `attr_accessor :bar`.
attr_writer :bar, :zoo
^^^^ Combine both accessors into `attr_accessor :bar`.
other_macro :something
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :bar
attr_reader :baz, :quux
attr_writer :zoo
other_macro :something
end
RUBY
end
it 'registers an offense and corrects properly when attr_writer is before attr_reader' do
expect_offense(<<~RUBY)
class Foo
attr_writer :foo
^^^^ Combine both accessors into `attr_accessor :foo`.
attr_reader :foo
^^^^ Combine both accessors into `attr_accessor :foo`.
other_macro :something
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :foo
other_macro :something
end
RUBY
end
it 'registers an offense and corrects when both accessors are in the same visibility scope' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar
^^^^ Combine both accessors into `attr_accessor :bar`.
attr_writer :bar
^^^^ Combine both accessors into `attr_accessor :bar`.
private
attr_writer :baz
^^^^ Combine both accessors into `attr_accessor :baz`.
attr_reader :baz
^^^^ Combine both accessors into `attr_accessor :baz`.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :bar
private
attr_accessor :baz
end
RUBY
end
it 'registers an offense and corrects when within eigenclass' do
expect_offense(<<~RUBY)
class Foo
attr_reader :bar
class << self
attr_reader :baz
^^^^ Combine both accessors into `attr_accessor :baz`.
attr_writer :baz
^^^^ Combine both accessors into `attr_accessor :baz`.
private
attr_reader :quux
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_reader :bar
class << self
attr_accessor :baz
private
attr_reader :quux
end
end
RUBY
end
context 'multiple bisected accessors' do
context 'when all attr names are bisected' do
it 'registers and replaces with attr_accessor' do
expect_offense(<<~RUBY)
class Foo
attr_reader :foo, :bar, :baz
^^^^ Combine both accessors into `attr_accessor :foo`.
^^^^ Combine both accessors into `attr_accessor :bar`.
^^^^ Combine both accessors into `attr_accessor :baz`.
attr_writer :foo, :bar, :baz
^^^^ Combine both accessors into `attr_accessor :foo`.
^^^^ Combine both accessors into `attr_accessor :bar`.
^^^^ Combine both accessors into `attr_accessor :baz`.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :foo, :bar, :baz
end
RUBY
end
end
context 'when some attr names are bisected' do
it 'registers and retains non-bisected attrs' do
expect_offense(<<~RUBY)
class Foo
attr_reader :foo, :bar, :baz
^^^^ Combine both accessors into `attr_accessor :foo`.
^^^^ Combine both accessors into `attr_accessor :baz`.
attr_writer :foo, :baz
^^^^ Combine both accessors into `attr_accessor :foo`.
^^^^ Combine both accessors into `attr_accessor :baz`.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :foo, :baz
attr_reader :bar
end
RUBY
end
end
end
it 'does not register an offense when only one accessor of the name exists' do
expect_no_offenses(<<~RUBY)
class Foo
attr_reader :bar
attr_writer :baz
end
RUBY
end
it 'does not register an offense when accessors are within different visibility scopes' do
expect_no_offenses(<<~RUBY)
class Foo
attr_reader :bar
private
attr_writer :bar
end
RUBY
end
it 'registers an offense for accessors with the same visibility in different scopes' do
expect_offense(<<~RUBY)
class Foo
attr_reader :foo
^^^^ Combine both accessors into `attr_accessor :foo`.
private
attr_writer :bar
public
attr_writer :foo
^^^^ Combine both accessors into `attr_accessor :foo`.
end
RUBY
expect_correction(<<~RUBY)
class Foo
attr_accessor :foo
private
attr_writer :bar
public
end
RUBY
end
it 'registers and corrects in a module' do
expect_offense(<<~RUBY)
module Foo
attr_reader :foo
^^^^ Combine both accessors into `attr_accessor :foo`.
attr_writer :foo, :bar
^^^^ Combine both accessors into `attr_accessor :foo`.
private
attr_reader :bar, :baz
^^^^ Combine both accessors into `attr_accessor :baz`.
attr_writer :baz
^^^^ Combine both accessors into `attr_accessor :baz`.
end
RUBY
expect_correction(<<~RUBY)
module Foo
attr_accessor :foo
attr_writer :bar
private
attr_accessor :baz
attr_reader :bar
end
RUBY
end
it 'does not register an offense when using `attr_accessor`' do
expect_no_offenses(<<~RUBY)
class Foo
attr_accessor :bar
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/comment_annotation_spec.rb | spec/rubocop/cop/style/comment_annotation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CommentAnnotation, :config do
context 'with default RequireColon configuration (colon + space)' do
let(:cop_config) { { 'Keywords' => %w[TODO FIXME OPTIMIZE HACK REVIEW] } }
context 'missing colon' do
it 'registers an offense and adds colon' do
expect_offense(<<~RUBY)
# TODO make better
^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a colon, and a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# TODO: make better
RUBY
end
end
context 'with configured keyword' do
let(:cop_config) { { 'Keywords' => %w[ISSUE] } }
it 'registers an offense for a missing colon after the word' do
expect_offense(<<~RUBY)
# ISSUE wrong order
^^^^^^ Annotation keywords like `ISSUE` should be all upper case, followed by a colon, and a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# ISSUE: wrong order
RUBY
end
end
context 'missing space after colon' do
it 'registers an offense and adds space' do
expect_offense(<<~RUBY)
# TODO:make better
^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a colon, and a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# TODO: make better
RUBY
end
end
context 'lower case keyword' do
it 'registers an offense and upcases' do
expect_offense(<<~RUBY)
# fixme: does not work
^^^^^^^ Annotation keywords like `fixme` should be all upper case, followed by a colon, and a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# FIXME: does not work
RUBY
end
end
context 'capitalized keyword' do
it 'registers an offense and upcases' do
expect_offense(<<~RUBY)
# Optimize: does not work
^^^^^^^^^^ Annotation keywords like `Optimize` should be all upper case, followed by a colon, and a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# OPTIMIZE: does not work
RUBY
end
end
context 'upper case keyword with colon but no note' do
it 'registers an offense without autocorrection' do
expect_offense(<<~RUBY)
# HACK:
^^^^^ Annotation comment, with keyword `HACK`, is missing a note.
RUBY
expect_no_corrections
end
end
context 'upper case keyword with space but no note' do
it 'registers an offense without autocorrection' do
expect_offense(<<~RUBY)
# HACK#{trailing_whitespace}
^^^^^ Annotation comment, with keyword `HACK`, is missing a note.
RUBY
expect_no_corrections
end
end
it 'accepts upper case keyword with colon, space and note' do
expect_no_offenses('# REVIEW: not sure about this')
end
it 'accepts upper case keyword alone' do
expect_no_offenses('# OPTIMIZE')
end
it 'accepts a comment that is obviously a code example' do
expect_no_offenses('# Todo.destroy(1)')
end
it 'accepts a keyword that is just the beginning of a sentence' do
expect_no_offenses(<<~RUBY)
# Optimize if you want. I wouldn't recommend it.
# Hack is a fun game.
RUBY
end
it 'accepts a keyword that is somewhere in a sentence' do
expect_no_offenses(<<~RUBY)
# Example: There are three reviews, with ranks 1, 2, and 3. A new
# review is saved with rank 2. The two reviews that originally had
# ranks 2 and 3 will have their ranks increased to 3 and 4.
RUBY
end
context 'when a keyword is not in the configuration' do
let(:cop_config) { { 'Keywords' => %w[FIXME OPTIMIZE HACK REVIEW] } }
it 'accepts the word without colon' do
expect_no_offenses('# TODO make better')
end
end
context 'offenses in consecutive inline comments' do
it 'registers each of them' do
expect_offense(<<~RUBY)
class ToBeDone
ITEMS = [
'', # TODO Item 1
^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a colon, and a space, then a note describing the problem.
'', # TODO Item 2
^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a colon, and a space, then a note describing the problem.
].freeze
end
RUBY
end
end
context 'multiline comment' do
it 'only registers an offense on the first line' do
expect_offense(<<~RUBY)
# TODO line 1
^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a colon, and a space, then a note describing the problem.
# TODO line 2
# TODO line 3
RUBY
end
end
context 'with multiword keywords' do
let(:cop_config) { { 'Keywords' => ['TODO', 'DO SOMETHING', 'TODO LATER'] } }
it 'registers an offense for each matching keyword' do
cop_config['Keywords'].each do |keyword|
expect_offense(<<~RUBY, keyword: keyword)
# #{keyword} blah blah blah
^{keyword}^ Annotation keywords like `#{keyword}` should be all upper case, followed by a colon, and a space, then a note describing the problem.
RUBY
end
end
end
end
context 'with RequireColon configuration set to false' do
let(:cop_config) do
{
'Keywords' => %w[TODO FIXME OPTIMIZE HACK REVIEW],
'RequireColon' => false
}
end
context 'with colon' do
it 'registers an offense and removes colon' do
expect_offense(<<~RUBY)
# TODO: make better
^^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# TODO make better
RUBY
end
end
context 'with configured keyword' do
let(:cop_config) { { 'Keywords' => %w[ISSUE], 'RequireColon' => false } }
it 'registers an offense for containing a colon after the word' do
expect_offense(<<~RUBY)
# ISSUE: wrong order
^^^^^^^ Annotation keywords like `ISSUE` should be all upper case, followed by a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# ISSUE wrong order
RUBY
end
end
context 'lower case keyword' do
it 'registers an offense and upcases' do
expect_offense(<<~RUBY)
# fixme does not work
^^^^^^ Annotation keywords like `fixme` should be all upper case, followed by a space, then a note describing the problem.
RUBY
expect_correction(<<~RUBY)
# FIXME does not work
RUBY
end
end
context 'upper case keyword with colon but no note' do
it 'registers an offense without autocorrection' do
expect_offense(<<~RUBY)
# HACK:
^^^^^ Annotation comment, with keyword `HACK`, is missing a note.
RUBY
expect_no_corrections
end
end
context 'upper case keyword with space but no note' do
it 'registers an offense without autocorrection' do
expect_offense(<<~RUBY)
# HACK#{trailing_whitespace}
^^^^^ Annotation comment, with keyword `HACK`, is missing a note.
RUBY
expect_no_corrections
end
end
it 'accepts upper case keyword with colon, space and note' do
expect_no_offenses('# REVIEW not sure about this')
end
it 'accepts upper case keyword alone' do
expect_no_offenses('# OPTIMIZE')
end
it 'accepts a comment that is obviously a code example' do
expect_no_offenses('# Todo.destroy(1)')
end
it 'accepts a keyword that is just the beginning of a sentence' do
expect_no_offenses(<<~RUBY)
# Optimize if you want. I wouldn't recommend it.
# Hack is a fun game.
RUBY
end
it 'accepts a keyword that is somewhere in a sentence' do
expect_no_offenses(<<~RUBY)
# Example: There are three reviews, with ranks 1, 2, and 3. A new
# review is saved with rank 2. The two reviews that originally had
# ranks 2 and 3 will have their ranks increased to 3 and 4.
RUBY
end
context 'when a keyword is not in the configuration' do
let(:cop_config) do
{
'Keywords' => %w[FIXME OPTIMIZE HACK REVIEW],
'RequireColon' => false
}
end
it 'accepts the word with colon' do
expect_no_offenses('# TODO: make better')
end
end
context 'offenses in consecutive inline comments' do
it 'registers each of them' do
expect_offense(<<~RUBY)
class ToBeDone
ITEMS = [
'', # TODO: Item 1
^^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a space, then a note describing the problem.
'', # TODO: Item 2
^^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a space, then a note describing the problem.
].freeze
end
RUBY
end
end
context 'multiline comment' do
it 'only registers an offense on the first line' do
expect_offense(<<~RUBY)
# TODO: line 1
^^^^^^ Annotation keywords like `TODO` should be all upper case, followed by a space, then a note describing the problem.
# TODO: line 2
# TODO: line 3
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/nested_file_dirname_spec.rb | spec/rubocop/cop/style/nested_file_dirname_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NestedFileDirname, :config do
context 'Ruby >= 3.1', :ruby31 do
it 'registers and corrects an offense when using `File.dirname(path)` nested two times' do
expect_offense(<<~RUBY)
File.dirname(File.dirname(path))
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dirname(path, 2)` instead.
RUBY
expect_correction(<<~RUBY)
File.dirname(path, 2)
RUBY
end
it 'registers and corrects an offense when using `File.dirname(path)` nested three times' do
expect_offense(<<~RUBY)
File.dirname(File.dirname(File.dirname(path)))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `dirname(path, 3)` instead.
RUBY
expect_correction(<<~RUBY)
File.dirname(path, 3)
RUBY
end
it 'does not register an offense when using non nested `File.dirname(path)`' do
expect_no_offenses(<<~RUBY)
File.dirname(path)
RUBY
end
it 'does not register an offense when using `File.dirname(path, 2)`' do
expect_no_offenses(<<~RUBY)
File.dirname(path, 2)
RUBY
end
end
context 'Ruby <= 3.0', :ruby30, unsupported_on: :prism do
it 'does not register an offense when using `File.dirname(path)` nested two times' do
expect_no_offenses(<<~RUBY)
File.dirname(File.dirname(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/zero_length_predicate_spec.rb | spec/rubocop/cop/style/zero_length_predicate_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ZeroLengthPredicate, :config do
context 'with arrays' do
it 'registers an offense for `array.length == 0`' do
expect_offense(<<~RUBY)
[1, 2, 3].length == 0
^^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `length == 0`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array&.length == 0`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.length == 0
^^^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `length == 0`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.empty?
RUBY
end
it 'registers an offense for `array.size == 0`' do
expect_offense(<<~RUBY)
[1, 2, 3].size == 0
^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `size == 0`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array.length.zero?`' do
expect_offense(<<~RUBY)
[1, 2, 3].length.zero?
^^^^^^^^^^^^ Use `empty?` instead of `length.zero?`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array&.length.zero?`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.length.zero?
^^^^^^^^^^^^ Use `empty?` instead of `length.zero?`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.empty?
RUBY
end
it 'registers an offense for `array&.length&.zero?`' do
expect_offense(<<~RUBY)
[1, 2, 3]&.length&.zero?
^^^^^^^^^^^^^ Use `empty?` instead of `length&.zero?`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.empty?
RUBY
end
it 'registers an offense for `array.size.zero?`' do
expect_offense(<<~RUBY)
[1, 2, 3].size.zero?
^^^^^^^^^^ Use `empty?` instead of `size.zero?`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `0 == array.length`' do
expect_offense(<<~RUBY)
0 == [1, 2, 3].length
^^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `0 == length`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `0 == array.size`' do
expect_offense(<<~RUBY)
0 == [1, 2, 3].size
^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `0 == size`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array.length < 1`' do
expect_offense(<<~RUBY)
[1, 2, 3].length < 1
^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `length < 1`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array&.length < 1`' do
expect_offense(<<~RUBY)
array&.length < 1
^^^^^^^^^^^^^^^^^ Use `empty?` instead of `length < 1`.
RUBY
expect_correction(<<~RUBY)
array&.empty?
RUBY
end
it 'registers an offense for `array.size < 1`' do
expect_offense(<<~RUBY)
[1, 2, 3].size < 1
^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `size < 1`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `1 > array.length`' do
expect_offense(<<~RUBY)
1 > [1, 2, 3].length
^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `1 > length`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `1 > array&.length`' do
expect_offense(<<~RUBY)
1 > array&.length
^^^^^^^^^^^^^^^^^ Use `empty?` instead of `1 > length`.
RUBY
expect_correction(<<~RUBY)
array&.empty?
RUBY
end
it 'registers an offense for `1 > array.size`' do
expect_offense(<<~RUBY)
1 > [1, 2, 3].size
^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `1 > size`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array.length > 0`' do
expect_offense(<<~RUBY)
[1, 2, 3].length > 0
^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `length > 0`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'does not register an offense for `array&.length > 0`' do
expect_no_offenses(<<~RUBY)
[1, 2, 3]&.length > 0
RUBY
end
it 'registers an offense for `array.size > 0`' do
expect_offense(<<~RUBY)
[1, 2, 3].size > 0
^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `size > 0`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array.length != 0`' do
expect_offense(<<~RUBY)
[1, 2, 3].length != 0
^^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `length != 0`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `array.size != 0`' do
expect_offense(<<~RUBY)
[1, 2, 3].size != 0
^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `size != 0`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `!array.length.zero?`' do
expect_offense(<<~RUBY)
![1, 2, 3].length.zero?
^^^^^^^^^^^^ Use `empty?` instead of `length.zero?`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `!array.size.zero?`' do
expect_offense(<<~RUBY)
![1, 2, 3].size.zero?
^^^^^^^^^^ Use `empty?` instead of `size.zero?`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `0 < array.length' do
expect_offense(<<~RUBY)
0 < [1, 2, 3].length
^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `0 < length`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `0 < array.size`' do
expect_offense(<<~RUBY)
0 < [1, 2, 3].size
^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `0 < size`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `0 != array.length`' do
expect_offense(<<~RUBY)
0 != [1, 2, 3].length
^^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `0 != length`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
it 'registers an offense for `0 != array.size`' do
expect_offense(<<~RUBY)
0 != [1, 2, 3].size
^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `0 != size`.
RUBY
expect_correction(<<~RUBY)
![1, 2, 3].empty?
RUBY
end
end
context 'with hashes' do
it 'registers an offense for `hash.size == 0`' do
expect_offense(<<~RUBY)
{ a: 1, b: 2 }.size == 0
^^^^^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `size == 0`.
RUBY
expect_correction(<<~RUBY)
{ a: 1, b: 2 }.empty?
RUBY
end
it 'registers an offense for `0 == hash.size' do
expect_offense(<<~RUBY)
0 == { a: 1, b: 2 }.size
^^^^^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `0 == size`.
RUBY
expect_correction(<<~RUBY)
{ a: 1, b: 2 }.empty?
RUBY
end
it 'registers an offense for `hash.size != 0`' do
expect_offense(<<~RUBY)
{ a: 1, b: 2 }.size != 0
^^^^^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `size != 0`.
RUBY
expect_correction(<<~RUBY)
!{ a: 1, b: 2 }.empty?
RUBY
end
it 'registers an offense for `0 != hash.size`' do
expect_offense(<<~RUBY)
0 != { a: 1, b: 2 }.size
^^^^^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `0 != size`.
RUBY
expect_correction(<<~RUBY)
!{ a: 1, b: 2 }.empty?
RUBY
end
end
context 'with strings' do
it 'registers an offense for `string.size == 0`' do
expect_offense(<<~RUBY)
"string".size == 0
^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `size == 0`.
RUBY
expect_correction(<<~RUBY)
"string".empty?
RUBY
end
it 'registers an offense for `0 == string.size`' do
expect_offense(<<~RUBY)
0 == "string".size
^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `0 == size`.
RUBY
expect_correction(<<~RUBY)
"string".empty?
RUBY
end
it 'registers an offense for `string.size != 0`' do
expect_offense(<<~RUBY)
"string".size != 0
^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `size != 0`.
RUBY
expect_correction(<<~RUBY)
!"string".empty?
RUBY
end
it 'registers an offense for `0 != string.size`' do
expect_offense(<<~RUBY)
0 != "string".size
^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `0 != size`.
RUBY
expect_correction(<<~RUBY)
!"string".empty?
RUBY
end
end
context 'with collection variables' do
it 'registers an offense for `collection.size == 0`' do
expect_offense(<<~RUBY)
collection.size == 0
^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `size == 0`.
RUBY
expect_correction(<<~RUBY)
collection.empty?
RUBY
end
it 'registers an offense for `0 == collection.size`' do
expect_offense(<<~RUBY)
0 == collection.size
^^^^^^^^^^^^^^^^^^^^ Use `empty?` instead of `0 == size`.
RUBY
expect_correction(<<~RUBY)
collection.empty?
RUBY
end
it 'registers an offense for `collection.size != 0`' do
expect_offense(<<~RUBY)
collection.size != 0
^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `size != 0`.
RUBY
expect_correction(<<~RUBY)
!collection.empty?
RUBY
end
it 'registers an offense for `0 != collection.size`' do
expect_offense(<<~RUBY)
0 != collection.size
^^^^^^^^^^^^^^^^^^^^ Use `!empty?` instead of `0 != size`.
RUBY
expect_correction(<<~RUBY)
!collection.empty?
RUBY
end
end
context 'when name of the variable is `size` or `length`' do
it 'accepts equality check' do
expect_no_offenses('size == 0')
expect_no_offenses('length == 0')
expect_no_offenses('0 == size')
expect_no_offenses('0 == length')
end
it 'accepts comparison' do
expect_no_offenses('size <= 0')
expect_no_offenses('length > 0')
expect_no_offenses('0 <= size')
expect_no_offenses('0 > length')
end
it 'accepts inequality check' do
expect_no_offenses('size != 0')
expect_no_offenses('length != 0')
expect_no_offenses('0 != size')
expect_no_offenses('0 != length')
end
end
context 'when inspecting a File::Stat object' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
File.stat(foo).size == 0
RUBY
end
it 'does not register an offense with ::File' do
expect_no_offenses(<<~RUBY)
::File.stat(foo).size == 0
RUBY
end
end
context 'when inspecting a StringIO object' do
context 'when initialized with a string' do
it 'does not register an offense using `size == 0`' do
expect_no_offenses(<<~RUBY)
StringIO.new('foo').size == 0
RUBY
end
it 'does not register an offense with top-level ::StringIO using `size == 0`' do
expect_no_offenses(<<~RUBY)
::StringIO.new('foo').size == 0
RUBY
end
it 'does not register an offense using `size.zero?`' do
expect_no_offenses(<<~RUBY)
StringIO.new('foo').size.zero?
RUBY
end
it 'does not register an offense with top-level ::StringIO using `size.zero?`' do
expect_no_offenses(<<~RUBY)
::StringIO.new('foo').size.zero?
RUBY
end
end
context 'when initialized without arguments' do
it 'does not register an offense using `size == 0`' do
expect_no_offenses(<<~RUBY)
StringIO.new.size == 0
RUBY
end
it 'does not register an offense with top-level ::StringIO using `size == 0`' do
expect_no_offenses(<<~RUBY)
::StringIO.new.size == 0
RUBY
end
it 'does not register an offense using `size.zero?`' do
expect_no_offenses(<<~RUBY)
StringIO.new.size.zero?
RUBY
end
it 'does not register an offense with top-level ::StringIO using `size.zero?`' do
expect_no_offenses(<<~RUBY)
::StringIO.new.size.zero?
RUBY
end
end
end
context 'when inspecting a File object' do
it 'does not register an offense using `size == 0`' do
expect_no_offenses(<<~RUBY)
File.new('foo').size == 0
RUBY
end
it 'does not register an offense with top-level ::File using `size == 0`' do
expect_no_offenses(<<~RUBY)
::File.new('foo').size == 0
RUBY
end
it 'does not register an offense using `size.zero?`' do
expect_no_offenses(<<~RUBY)
File.new('foo').size.zero?
RUBY
end
it 'does not register an offense with top-level ::File using `size.zero?`' do
expect_no_offenses(<<~RUBY)
::File.new('foo').size.zero?
RUBY
end
end
context 'when inspecting a Tempfile object' do
it 'does not register an offense using `size == 0`' do
expect_no_offenses(<<~RUBY)
Tempfile.new('foo').size == 0
RUBY
end
it 'does not register an offense with top-level ::Tempfile using `size == 0`' do
expect_no_offenses(<<~RUBY)
::Tempfile.new('foo').size == 0
RUBY
end
it 'does not register an offense using `size.zero?`' do
expect_no_offenses(<<~RUBY)
Tempfile.new('foo').size.zero?
RUBY
end
it 'does not register an offense with top-level ::Tempfile using `size.zero?`' do
expect_no_offenses(<<~RUBY)
::Tempfile.new('foo').size.zero?
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/option_hash_spec.rb | spec/rubocop/cop/style/option_hash_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::OptionHash, :config do
let(:cop_config) { { 'SuspiciousParamNames' => suspicious_names } }
let(:suspicious_names) { ['options'] }
it 'registers an offense' do
expect_offense(<<~RUBY)
def some_method(options = {})
^^^^^^^^^^^^ Prefer keyword arguments to options hashes.
puts some_arg
end
RUBY
end
context 'when the last argument is an options hash named something else' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def steep(flavor, duration, config={})
mug = config.fetch(:mug)
prep(flavor, duration, mug)
end
RUBY
end
context 'when the argument name is in the list of suspicious names' do
let(:suspicious_names) { %w[options config] }
it 'registers an offense' do
expect_offense(<<~RUBY)
def steep(flavor, duration, config={})
^^^^^^^^^ Prefer keyword arguments to options hashes.
mug = config.fetch(:mug)
prep(flavor, duration, mug)
end
RUBY
end
end
end
context 'when there are no arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def meditate
puts true
puts true
end
RUBY
end
end
context 'when the last argument is a non-options-hash optional hash' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def cook(instructions, ingredients = { hot: [], cold: [] })
prep(ingredients)
end
RUBY
end
end
context 'when passing options hash to super' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def allowed(foo, options = {})
super
end
RUBY
end
it 'does not register an offense when code exists before call to super' do
expect_no_offenses(<<~RUBY)
def allowed(foo, options = {})
bar
super
end
RUBY
end
it 'does not register an offense when call to super is in a nested block' do
expect_no_offenses(<<~RUBY)
def allowed(foo, options = {})
5.times do
super
end
end
RUBY
end
end
context 'permitted list' do
let(:cop_config) { { 'Allowlist' => %w[to_json] } }
it 'ignores if the method is permitted' do
expect_no_offenses(<<~RUBY)
def to_json(options = {})
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/expand_path_arguments_spec.rb | spec/rubocop/cop/style/expand_path_arguments_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ExpandPathArguments, :config do
it "registers an offense when using `File.expand_path('..', __FILE__)`" do
expect_offense(<<~RUBY)
File.expand_path('..', __FILE__)
^^^^^^^^^^^ Use `expand_path(__dir__)` instead of `expand_path('..', __FILE__)`.
RUBY
expect_correction(<<~RUBY)
File.expand_path(__dir__)
RUBY
end
it "registers an offense when using `File.expand_path('../..', __FILE__)`" do
expect_offense(<<~RUBY)
File.expand_path('../..', __FILE__)
^^^^^^^^^^^ Use `expand_path('..', __dir__)` instead of `expand_path('../..', __FILE__)`.
RUBY
expect_correction(<<~RUBY)
File.expand_path('..', __dir__)
RUBY
end
it "registers an offense when using `File.expand_path('../../..', __FILE__)`" do
expect_offense(<<~RUBY)
File.expand_path('../../..', __FILE__)
^^^^^^^^^^^ Use `expand_path('../..', __dir__)` instead of `expand_path('../../..', __FILE__)`.
RUBY
expect_correction(<<~RUBY)
File.expand_path('../..', __dir__)
RUBY
end
it "registers an offense when using `File.expand_path('.', __FILE__)`" do
expect_offense(<<~RUBY)
File.expand_path('.', __FILE__)
^^^^^^^^^^^ Use `expand_path(__FILE__)` instead of `expand_path('.', __FILE__)`.
RUBY
expect_correction(<<~RUBY)
File.expand_path(__FILE__)
RUBY
end
it "registers an offense when using `File.expand_path('../../lib', __FILE__)`" do
expect_offense(<<~RUBY)
File.expand_path('../../lib', __FILE__)
^^^^^^^^^^^ Use `expand_path('../lib', __dir__)` instead of `expand_path('../../lib', __FILE__)`.
RUBY
expect_correction(<<~RUBY)
File.expand_path('../lib', __dir__)
RUBY
end
it "registers an offense when using `File.expand_path('./../..', __FILE__)`" do
expect_offense(<<~RUBY)
File.expand_path('./../..', __FILE__)
^^^^^^^^^^^ Use `expand_path('..', __dir__)` instead of `expand_path('./../..', __FILE__)`.
RUBY
expect_correction(<<~RUBY)
File.expand_path('..', __dir__)
RUBY
end
it "registers an offense when using `::File.expand_path('./../..', __FILE__)`" do
expect_offense(<<~RUBY)
::File.expand_path('./../..', __FILE__)
^^^^^^^^^^^ Use `expand_path('..', __dir__)` instead of `expand_path('./../..', __FILE__)`.
RUBY
expect_correction(<<~RUBY)
::File.expand_path('..', __dir__)
RUBY
end
it 'registers an offense when using `Pathname(__FILE__).parent.expand_path`' do
expect_offense(<<~RUBY)
Pathname(__FILE__).parent.expand_path
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Pathname(__dir__).expand_path` instead of `Pathname(__FILE__).parent.expand_path`.
RUBY
expect_correction(<<~RUBY)
Pathname(__dir__).expand_path
RUBY
end
it 'registers an offense when using `Pathname.new(__FILE__).parent.expand_path`' do
expect_offense(<<~RUBY)
Pathname.new(__FILE__).parent.expand_path
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Pathname.new(__dir__).expand_path` instead of `Pathname.new(__FILE__).parent.expand_path`.
RUBY
expect_correction(<<~RUBY)
Pathname.new(__dir__).expand_path
RUBY
end
it 'registers an offense when using `::Pathname.new(__FILE__).parent.expand_path`' do
expect_offense(<<~RUBY)
::Pathname.new(__FILE__).parent.expand_path
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Pathname.new(__dir__).expand_path` instead of `Pathname.new(__FILE__).parent.expand_path`.
RUBY
expect_correction(<<~RUBY)
::Pathname.new(__dir__).expand_path
RUBY
end
it 'does not register an offense when using `File.expand_path(__dir__)`' do
expect_no_offenses(<<~RUBY)
File.expand_path(__dir__)
RUBY
end
it "does not register an offense when using `File.expand_path('..', __dir__)`" do
expect_no_offenses(<<~RUBY)
File.expand_path('..', __dir__)
RUBY
end
it 'does not register an offense when using `File.expand_path(__FILE__)`' do
expect_no_offenses(<<~RUBY)
File.expand_path(__FILE__)
RUBY
end
it 'does not register an offense when using `File.expand_path(path, __FILE__)`' do
expect_no_offenses(<<~RUBY)
File.expand_path(path, __FILE__)
RUBY
end
it 'does not register an offense when using ' \
'`File.expand_path("#{path_to_file}.png", __FILE__)`' do
expect_no_offenses(<<~'RUBY')
File.expand_path("#{path_to_file}.png", __FILE__)
RUBY
end
it 'does not register an offense when using `Pathname(__dir__).expand_path`' do
expect_no_offenses(<<~RUBY)
Pathname(__dir__).expand_path
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/invertible_unless_condition_spec.rb | spec/rubocop/cop/style/invertible_unless_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::InvertibleUnlessCondition, :config do
let(:cop_config) do
{
'InverseMethods' => {
:!= => :==,
:even? => :odd?,
:odd? => :even?,
:>= => :<,
:< => :>=,
:zero? => :nonzero?,
# non-standard Rails extensions, but so we can test arguments
:include? => :exclude?,
:exclude? => :include?
}
}
end
context 'when invertible `unless`' do
it 'registers an offense and corrects when using `!` negation' do
expect_offense(<<~RUBY)
foo unless !x
^^^^^^^^^^^^^ Prefer `if x` over `unless !x`.
foo unless !!x
^^^^^^^^^^^^^^ Prefer `if !x` over `unless !!x`.
RUBY
expect_correction(<<~RUBY)
foo if x
foo if !x
RUBY
end
it 'registers an offense and corrects when using simple operator condition' do
expect_offense(<<~RUBY)
foo unless x != y
^^^^^^^^^^^^^^^^^ Prefer `if x == y` over `unless x != y`.
RUBY
expect_correction(<<~RUBY)
foo if x == y
RUBY
end
it 'registers an offense and corrects when using simple method condition' do
expect_offense(<<~RUBY)
foo unless x.odd?
^^^^^^^^^^^^^^^^^ Prefer `if x.even?` over `unless x.odd?`.
RUBY
expect_correction(<<~RUBY)
foo if x.even?
RUBY
end
it 'registers an offense and corrects when using method condition with arguments' do
expect_offense(<<~RUBY)
foo unless array.include?(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `if array.exclude?(value)` over `unless array.include?(value)`.
foo unless array.exclude? value # no parentheses
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `if array.include? value` over `unless array.exclude? value`.
RUBY
expect_correction(<<~RUBY)
foo if array.exclude?(value)
foo if array.include? value # no parentheses
RUBY
end
it 'registers an offense and corrects when using simple bracketed condition' do
expect_offense(<<~RUBY)
foo unless ((x != y))
^^^^^^^^^^^^^^^^^^^^^ Prefer `if ((x == y))` over `unless ((x != y))`.
RUBY
expect_correction(<<~RUBY)
foo if ((x == y))
RUBY
end
it 'registers an offense and corrects when using complex condition' do
expect_offense(<<~RUBY)
foo unless x != y && (((x.odd?) || (((y >= 5)))) || z.zero?)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `if x == y || (((x.even?) && (((y < 5)))) && z.nonzero?)` over `unless x != y && (((x.odd?) || (((y >= 5)))) || z.zero?)`.
RUBY
expect_correction(<<~RUBY)
foo if x == y || (((x.even?) && (((y < 5)))) && z.nonzero?)
RUBY
end
end
it 'registers an offense and corrects methods without arguments called with implicit receivers' do
expect_offense(<<~RUBY)
foo unless odd?
^^^^^^^^^^^^^^^ Prefer `if even?` over `unless odd?`.
RUBY
expect_correction(<<~RUBY)
foo if even?
RUBY
end
it 'registers an offense and corrects parenthesized methods with arguments called with implicit receivers' do
expect_offense(<<~RUBY)
foo unless include?(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `if exclude?(value)` over `unless include?(value)`.
RUBY
expect_correction(<<~RUBY)
foo if exclude?(value)
RUBY
end
it 'registers an offense and corrects unparenthesized methods with arguments called with implicit receivers' do
expect_offense(<<~RUBY)
foo unless include? value
^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `if exclude? value` over `unless include? value`.
RUBY
expect_correction(<<~RUBY)
foo if exclude? value
RUBY
end
it 'does not register an offense when using explicit begin condition' do
expect_no_offenses(<<~RUBY)
foo unless begin x != y end
RUBY
end
it 'does not register an offense when using non invertible `unless`' do
expect_no_offenses(<<~RUBY)
foo unless x != y || x.awesome?
RUBY
end
it 'does not register an offense when checking for inheritance' do
expect_no_offenses(<<~RUBY)
foo unless x < Foo
RUBY
end
it 'does not register an offense when using invertible `if`' do
expect_no_offenses(<<~RUBY)
foo if !condition
RUBY
end
it 'does not register an offense when using empty braces with `unless`' do
expect_no_offenses(<<~RUBY)
foo unless ()
RUBY
end
it 'does not register an offense when using empty braces with inverted `if`' do
expect_no_offenses(<<~RUBY)
foo if !()
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/multiline_method_signature_spec.rb | spec/rubocop/cop/style/multiline_method_signature_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MultilineMethodSignature, :config do
context 'when arguments span a single line' do
context 'when defining an instance method' do
it 'registers an offense and corrects when closing paren is on the following line' do
expect_offense(<<~RUBY)
def foo(bar
^^^^^^^^^^^ Avoid multi-line method signatures.
)
end
RUBY
expect_correction(<<~RUBY)
def foo(bar)
end
RUBY
end
it 'registers an offense and corrects when line break after opening parenthesis' do
expect_offense(<<~RUBY)
class Foo
def foo(
^^^^^^^^ Avoid multi-line method signatures.
arg
)
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
def foo(arg)
end
end
RUBY
end
it 'registers an offense and corrects when closing paren is on the following line' \
'and line break after `def` keyword' do
expect_offense(<<~RUBY)
def
^^^ Avoid multi-line method signatures.
foo(bar
)
end
RUBY
expect_correction(<<~RUBY)
def foo
(bar)
end
RUBY
end
it 'registers an offense and corrects when closing paren is on the following line' \
'and multiple line breaks after `def` keyword' do
expect_offense(<<~RUBY)
def
^^^ Avoid multi-line method signatures.
foo(bar
)
end
RUBY
expect_correction(<<~RUBY)
def foo
(bar)
end
RUBY
end
context 'when method signature is on a single line' do
it 'does not register an offense for parameterized method' do
expect_no_offenses(<<~RUBY)
def foo(bar, baz)
end
RUBY
end
it 'does not register an offense for unparameterized method' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
end
it 'does not register an offense when line break after `def` keyword' do
expect_no_offenses(<<~RUBY)
def
method_name arg; end
RUBY
end
end
context 'when defining a class method' do
context 'when arguments span a single line' do
it 'registers an offense and corrects when closing paren is on the following line' do
expect_offense(<<~RUBY)
def self.foo(bar
^^^^^^^^^^^^^^^^ Avoid multi-line method signatures.
)
end
RUBY
expect_correction(<<~RUBY)
def self.foo(bar)
end
RUBY
end
end
context 'when method signature is on a single line' do
it 'does not register an offense for parameterized method' do
expect_no_offenses(<<~RUBY)
def self.foo(bar, baz)
end
RUBY
end
it 'does not register an offense for unparameterized method' do
expect_no_offenses(<<~RUBY)
def self.foo
end
RUBY
end
end
end
end
context 'when arguments span multiple lines' do
context 'when defining an instance method' do
it 'registers an offense and corrects when `end` is on the following line' do
expect_offense(<<~RUBY)
def foo(bar,
^^^^^^^^^^^^ Avoid multi-line method signatures.
baz)
end
RUBY
expect_correction(<<~RUBY)
def foo(bar, baz)
end
RUBY
end
it 'registers an offense and corrects when `end` is on the same line with last argument' do
expect_offense(<<~RUBY)
def foo(bar,
^^^^^^^^^^^^ Avoid multi-line method signatures.
baz); end
RUBY
expect_correction(<<~RUBY)
def foo(bar, baz); end
RUBY
end
it 'registers an offense and corrects when `end` is on the same line with only closing parentheses' do
expect_offense(<<~RUBY)
def foo(bar,
^^^^^^^^^^^^ Avoid multi-line method signatures.
baz
); end
RUBY
expect_correction(<<~RUBY)
def foo(bar, baz); end
RUBY
end
end
context 'when defining a class method' do
it 'registers an offense and corrects when `end` is on the following line' do
expect_offense(<<~RUBY)
def self.foo(bar,
^^^^^^^^^^^^^^^^^ Avoid multi-line method signatures.
baz)
end
RUBY
expect_correction(<<~RUBY)
def self.foo(bar, baz)
end
RUBY
end
it 'registers an offense and corrects when `end` is on the same line' do
expect_offense(<<~RUBY)
def self.foo(bar,
^^^^^^^^^^^^^^^^^ Avoid multi-line method signatures.
baz); end
RUBY
expect_correction(<<~RUBY)
def self.foo(bar, baz); end
RUBY
end
it 'registers an offense and corrects when `end` is on the same line with only closing parentheses' do
expect_offense(<<~RUBY)
def self.foo(bar,
^^^^^^^^^^^^^^^^^ Avoid multi-line method signatures.
baz
); end
RUBY
expect_correction(<<~RUBY)
def self.foo(bar, baz); end
RUBY
end
end
context 'when correction would exceed maximum line length' do
let(:other_cops) { { 'Layout/LineLength' => { 'Max' => 5 } } }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo(bar,
baz)
end
RUBY
end
end
context 'when correction would not exceed maximum line length' do
let(:other_cops) { { 'Layout/LineLength' => { 'Max' => 25 } } }
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
def foo(bar,
^^^^^^^^^^^^ Avoid multi-line method signatures.
baz)
qux.qux
end
RUBY
expect_correction(<<~RUBY)
def foo(bar, baz)
qux.qux
end
RUBY
end
end
end
context 'when `Layout/LineLength` is disabled' do
let(:other_cops) { { 'Layout/LineLength' => { 'Enabled' => false } } }
it 'registers an offense' do
expect_offense(<<~RUBY)
def foo(bar
^^^^^^^^^^^ Avoid multi-line method signatures.
)
end
RUBY
expect_correction(<<~RUBY)
def foo(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/global_std_stream_spec.rb | spec/rubocop/cop/style/global_std_stream_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::GlobalStdStream, :config do
it 'registers an offense and corrects when using std stream as const' do
expect_offense(<<~RUBY)
STDOUT.puts('hello')
^^^^^^ Use `$stdout` instead of `STDOUT`.
hash = { out: STDOUT, key: value }
^^^^^^ Use `$stdout` instead of `STDOUT`.
def m(out = STDOUT)
^^^^^^ Use `$stdout` instead of `STDOUT`.
out.puts('hello')
end
RUBY
expect_correction(<<~RUBY)
$stdout.puts('hello')
hash = { out: $stdout, key: value }
def m(out = $stdout)
out.puts('hello')
end
RUBY
end
it 'registers an offense when using redundant constant base' do
expect_offense(<<~RUBY)
::STDOUT.puts('hello')
^^^^^^^^ Use `$stdout` instead of `STDOUT`.
RUBY
expect_correction(<<~RUBY)
$stdout.puts('hello')
RUBY
end
it 'does not register an offense when using non std stream const' do
expect_no_offenses(<<~RUBY)
SOME_CONST.puts('hello')
RUBY
end
it 'does not register an offense when assigning std stream const to std stream gvar' do
expect_no_offenses(<<~RUBY)
$stdin = STDIN
RUBY
end
it 'does not register an offense when assigning other const to std stream gvar' do
expect_no_offenses(<<~RUBY)
$stdin = SOME_CONST
RUBY
end
it 'does not register an offense when using namespaced constant' do
expect_no_offenses(<<~RUBY)
Foo::STDOUT.puts('hello')
Foo::Bar::STDOUT.puts('hello')
::Foo::STDOUT.puts('hello')
::Foo::BaR::STDOUT.puts('hello')
foo::STDOUT.puts('hello')
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/slicing_with_range_spec.rb | spec/rubocop/cop/style/slicing_with_range_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SlicingWithRange, :config do
context '<= Ruby 2.5', :ruby25, unsupported_on: :prism do
it 'reports no offense for array slicing end with `-1`' do
expect_no_offenses(<<~RUBY)
ary[1..-1]
RUBY
end
end
context '>= Ruby 2.6', :ruby26 do
it 'reports an offense for slicing with `[0..-1]`' do
expect_offense(<<~RUBY)
ary[0..-1]
^^^^^^^ Remove the useless `[0..-1]`.
RUBY
expect_correction(<<~RUBY)
ary
RUBY
end
it 'does not register an offense for slicing with `[0...-1]`' do
expect_no_offenses(<<~RUBY)
ary[0...-1]
RUBY
end
it 'reports an offense for slicing with `[0..nil]`' do
expect_offense(<<~RUBY)
ary[0..nil]
^^^^^^^^ Remove the useless `[0..nil]`.
RUBY
expect_correction(<<~RUBY)
ary
RUBY
end
it 'reports an offense for slicing with `[0...nil]`' do
expect_offense(<<~RUBY)
ary[0...nil]
^^^^^^^^^ Remove the useless `[0...nil]`.
RUBY
expect_correction(<<~RUBY)
ary
RUBY
end
it 'reports an offense for slicing to `..-1`' do
expect_offense(<<~RUBY)
ary[1..-1]
^^^^^^^ Prefer `[1..]` over `[1..-1]`.
RUBY
expect_correction(<<~RUBY)
ary[1..]
RUBY
end
it 'reports an offense for slicing to `..nil`' do
expect_offense(<<~RUBY)
ary[1..nil]
^^^^^^^^ Prefer `[1..]` over `[1..nil]`.
RUBY
expect_correction(<<~RUBY)
ary[1..]
RUBY
end
it 'reports an offense for slicing to `...nil`' do
expect_offense(<<~RUBY)
ary[1...nil]
^^^^^^^^^ Prefer `[1...]` over `[1...nil]`.
RUBY
expect_correction(<<~RUBY)
ary[1...]
RUBY
end
it 'reports an offense for slicing from expression to `..-1`' do
expect_offense(<<~RUBY)
ary[fetch_start(true).first..-1]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `[fetch_start(true).first..]` over `[fetch_start(true).first..-1]`.
RUBY
expect_correction(<<~RUBY)
ary[fetch_start(true).first..]
RUBY
end
it 'reports no offense for excluding end' do
expect_no_offenses(<<~RUBY)
ary[1...-1]
RUBY
end
it 'reports no offense for other methods' do
expect_no_offenses(<<~RUBY)
ary.push(1..-1)
RUBY
end
it 'reports no offense for array with range inside' do
expect_no_offenses(<<~RUBY)
ranges = [1..-1]
RUBY
end
it 'reports no offense for array slicing start with 0' do
expect_no_offenses(<<~RUBY)
ary[0..42]
RUBY
end
context 'when calling `[]` with a dot' do
it 'reports an offense and removes the entire method call for 0..-1' do
expect_offense(<<~RUBY)
ary.[](0..-1)
^^^^^^^^^^ Remove the useless `.[](0..-1)`.
RUBY
expect_correction(<<~RUBY)
ary
RUBY
end
it 'reports an offense and removes the entire method call for 0..-1 without parens' do
expect_offense(<<~RUBY)
ary.[] 0..-1
^^^^^^^^^ Remove the useless `.[] 0..-1`.
RUBY
expect_correction(<<~RUBY)
ary
RUBY
end
it 'reports an offense and corrects for `1..-1`' do
expect_offense(<<~RUBY)
ary.[](1..-1)
^^^^^^^^^^ Prefer `1..` over `1..-1`.
RUBY
expect_correction(<<~RUBY)
ary.[](1..)
RUBY
end
it 'does not register an offense for `1..-1` without parens' do
expect_no_offenses(<<~RUBY)
ary.[] 1..-1
RUBY
end
end
end
context '>= Ruby 2.7', :ruby27 do
it 'reports an offense for slicing with `[nil..42]`' do
expect_offense(<<~RUBY)
ary[nil..42]
^^^^^^^^^ Prefer `[..42]` over `[nil..42]`.
RUBY
expect_correction(<<~RUBY)
ary[..42]
RUBY
end
it 'does not register an offense for slicing with `[0..42]`' do
expect_no_offenses(<<~RUBY)
ary[0..42]
RUBY
end
it 'reports no offense for startless' do
expect_no_offenses(<<~RUBY)
ary[..-1]
RUBY
end
context 'when calling `[]` with a dot' do
it 'reports an offense and corrects for `nil..42`' do
expect_offense(<<~RUBY)
ary.[](nil..42)
^^^^^^^^^^^^ Prefer `..42` over `nil..42`.
RUBY
expect_correction(<<~RUBY)
ary.[](..42)
RUBY
end
it 'does not register an offense for `nil..42` without parens' do
expect_no_offenses(<<~RUBY)
ary.[] nil..42
RUBY
end
end
context 'when calling `[]` with a safe navigation' do
it 'reports an offense and removes the entire method call for 0..-1' do
expect_offense(<<~RUBY)
ary&.[](0..-1)
^^^^^^^^^^^ Remove the useless `&.[](0..-1)`.
RUBY
expect_correction(<<~RUBY)
ary
RUBY
end
it 'reports an offense and removes the entire method call for 0..-1 without parens' do
expect_offense(<<~RUBY)
ary.[] 0..-1
^^^^^^^^^ Remove the useless `.[] 0..-1`.
RUBY
expect_correction(<<~RUBY)
ary
RUBY
end
it 'reports an offense and corrects for `1..-1`' do
expect_offense(<<~RUBY)
ary.[](1..-1)
^^^^^^^^^^ Prefer `1..` over `1..-1`.
RUBY
expect_correction(<<~RUBY)
ary.[](1..)
RUBY
end
it 'does not register an offense for `1..-1` without parens' do
expect_no_offenses(<<~RUBY)
ary.[] 1..-1
RUBY
end
it 'reports an offense and corrects for `nil..42`' do
expect_offense(<<~RUBY)
ary&.[](nil..42)
^^^^^^^^^^^^^ Prefer `..42` over `nil..42`.
RUBY
expect_correction(<<~RUBY)
ary&.[](..42)
RUBY
end
it 'does not register an offense for `nil..42` without parens' do
expect_no_offenses(<<~RUBY)
ary&.[] nil..42
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/data_inheritance_spec.rb | spec/rubocop/cop/style/data_inheritance_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::DataInheritance, :config do
context 'Ruby >= 3.2', :ruby32 do
it 'registers an offense when extending instance of `Data.define`' do
expect_offense(<<~RUBY)
class Person < Data.define(:first_name, :last_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Data.define`. Use a block to customize the class.
def foo; end
end
RUBY
expect_correction(<<~RUBY)
Person = Data.define(:first_name, :last_name) do
def foo; end
end
RUBY
end
it 'registers an offense when extending instance of `::Data.define`' do
expect_offense(<<~RUBY)
class Person < ::Data.define(:first_name, :last_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Data.define`. Use a block to customize the class.
def foo; end
end
RUBY
expect_correction(<<~RUBY)
Person = ::Data.define(:first_name, :last_name) do
def foo; end
end
RUBY
end
it 'registers an offense when extending instance of `Data.define` with do ... end' do
expect_offense(<<~RUBY)
class Person < Data.define(:first_name, :last_name) do end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Data.define`. Use a block to customize the class.
end
RUBY
expect_correction(<<~RUBY)
Person = Data.define(:first_name, :last_name) do
end
RUBY
end
it 'registers an offense when extending instance of `Data.define` without `do` ... `end` and class body is empty' do
expect_offense(<<~RUBY)
class Person < Data.define(:first_name, :last_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Data.define`. Use a block to customize the class.
end
RUBY
expect_correction(<<~RUBY)
Person = Data.define(:first_name, :last_name)
RUBY
end
it 'registers an offense when extending instance of `Data.define` without `do` ... `end` and class body is empty and single line definition' do
expect_offense(<<~RUBY)
class Person < Data.define(:first_name, :last_name); end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Data.define`. Use a block to customize the class.
RUBY
expect_correction(<<~RUBY)
Person = Data.define(:first_name, :last_name)
RUBY
end
it 'registers an offense when extending instance of `::Data.define` with do ... end' do
expect_offense(<<~RUBY)
class Person < ::Data.define(:first_name, :last_name) do end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Data.define`. Use a block to customize the class.
end
RUBY
expect_correction(<<~RUBY)
Person = ::Data.define(:first_name, :last_name) do
end
RUBY
end
it 'registers an offense when extending instance of `Data.define` when there is a comment ' \
'before class declaration' do
expect_offense(<<~RUBY)
# comment
class Person < Data.define(:first_name, :last_name) do end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Data.define`. Use a block to customize the class.
end
RUBY
expect_correction(<<~RUBY)
# comment
Person = Data.define(:first_name, :last_name) do
end
RUBY
end
it 'accepts plain class' do
expect_no_offenses(<<~RUBY)
class Person
end
RUBY
end
it 'accepts extending DelegateClass' do
expect_no_offenses(<<~RUBY)
class Person < DelegateClass(Animal)
end
RUBY
end
it 'accepts assignment to `Data.define`' do
expect_no_offenses('Person = Data.define(:first_name, :last_name)')
end
it 'accepts assignment to `::Data.define`' do
expect_no_offenses('Person = ::Data.define(:first_name, :last_name)')
end
it 'accepts assignment to block form of `Data.define`' do
expect_no_offenses(<<~RUBY)
Person = Data.define(:first_name, :last_name) do
def age
42
end
end
RUBY
end
end
context 'Ruby <= 3.1', :ruby31, unsupported_on: :prism do
it 'accepts extending instance of `Data.define`' do
expect_no_offenses(<<~RUBY)
class Person < Data.define(:first_name, :last_name)
def foo; end
end
RUBY
end
it 'accepts extending instance of `::Data.define`' do
expect_no_offenses(<<~RUBY)
class Person < ::Data.define(:first_name, :last_name)
def foo; end
end
RUBY
end
it 'accepts extending instance of `Data.define` with do ... end' do
expect_no_offenses(<<~RUBY)
class Person < Data.define(:first_name, :last_name) do end
end
RUBY
end
it 'accepts extending instance of `Data.define` without `do` ... `end` and class body is empty' do
expect_no_offenses(<<~RUBY)
class Person < Data.define(:first_name, :last_name)
end
RUBY
end
it 'accepts extending instance of `Data.define` without `do` ... `end` and class body is empty and single line definition' do
expect_no_offenses(<<~RUBY)
class Person < Data.define(:first_name, :last_name); end
RUBY
end
it 'accepts extending instance of `::Data.define` with do ... end' do
expect_no_offenses(<<~RUBY)
class Person < ::Data.define(:first_name, :last_name) do end
end
RUBY
end
it 'accepts extending instance of `Data.define` when there is a comment ' \
'before class declaration' do
expect_no_offenses(<<~RUBY)
# comment
class Person < Data.define(:first_name, :last_name) do end
end
RUBY
end
it 'accepts plain class' do
expect_no_offenses(<<~RUBY)
class Person
end
RUBY
end
it 'accepts extending DelegateClass' do
expect_no_offenses(<<~RUBY)
class Person < DelegateClass(Animal)
end
RUBY
end
it 'accepts assignment to `Data.define`' do
expect_no_offenses('Person = Data.define(:first_name, :last_name)')
end
it 'accepts assignment to `::Data.define`' do
expect_no_offenses('Person = ::Data.define(:first_name, :last_name)')
end
it 'accepts assignment to block form of `Data.define`' do
expect_no_offenses(<<~RUBY)
Person = Data.define(:first_name, :last_name) do
def age
42
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/method_called_on_do_end_block_spec.rb | spec/rubocop/cop/style/method_called_on_do_end_block_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MethodCalledOnDoEndBlock, :config do
context 'with a multi-line do..end block' do
it 'registers an offense for a chained call' do
expect_offense(<<~RUBY)
a do
b
end.c
^^^^^ Avoid chaining a method call on a do...end block.
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense for a chained call' do
expect_offense(<<~RUBY)
a do
b
end&.c
^^^^^^ Avoid chaining a method call on a do...end block.
RUBY
end
end
it 'accepts it if there is no chained call' do
expect_no_offenses(<<~RUBY)
a do
b
end
RUBY
end
it 'accepts a chained block' do
expect_no_offenses(<<~RUBY)
a do
b
end.c do
d
end
RUBY
end
end
context 'with a single-line do..end block' do
it 'registers an offense for a chained call' do
expect_offense(<<~RUBY)
a do b end.c
^^^^^ Avoid chaining a method call on a do...end block.
RUBY
end
it 'accepts a single-line do..end block with a chained block' do
expect_no_offenses('a do b end.c do d end')
end
end
context 'with a {} block' do
it 'accepts a multi-line block with a chained call' do
expect_no_offenses(<<~RUBY)
a {
b
}.c
RUBY
end
it 'accepts a single-line block with a chained call' do
expect_no_offenses('a { b }.c')
end
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for a chained call' do
expect_offense(<<~RUBY)
a do
_1
end.c
^^^^^ Avoid chaining a method call on a do...end block.
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for a chained call' do
expect_offense(<<~RUBY)
a do
it
end.c
^^^^^ Avoid chaining a method call on a do...end block.
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/class_methods_spec.rb | spec/rubocop/cop/style/class_methods_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ClassMethods, :config do
it 'registers an offense for methods using a class name' do
expect_offense(<<~RUBY)
class Test
def Test.some_method
^^^^ Use `self.some_method` instead of `Test.some_method`.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
class Test
def self.some_method
do_something
end
end
RUBY
end
it 'registers an offense for methods using a module name' do
expect_offense(<<~RUBY)
module Test
def Test.some_method
^^^^ Use `self.some_method` instead of `Test.some_method`.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
module Test
def self.some_method
do_something
end
end
RUBY
end
it 'does not register an offense for methods using self' do
expect_no_offenses(<<~RUBY)
module Test
def self.some_method
do_something
end
end
RUBY
end
it 'does not register an offense for other top-level singleton methods' do
expect_no_offenses(<<~RUBY)
class Test
X = Something.new
def X.some_method
do_something
end
end
RUBY
end
it 'does not register an offense outside class/module bodies' do
expect_no_offenses(<<~RUBY)
def Test.some_method
do_something
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/each_for_simple_loop_spec.rb | spec/rubocop/cop/style/each_for_simple_loop_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EachForSimpleLoop, :config do
it 'does not register offense if range starting point is not constant' do
expect_no_offenses('(a..10).each {}')
end
it 'does not register offense if range endpoint is not constant' do
expect_no_offenses('(0..b).each {}')
end
context 'with inline block with no parameters' do
it 'autocorrects an offense' do
expect_offense(<<~RUBY)
(0...10).each { do_something }
^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
RUBY
expect_correction(<<~RUBY)
10.times { do_something }
RUBY
end
end
context 'with inline block with parameters' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
(0...10).each { |n| do_something(n) }
RUBY
end
end
context 'with multiline block with no parameters' do
it 'autocorrects an offense' do
expect_offense(<<~RUBY)
(0...10).each do
^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
do_something
end
RUBY
expect_correction(<<~RUBY)
10.times do
do_something
end
RUBY
end
end
context 'with multiline block with parameters' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
(0...10).each do |n|
do_something(n)
end
RUBY
end
end
context 'when using safe navigation operator' do
context 'with inline block with no parameters' do
it 'autocorrects an offense' do
expect_offense(<<~RUBY)
(0...10)&.each { do_something }
^^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
RUBY
expect_correction(<<~RUBY)
10.times { do_something }
RUBY
end
end
context 'with inline block with parameters' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
(0...10)&.each { |n| do_something(n) }
RUBY
end
end
context 'with multiline block with no parameters' do
it 'autocorrects an offense' do
expect_offense(<<~RUBY)
(0...10)&.each do
^^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
do_something
end
RUBY
expect_correction(<<~RUBY)
10.times do
do_something
end
RUBY
end
end
context 'with multiline block with parameters' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
(0...10)&.each do |n|
do_something(n)
end
RUBY
end
end
end
it 'does not register offense for character range' do
expect_no_offenses("('a'..'b').each {}")
end
context 'when using an inclusive end range' do
it 'autocorrects the source with inline block' do
expect_offense(<<~RUBY)
(0..10).each {}
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
RUBY
expect_correction(<<~RUBY)
11.times {}
RUBY
end
it 'autocorrects the source with multiline block' do
expect_offense(<<~RUBY)
(0..10).each do
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
11.times do
end
RUBY
end
it 'autocorrects the range not starting with zero' do
expect_offense(<<~RUBY)
(3..7).each do
^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
5.times do
end
RUBY
end
context 'when using safe navigation operator' do
it 'autocorrects the range not starting with zero' do
expect_offense(<<~RUBY)
(3..7)&.each do
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
5.times do
end
RUBY
end
end
it 'does not register offense for range not starting with zero and using param' do
expect_no_offenses(<<~RUBY)
(3..7).each do |n|
end
RUBY
end
end
context 'when using an exclusive end range' do
it 'autocorrects the source with inline block' do
expect_offense(<<~RUBY)
(0...10).each {}
^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
RUBY
expect_correction(<<~RUBY)
10.times {}
RUBY
end
it 'autocorrects the source with multiline block' do
expect_offense(<<~RUBY)
(0...10).each do
^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
10.times do
end
RUBY
end
it 'autocorrects the range not starting with zero' do
expect_offense(<<~RUBY)
(3...7).each do
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY
expect_correction(<<~RUBY)
4.times do
end
RUBY
end
it 'does not register offense for range not starting with zero and using param' do
expect_no_offenses(<<~RUBY)
(3...7).each do |n|
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/special_global_vars_spec.rb | spec/rubocop/cop/style/special_global_vars_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SpecialGlobalVars, :config do
context 'when style is use_english_names' do
context 'when add require English is disabled' do
let(:cop_config) do
{
'EnforcedStyle' => 'use_english_names',
'RequireEnglish' => false
}
end
it 'registers an offense for $:' do
expect_offense(<<~RUBY)
puts $:
^^ Prefer `$LOAD_PATH` over `$:`.
RUBY
expect_correction(<<~RUBY)
puts $LOAD_PATH
RUBY
end
it 'registers an offense for $"' do
expect_offense(<<~RUBY)
puts $"
^^ Prefer `$LOADED_FEATURES` over `$"`.
RUBY
expect_correction(<<~RUBY)
puts $LOADED_FEATURES
RUBY
end
it 'registers an offense for $0' do
expect_offense(<<~RUBY)
puts $0
^^ Prefer `$PROGRAM_NAME` over `$0`.
RUBY
expect_correction(<<~RUBY)
puts $PROGRAM_NAME
RUBY
end
it 'registers an offense for $$' do
expect_offense(<<~RUBY)
puts $$
^^ Prefer `$PROCESS_ID` or `$PID` from the stdlib 'English' module (don't forget to require it) over `$$`.
RUBY
expect_correction(<<~RUBY)
puts $PROCESS_ID
RUBY
end
it 'is clear about variables from the English library vs those not' do
expect_offense(<<~RUBY)
puts $*
^^ Prefer `$ARGV` from the stdlib 'English' module (don't forget to require it) or `ARGV` over `$*`.
RUBY
expect_correction(<<~RUBY)
puts $ARGV
RUBY
end
it 'does not register an offense for backrefs like $1' do
expect_no_offenses('puts $1')
end
it 'autocorrects $/ to $INPUT_RECORD_SEPARATOR' do
expect_offense(<<~RUBY)
$/
^^ Prefer `$INPUT_RECORD_SEPARATOR` or `$RS` from the stdlib 'English' module (don't forget to require it) over `$/`.
RUBY
expect_correction(<<~RUBY)
$INPUT_RECORD_SEPARATOR
RUBY
end
it 'autocorrects #$: to #{$LOAD_PATH}' do
expect_offense(<<~'RUBY')
"#$:"
^^ Prefer `$LOAD_PATH` over `$:`.
RUBY
expect_correction(<<~'RUBY')
"#{$LOAD_PATH}"
RUBY
end
it 'autocorrects #{$!} to #{$ERROR_INFO}' do
expect_offense(<<~'RUBY')
"#{$!}"
^^ Prefer `$ERROR_INFO` from the stdlib 'English' module (don't forget to require it) over `$!`.
RUBY
expect_correction(<<~'RUBY')
"#{$ERROR_INFO}"
RUBY
end
it 'generates correct auto-config when Perl variable names are used' do
expect_offense(<<~RUBY)
$0
^^ Prefer `$PROGRAM_NAME` over `$0`.
RUBY
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'use_perl_names')
expect_correction(<<~RUBY)
$PROGRAM_NAME
RUBY
end
it 'generates correct auto-config when mixed styles are used' do
expect_offense(<<~RUBY)
$!; $ERROR_INFO
^^ Prefer `$ERROR_INFO` from the stdlib 'English' module (don't forget to require it) over `$!`.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
$ERROR_INFO; $ERROR_INFO
RUBY
end
end
context 'when add require English is enabled' do
let(:cop_config) do
{
'EnforcedStyle' => 'use_english_names',
'RequireEnglish' => true
}
end
context 'when English has not been required at top-level' do
it 'adds require English for $$' do
expect_offense(<<~RUBY)
puts $$
^^ Prefer `$PROCESS_ID` or `$PID` from the stdlib 'English' module (don't forget to require it) over `$$`.
RUBY
expect_correction(<<~RUBY)
require 'English'
puts $PROCESS_ID
RUBY
end
it 'adds require English for $$ in nested code' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
x = true
if x
puts $$
^^ Prefer `$PROCESS_ID` or `$PID` from the stdlib 'English' module (don't forget to require it) over `$$`.
end
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
require 'English'
x = true
if x
puts $PROCESS_ID
end
RUBY
end
it 'adds require English for twice `$*` in nested code' do
expect_offense(<<~RUBY)
# frozen_string_literal: true
puts $*[0]
^^ Prefer `$ARGV` from the stdlib 'English' module (don't forget to require it) or `ARGV` over `$*`.
puts $*[1]
^^ Prefer `$ARGV` from the stdlib 'English' module (don't forget to require it) or `ARGV` over `$*`.
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: true
require 'English'
puts $ARGV[0]
puts $ARGV[1]
RUBY
end
it 'does not add for replacement outside of English lib' do
expect_offense(<<~RUBY)
puts $0
^^ Prefer `$PROGRAM_NAME` over `$0`.
RUBY
expect_correction(<<~RUBY)
puts $PROGRAM_NAME
RUBY
end
end
context 'when English is already required at top-level' do
it 'leaves require English alone for $$' do
expect_offense(<<~RUBY)
require 'English'
puts $$
^^ Prefer `$PROCESS_ID` or `$PID` from the stdlib 'English' module (don't forget to require it) over `$$`.
RUBY
expect_correction(<<~RUBY)
require 'English'
puts $PROCESS_ID
RUBY
end
it 'moves require English above replacement' do
expect_offense(<<~RUBY)
puts $$
^^ Prefer `$PROCESS_ID` or `$PID` from the stdlib 'English' module (don't forget to require it) over `$$`.
require 'English'
RUBY
expect_correction(<<~RUBY)
require 'English'
puts $PROCESS_ID
RUBY
end
end
end
end
context 'when style is use_perl_names' do
let(:cop_config) { { 'EnforcedStyle' => 'use_perl_names' } }
it 'registers an offense for $LOAD_PATH' do
expect_offense(<<~RUBY)
puts $LOAD_PATH
^^^^^^^^^^ Prefer `$:` over `$LOAD_PATH`.
RUBY
expect_correction(<<~RUBY)
puts $:
RUBY
end
it 'registers an offense for $LOADED_FEATURES' do
expect_offense(<<~RUBY)
puts $LOADED_FEATURES
^^^^^^^^^^^^^^^^ Prefer `$"` over `$LOADED_FEATURES`.
RUBY
expect_correction(<<~RUBY)
puts $"
RUBY
end
it 'registers an offense for $PROGRAM_NAME' do
expect_offense(<<~RUBY)
puts $PROGRAM_NAME
^^^^^^^^^^^^^ Prefer `$0` over `$PROGRAM_NAME`.
RUBY
expect_correction(<<~RUBY)
puts $0
RUBY
end
it 'registers an offense for $PID' do
expect_offense(<<~RUBY)
puts $PID
^^^^ Prefer `$$` over `$PID`.
RUBY
expect_correction(<<~RUBY)
puts $$
RUBY
end
it 'registers an offense for $PROCESS_ID' do
expect_offense(<<~RUBY)
puts $PROCESS_ID
^^^^^^^^^^^ Prefer `$$` over `$PROCESS_ID`.
RUBY
expect_correction(<<~RUBY)
puts $$
RUBY
end
it 'does not register an offense for backrefs like $1' do
expect_no_offenses('puts $1')
end
it 'autocorrects $INPUT_RECORD_SEPARATOR to $/' do
expect_offense(<<~RUBY)
$INPUT_RECORD_SEPARATOR
^^^^^^^^^^^^^^^^^^^^^^^ Prefer `$/` over `$INPUT_RECORD_SEPARATOR`.
RUBY
expect_correction(<<~RUBY)
$/
RUBY
end
it 'autocorrects #{$LOAD_PATH} to #$:' do
expect_offense(<<~'RUBY')
"#{$LOAD_PATH}"
^^^^^^^^^^ Prefer `$:` over `$LOAD_PATH`.
RUBY
expect_correction(<<~'RUBY')
"#$:"
RUBY
end
end
context 'when style is use_builtin_english_names' do
let(:cop_config) { { 'EnforcedStyle' => 'use_builtin_english_names' } }
it 'does not register an offense for builtin names' do
expect_no_offenses(<<~RUBY)
puts $LOAD_PATH
puts $LOADED_FEATURES
puts $PROGRAM_NAME
RUBY
end
it 'autocorrects non-preferred builtin names' do
expect_offense(<<~RUBY)
puts $:
^^ Prefer `$LOAD_PATH` over `$:`.
puts $"
^^ Prefer `$LOADED_FEATURES` over `$"`.
puts $0
^^ Prefer `$PROGRAM_NAME` over `$0`.
RUBY
expect_correction(<<~RUBY)
puts $LOAD_PATH
puts $LOADED_FEATURES
puts $PROGRAM_NAME
RUBY
end
it 'does not register an offense for Perl names' do
expect_no_offenses(<<~RUBY)
puts $?
puts $*
RUBY
end
it 'does not register an offense for backrefs like $1' do
expect_no_offenses('puts $1')
end
it 'generates correct auto-config when Perl variable names are used' do
expect_offense(<<~RUBY)
$0
^^ Prefer `$PROGRAM_NAME` over `$0`.
RUBY
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'use_perl_names')
expect_correction(<<~RUBY)
$PROGRAM_NAME
RUBY
end
it 'generates correct auto-config when mixed styles are used' do
expect_offense(<<~RUBY)
$0; $PROGRAM_NAME
^^ Prefer `$PROGRAM_NAME` over `$0`.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
$PROGRAM_NAME; $PROGRAM_NAME
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_current_directory_in_path_spec.rb | spec/rubocop/cop/style/redundant_current_directory_in_path_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantCurrentDirectoryInPath, :config do
it "registers an offense when using a current directory path in `require_relative '...'`" do
expect_offense(<<~RUBY)
require_relative './path/to/feature'
^^ Remove the redundant current directory path.
RUBY
expect_correction(<<~RUBY)
require_relative 'path/to/feature'
RUBY
end
it "registers an offense when using a current directory path with string interpolation in `require_relative '...'`" do
expect_offense(<<~'RUBY')
require_relative './path/#{to}/feature'
^^ Remove the redundant current directory path.
RUBY
expect_correction(<<~'RUBY')
require_relative 'path/#{to}/feature'
RUBY
end
it "registers an offense when using a complex current directory path in `require_relative '...'`" do
expect_offense(<<~RUBY)
require_relative './//./../path/to/feature'
^^^^ Remove the redundant current directory path.
RUBY
expect_correction(<<~RUBY)
require_relative '../path/to/feature'
RUBY
end
it 'registers an offense when using a current directory path in `require_relative %q(...)`' do
expect_offense(<<~RUBY)
require_relative %q(./path/to/feature)
^^ Remove the redundant current directory path.
RUBY
expect_correction(<<~RUBY)
require_relative %q(path/to/feature)
RUBY
end
it 'does not register an offense when using a parent directory path in `require_relative`' do
expect_no_offenses(<<~RUBY)
require_relative '../path/to/feature'
RUBY
end
it 'does not register an offense when using a path that starts with a dot in `require_relative`' do
expect_no_offenses(<<~RUBY)
require_relative '.path'
RUBY
end
it 'does not register an offense when not using a one-character path in `require_relative`' do
expect_no_offenses(<<~RUBY)
require_relative 'p/t/feature'
RUBY
end
it 'does not register an offense when not using a current directory path in `require_relative`' do
expect_no_offenses(<<~RUBY)
require_relative 'path/to/feature'
RUBY
end
it 'does not register an offense when not using a current directory path with string interpolation in `require_relative`' do
expect_no_offenses(<<~'RUBY')
require_relative "path/#{to}/feature"
RUBY
end
it 'does not register an offense when not using a current directory path in not `require_relative`' do
expect_no_offenses(<<~RUBY)
do_something './path/to/feature'
RUBY
end
it 'does not register an offense when a method with no arguments is used' do
expect_no_offenses(<<~RUBY)
do_something
RUBY
end
it 'does not register an offense when a `require_relative` with no arguments is used' do
expect_no_offenses(<<~RUBY)
require_relative
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_comparison_spec.rb | spec/rubocop/cop/style/nil_comparison_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NilComparison, :config do
context 'configured with predicate preferred' do
let(:cop_config) { { 'EnforcedStyle' => 'predicate' } }
it 'registers an offense for == nil' do
expect_offense(<<~RUBY)
x == nil
^^ Prefer the use of the `nil?` predicate.
RUBY
expect_correction(<<~RUBY)
x.nil?
RUBY
end
it 'registers an offense for === nil' do
expect_offense(<<~RUBY)
x === nil
^^^ Prefer the use of the `nil?` predicate.
RUBY
expect_correction(<<~RUBY)
x.nil?
RUBY
end
it 'registers and corrects an offense when using `x == nil` as a guard condition' do
expect_offense(<<~RUBY)
bar if x == nil
^^ Prefer the use of the `nil?` predicate.
RUBY
expect_correction(<<~RUBY)
bar if x.nil?
RUBY
end
it 'registers and corrects an offense when using `x.==(nil)` syntax' do
expect_offense(<<~RUBY)
x.==(nil)
^^ Prefer the use of the `nil?` predicate.
RUBY
expect_correction(<<~RUBY)
x.nil?
RUBY
end
it 'registers and corrects an offense when using `x.===(nil)` syntax' do
expect_offense(<<~RUBY)
x.===(nil)
^^^ Prefer the use of the `nil?` predicate.
RUBY
expect_correction(<<~RUBY)
x.nil?
RUBY
end
end
context 'configured with comparison preferred' do
let(:cop_config) { { 'EnforcedStyle' => 'comparison' } }
it 'registers an offense for nil?' do
expect_offense(<<~RUBY)
x.nil?
^^^^ Prefer the use of the `==` comparison.
RUBY
expect_correction(<<~RUBY)
x == nil
RUBY
end
it 'registers and corrects an offense for `!x.nil?`' do
expect_offense(<<~RUBY)
!x.nil?
^^^^ Prefer the use of the `==` comparison.
RUBY
expect_correction(<<~RUBY)
!(x == nil)
RUBY
end
it 'registers no offense when there is no receiver' do
expect_no_offenses('nil?')
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/keyword_parameters_order_spec.rb | spec/rubocop/cop/style/keyword_parameters_order_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::KeywordParametersOrder, :config do
it 'registers an offense and corrects when `kwoptarg` is before `kwarg`' do
expect_offense(<<~RUBY)
def m(arg, optional: 1, required:)
^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
end
RUBY
expect_correction(<<~RUBY)
def m(arg, required:, optional: 1)
end
RUBY
end
it 'registers an offense and corrects when `kwoptarg` is before `kwarg` and argument parentheses omitted' do
expect_offense(<<~RUBY)
def m arg, optional: 1, required:
^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
do_something
end
RUBY
expect_correction(<<~RUBY)
def m arg, required:, optional: 1
do_something
end
RUBY
end
it 'registers an offense and corrects when multiple `kwoptarg` are before `kwarg` and argument parentheses omitted' do
expect_offense(<<~RUBY)
def m arg, optional1: 1, optional2: 2, required:
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
do_something
end
RUBY
expect_correction(<<~RUBY)
def m arg, required:, optional1: 1, optional2: 2
do_something
end
RUBY
end
it 'registers an offense and corrects when multiple `kwoptarg`s are interleaved with `kwarg`s' do
expect_offense(<<~RUBY)
def m(arg, optional1: 1, required1:, optional2: 2, required2:, **rest, &block)
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
end
RUBY
expect_correction(<<~RUBY)
def m(arg, required1:, required2:, optional1: 1, optional2: 2, **rest, &block)
end
RUBY
end
it 'registers an offense and corrects when multiple `kwoptarg`s are interleaved with `kwarg`s' \
'and last argument is `kwrestarg` and argument parentheses omitted' do
expect_offense(<<~RUBY)
def m arg, optional1: 1, required1:, optional2: 2, required2:, **rest
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
do_something
end
RUBY
expect_correction(<<~RUBY)
def m arg, required1:, required2:, optional1: 1, optional2: 2, **rest
do_something
end
RUBY
end
it 'registers an offense and corrects when multiple `kwoptarg`s are interleaved with `kwarg`s' \
'and last argument is `blockarg` and argument parentheses omitted' do
expect_offense(<<~RUBY)
def m arg, optional1: 1, required1:, optional2: 2, required2:, **rest, &block
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
do_something
end
RUBY
expect_correction(<<~RUBY)
def m arg, required1:, required2:, optional1: 1, optional2: 2, **rest, &block
do_something
end
RUBY
end
it 'registers an offense but does not autocorrect when the argument range contains comments' do
expect_offense(<<~RUBY)
def foo(optional: 123,
^^^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
# Some explanation
required:)
end
RUBY
expect_no_corrections
end
it 'does not register an offense when there are no `kwoptarg`s before `kwarg`s' do
expect_no_offenses(<<~RUBY)
def m(arg, required:, optional: 1)
end
RUBY
end
context 'when using block keyword parameters' do
it 'registers an offense and corrects when `kwoptarg` is before `kwarg`' do
expect_offense(<<~RUBY)
m(arg) do |block_arg, optional: 1, required:|
^^^^^^^^^^^ Place optional keyword parameters at the end of the parameters list.
end
RUBY
expect_correction(<<~RUBY)
m(arg) do |block_arg, required:, optional: 1|
end
RUBY
end
it 'does not register an offense when there are no `kwoptarg`s before `kwarg`s' do
expect_no_offenses(<<~RUBY)
m(arg) do |block_arg, required:, optional: 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/redundant_line_continuation_spec.rb | spec/rubocop/cop/style/redundant_line_continuation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantLineContinuation, :config do
context 'when a line continuation precedes the arguments to an unparenthesized method call' do
shared_examples 'no offense' do |argument|
it "does not register an offense when the first argument is `#{argument}`" do
expect_no_offenses(<<~RUBY)
foo \\
#{argument}
RUBY
end
it "does not register an offense for `super` when the first argument is `#{argument}`" do
expect_no_offenses(<<~RUBY)
super \\
#{argument}
RUBY
end
end
shared_examples 'no forwarding offense' do |argument, *metadata|
it "does not register an offense when the first argument is `#{argument}", *metadata do
expect_no_offenses(<<~RUBY)
def a(#{argument})
b \\
#{argument}; # the semicolon is necessary or ruby cannot parse
end
RUBY
end
it "does not register an offense with superwhen the first argument is `#{argument}", *metadata do
expect_no_offenses(<<~RUBY)
def a(#{argument})
super \\
#{argument}; # the semicolon is necessary or ruby cannot parse
end
RUBY
end
end
it_behaves_like 'no offense', '"string"'
it_behaves_like 'no offense', '"#{dynamic string}"'
it_behaves_like 'no offense', '`xstring`'
it_behaves_like 'no offense', ':symbol'
it_behaves_like 'no offense', '?c'
it_behaves_like 'no offense', '123'
it_behaves_like 'no offense', 'bar'
it_behaves_like 'no offense', '!bar'
it_behaves_like 'no offense', '..5'
it_behaves_like 'no offense', '...5'
it_behaves_like 'no offense', '~5'
it_behaves_like 'no offense', '->() {}'
it_behaves_like 'no offense', 'proc {}'
it_behaves_like 'no offense', '*bar'
it_behaves_like 'no offense', '**bar'
it_behaves_like 'no offense', '&block'
it_behaves_like 'no offense', '+1'
it_behaves_like 'no offense', '-1'
it_behaves_like 'no offense', '+bar'
it_behaves_like 'no offense', '-bar'
it_behaves_like 'no offense', '/bar/'
it_behaves_like 'no offense', '%[bar]'
it_behaves_like 'no offense', '%w[bar]'
it_behaves_like 'no offense', '%W[bar]'
it_behaves_like 'no offense', '%i[bar]'
it_behaves_like 'no offense', '%I[bar]'
it_behaves_like 'no offense', '%r[bar]'
it_behaves_like 'no offense', '%x[bar]'
it_behaves_like 'no offense', '%s[bar]'
it_behaves_like 'no offense', 'defined?(bar)'
it_behaves_like 'no forwarding offense', '...'
it_behaves_like 'no forwarding offense', '&', :ruby31
it_behaves_like 'no forwarding offense', '*', :ruby32
it_behaves_like 'no forwarding offense', '**', :ruby32
end
it 'registers an offense when redundant line continuations for define class' do
expect_offense(<<~'RUBY')
class Foo \
^ Redundant line continuation.
end
RUBY
expect_correction(<<~RUBY)
class Foo#{trailing_whitespace}
end
RUBY
end
it 'registers an offense when redundant line continuations for define method' do
expect_offense(<<~'RUBY')
def foo(bar, \
^ Redundant line continuation.
baz)
end
RUBY
expect_correction(<<~RUBY)
def foo(bar,#{trailing_whitespace}
baz)
end
RUBY
end
it 'registers an offense when redundant line continuations for define class method' do
expect_offense(<<~'RUBY')
def self.foo(bar, \
^ Redundant line continuation.
baz)
end
RUBY
expect_correction(<<~RUBY)
def self.foo(bar,#{trailing_whitespace}
baz)
end
RUBY
end
it 'registers an offense when redundant line continuations for block' do
expect_offense(<<~'RUBY')
foo do \
^ Redundant line continuation.
bar
end
RUBY
expect_correction(<<~RUBY)
foo do#{trailing_whitespace}
bar
end
RUBY
end
it 'registers an offense when redundant line continuations for a block are used, ' \
'especially without parentheses around first argument' do
expect_offense(<<~'RUBY')
let :foo do \
^ Redundant line continuation.
foo(bar, \
^ Redundant line continuation.
baz)
end
RUBY
expect_correction(<<~RUBY)
let :foo do#{trailing_whitespace}
foo(bar,#{trailing_whitespace}
baz)
end
RUBY
end
it 'registers an offense when redundant line continuations for method chain' do
expect_offense(<<~'RUBY')
foo. \
^ Redundant line continuation.
bar
foo \
^ Redundant line continuation.
.bar \
^ Redundant line continuation.
.baz
RUBY
expect_correction(<<~RUBY)
foo.#{trailing_whitespace}
bar
foo#{trailing_whitespace}
.bar#{trailing_whitespace}
.baz
RUBY
end
it 'registers an offense when redundant line continuations for method chain with safe navigation' do
expect_offense(<<~'RUBY')
foo&. \
^ Redundant line continuation.
bar
RUBY
expect_correction(<<~RUBY)
foo&.#{trailing_whitespace}
bar
RUBY
end
it 'does not register an offense when line continuations involve `return` with a return value' do
expect_no_offenses(<<~'RUBY')
return \
foo
RUBY
end
it 'registers an offense when line continuations involve `return` with a parenthesized return value' do
expect_offense(<<~'RUBY')
return(\
^ Redundant line continuation.
foo
)
RUBY
expect_correction(<<~RUBY)
return(
foo
)
RUBY
end
it 'does not register an offense when line continuations involve `break` with a return value' do
expect_no_offenses(<<~'RUBY')
foo do
break \
bar
end
RUBY
end
it 'does not register an offense when line continuations involve `next` with a return value' do
expect_no_offenses(<<~'RUBY')
foo do
next \
bar
end
RUBY
end
it 'does not register an offense when line continuations involve `yield` with a return value' do
expect_no_offenses(<<~'RUBY')
def foo
yield \
bar
end
RUBY
end
it 'registers an offense when line continuations with `if`' do
expect_offense(<<~'RUBY')
if foo \
^ Redundant line continuation.
then bar
end
RUBY
expect_correction(<<~RUBY)
if foo#{trailing_whitespace}
then bar
end
RUBY
end
it 'does not register an offense when line continuations with `if` modifier' do
expect_no_offenses(<<~'RUBY')
bar \
if foo
RUBY
end
it 'does not register an offense when line continuations with `unless` modifier' do
expect_no_offenses(<<~'RUBY')
bar \
unless foo
RUBY
end
it 'does not register an offense when line continuations with `while` modifier' do
expect_no_offenses(<<~'RUBY')
bar \
while foo
RUBY
end
it 'does not register an offense when line continuations with `until` modifier' do
expect_no_offenses(<<~'RUBY')
bar \
until foo
RUBY
end
it 'does not register an offense when line continuations with `rescue` modifier' do
expect_no_offenses(<<~'RUBY')
bar \
rescue foo
RUBY
end
it 'does not register an offense when required line continuations for `&&` is used with an assignment after a line break' do
expect_no_offenses(<<~'RUBY')
if foo \
&& (bar = baz)
end
RUBY
end
it 'does not register an offense when required line continuations for multiline leading dot method chain with an empty line' do
expect_no_offenses(<<~'RUBY')
obj
.foo(42) \
.bar
RUBY
end
it 'does not register an offense when required line continuations for multiline leading dot safe navigation method chain with an empty line' do
expect_no_offenses(<<~'RUBY')
obj
&.foo(42) \
.bar
RUBY
end
it 'does not register an offense when required line continuations for multiline leading dot method chain with a blank line' do
expect_no_offenses(<<~RUBY)
obj
.foo(42) \\
#{trailing_whitespace}
.bar
RUBY
end
it 'registers an offense when redundant line continuations for multiline leading dot method chain without an empty line' do
expect_offense(<<~'RUBY')
obj
.foo(42) \
^ Redundant line continuation.
.bar
RUBY
expect_correction(<<~RUBY)
obj
.foo(42)#{trailing_whitespace}
.bar
RUBY
end
it 'registers an offense when redundant line continuations for multiline trailing dot method chain with an empty line' do
expect_offense(<<~'RUBY')
obj.
foo(42). \
^ Redundant line continuation.
bar
RUBY
expect_correction(<<~RUBY)
obj.
foo(42).#{trailing_whitespace}
bar
RUBY
end
it 'registers an offense when redundant line continuations for multiline trailing dot method chain without an empty line' do
expect_offense(<<~'RUBY')
obj.
foo(42). \
^ Redundant line continuation.
bar
RUBY
expect_correction(<<~RUBY)
obj.
foo(42).#{trailing_whitespace}
bar
RUBY
end
it 'registers an offense when redundant line continuations for array' do
expect_offense(<<~'RUBY')
[foo, \
^ Redundant line continuation.
bar]
RUBY
expect_correction(<<~RUBY)
[foo,#{trailing_whitespace}
bar]
RUBY
end
it 'registers an offense when redundant line continuations for hash' do
expect_offense(<<~'RUBY')
{foo: \
^ Redundant line continuation.
bar}
RUBY
expect_correction(<<~RUBY)
{foo:#{trailing_whitespace}
bar}
RUBY
end
it 'registers an offense when redundant line continuations for method call' do
expect_offense(<<~'RUBY')
foo(bar, \
^ Redundant line continuation.
baz)
RUBY
expect_correction(<<~RUBY)
foo(bar,#{trailing_whitespace}
baz)
RUBY
end
it 'registers an offense and corrects when using redundant line concatenation for assigning a return value and with argument parentheses' do
expect_offense(<<~'RUBY')
foo = do_something( \
^ Redundant line continuation.
argument)
RUBY
expect_correction(<<~RUBY)
foo = do_something(#{trailing_whitespace}
argument)
RUBY
end
it 'does not register an offense when line continuations for double quoted string' do
expect_no_offenses(<<~'RUBY')
foo = "foo \
bar"
RUBY
end
it 'does not register an offense when line continuations for single quoted string' do
expect_no_offenses(<<~'RUBY')
foo = 'foo \
bar'
RUBY
end
it 'does not register an offense when line continuations inside comment' do
expect_no_offenses(<<~'RUBY')
class Foo
# foo \
# bar
end
RUBY
end
it 'does not register an offense for a backslash in a comment at EOF' do
expect_no_offenses(<<~'RUBY')
foo # \
RUBY
end
it 'does not register an offense for string concatenation with single quotes' do
expect_no_offenses(<<~'RUBY')
'bar' \
'baz'
RUBY
end
it 'does not register an offense for string concatenation with double quotes' do
expect_no_offenses(<<~'RUBY')
"bar" \
"baz"
RUBY
end
it 'does not register an offense for string concatenation inside a method call' do
expect_no_offenses(<<~'RUBY')
foo('bar' \
'baz')
foo(bar('string1' \
'string2')).baz
RUBY
end
it 'registers an offense for an interpolated string argument followed by line continuation' do
expect_offense(<<~'RUBY')
foo("#{bar}", \
^ Redundant line continuation.
baz)
RUBY
end
it 'does not register an offense when using line concatenation and calling a method without parentheses' do
expect_no_offenses(<<~'RUBY')
foo do_something \
argument
RUBY
end
it 'does not register an offense when using line concatenation and safe navigation calling a method without parentheses' do
expect_no_offenses(<<~'RUBY')
foo obj&.do_something \
argument
RUBY
end
it 'does not register an offense when using line concatenation and calling a method with keyword arguments without parentheses' do
expect_no_offenses(<<~'RUBY')
foo.bar do_something \
key: value
RUBY
end
it 'does not register an offense when using line concatenation and calling a method without parentheses in multiple expression block' do
expect_no_offenses(<<~'RUBY')
foo do
bar \
key: value
baz
end
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of method call' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
argument
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without hash argument parentheses of method call' do
expect_no_offenses(<<~'RUBY')
foo.bar = do_something \
key: value
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of local variable' do
expect_no_offenses(<<~'RUBY')
argument = 42
foo = do_something \
argument
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of instance variable' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
@argument
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of class variable' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
@@argument
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of global variable' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
$argument
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of constant' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
ARGUMENT
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of constant base' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
::ARGUMENT
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of string literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
'argument'
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of interpolated string literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
"argument#{x}"
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of xstring literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
`argument`
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of symbol literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
:argument
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of regexp literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
(1..9)
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of integer literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
42
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of float literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
42.0
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of true literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
true
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of false literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
false
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of nil literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
nil
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of self' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
self
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of array literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
[]
RUBY
end
it 'does not register an offense when using line concatenation for assigning a return value and without argument parentheses of hash literal' do
expect_no_offenses(<<~'RUBY')
foo = do_something \
{}
RUBY
end
it 'does not register an offense when a line continuation precedes an arithmetic operator' do
expect_no_offenses(<<~'RUBY')
1 \
+ 2 \
- 3 \
* 4 \
/ 5 \
% 6 \
** 7
RUBY
end
it 'does not register an offense when a line continuation precedes a bitwise operator' do
expect_no_offenses(<<~'RUBY')
1 \
& 2 \
| 3 \
^ 4
RUBY
end
it 'does not register an offense when line continuations with comparison operator and the LHS is wrapped in parentheses' do
expect_no_offenses(<<~'RUBY')
(
42) \
== bar
RUBY
end
it 'does not register an offense when line continuations with comparison operator and the LHS is wrapped in brackets' do
expect_no_offenses(<<~'RUBY')
[
42] \
== bar
RUBY
end
it 'does not register an offense when line continuations with comparison operator and the LHS is wrapped in braces' do
expect_no_offenses(<<~'RUBY')
{
k: :v} \
== bar
RUBY
end
it 'does not register an offense when line continuations with &&' do
expect_no_offenses(<<~'RUBY')
foo \
&& bar
RUBY
end
it 'does not register an offense when line continuations with ||' do
expect_no_offenses(<<~'RUBY')
foo \
|| bar
RUBY
end
it 'does not register an offense when line continuations with `&&` in assignments' do
expect_no_offenses(<<~'RUBY')
foo = bar\
&& baz
RUBY
end
it 'does not register an offense when line continuations with `||` in assignments' do
expect_no_offenses(<<~'RUBY')
foo = bar\
|| baz
RUBY
end
it 'does not register an offense when line continuations with `&&` in method definition' do
expect_no_offenses(<<~'RUBY')
def do_something
foo \
&& bar
end
RUBY
end
it 'does not register an offense when line continuations with `||` in method definition' do
expect_no_offenses(<<~'RUBY')
def do_something
foo \
|| bar
end
RUBY
end
it 'registers an offense for an extra continuation after a required continuation' do
expect_offense(<<~'RUBY')
def do_something
foo \
|| bar \
^ Redundant line continuation.
end
RUBY
expect_correction(<<~RUBY)
def do_something
foo \\
|| bar#{trailing_whitespace}
end
RUBY
end
it 'registers an offense for a redundant continuation following a required continuation in separate blocks' do
expect_offense(<<~'RUBY')
x do
foo bar \
baz
end
y do
foo(bar, \
^ Redundant line continuation.
baz)
end
RUBY
expect_correction(<<~RUBY)
x do
foo bar \\
baz
end
y do
foo(bar,#{trailing_whitespace}
baz)
end
RUBY
end
it 'registers an offense for an redundant continuation on a statement preceding a required continuation inside the same begin node' do
expect_offense(<<~'RUBY')
foo(bar, \
^ Redundant line continuation.
baz)
foo bar \
baz
RUBY
expect_correction(<<~RUBY)
foo(bar,#{trailing_whitespace}
baz)
foo bar \\
baz
RUBY
end
it 'registers an offense for an redundant continuation on a statement following a required continuation inside the same begin node' do
expect_offense(<<~'RUBY')
foo bar \
baz
foo(bar, \
^ Redundant line continuation.
baz)
RUBY
expect_correction(<<~RUBY)
foo bar \\
baz
foo(bar,#{trailing_whitespace}
baz)
RUBY
end
it 'registers an offense for multiple redundant continuations inside the same begin node' do
expect_offense(<<~'RUBY')
foo(bar, \
^ Redundant line continuation.
baz)
foo(bar, \
^ Redundant line continuation.
baz)
RUBY
expect_correction(<<~RUBY)
foo(bar,#{trailing_whitespace}
baz)
foo(bar,#{trailing_whitespace}
baz)
RUBY
end
it 'does not register an offense for multiple required continuations inside the same begin node' do
expect_no_offenses(<<~'RUBY')
foo bar \
baz
foo bar \
baz
RUBY
end
it 'does not register an offense when multi-line continuations with &' do
expect_no_offenses(<<~'RUBY')
foo \
& bar \
& baz
RUBY
end
it 'does not register an offense when multi-line continuations with |' do
expect_no_offenses(<<~'RUBY')
foo \
| bar \
| baz
RUBY
end
it 'does not register an offense when line continuations with ternary operator' do
expect_no_offenses(<<~'RUBY')
foo \
? bar
: baz
RUBY
end
it 'does not register an offense when line continuations with method argument' do
expect_no_offenses(<<~'RUBY')
some_method \
(argument)
some_method \
argument
RUBY
end
it 'does not register an offense for a line continuation with a method definition as a method argument' do
expect_no_offenses(<<~'RUBY')
class Foo
memoize \
def do_something
end
end
RUBY
end
it 'does not register an offense when line continuations with using && for comparison chaining' do
expect_no_offenses(<<~'RUBY')
foo == other.foo \
&& bar == other.bar \
&& baz == other.baz
RUBY
end
it 'does not register an offense when line continuations with using || for comparison chaining' do
expect_no_offenses(<<~'RUBY')
foo == other.foo \
|| bar == other.bar \
|| baz == other.baz
RUBY
end
it 'does not register an offense when line continuations with `&&` in method definition and before a destructuring assignment' do
expect_no_offenses(<<~'RUBY')
var, = *foo
bar \
&& baz
RUBY
end
it 'does not register an offense when line continuations inside heredoc' do
expect_no_offenses(<<~'RUBY')
<<~SQL
SELECT * FROM foo \
WHERE bar = 1
SQL
RUBY
end
it 'does not register an offense when not using line continuations' do
expect_no_offenses(<<~RUBY)
foo
.bar
.baz
foo
&.bar
[foo,
bar]
{ foo:
bar }
foo(bar,
baz)
RUBY
end
it 'registers an offense when there is a line continuation at the end of Ruby code' do
expect_offense(<<~'RUBY')
foo \
^ Redundant line continuation.
RUBY
expect_correction(<<~RUBY)
foo#{trailing_whitespace}
RUBY
end
it 'registers an offense when there is a line continuation at the end of Ruby code followed by `__END__` data' do
expect_offense(<<~'RUBY')
foo \
^ Redundant line continuation.
__END__
data \
RUBY
expect_correction(<<~RUBY)
foo#{trailing_whitespace}
__END__
data \\
RUBY
end
it 'registers an offense when there is a line continuation inside a method call followed by a percent array' do
expect_offense(<<~'RUBY')
foo(bar, \
^ Redundant line continuation.
%i[baz quux])
RUBY
end
it 'registers an offense for a method call with a line continuation and no following arguments' do
expect_offense(<<~'RUBY')
def foo
bar \
^ Redundant line continuation.
end
RUBY
end
it 'registers an offense for `super` with a line continuation and no following arguments' do
expect_offense(<<~'RUBY')
def foo
super \
^ Redundant line continuation.
end
RUBY
end
it 'registers an offense for multiline assignment with a line continuation' do
expect_offense(<<~'RUBY')
a, b, \
^ Redundant line continuation.
c = [1, 2, 3]
RUBY
expect_correction(<<~RUBY)
a, b,#{trailing_whitespace}
c = [1, 2, 3]
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_begin_spec.rb | spec/rubocop/cop/style/redundant_begin_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantBegin, :config do
it 'reports an offense for single line def with redundant begin block' do
expect_offense(<<~RUBY)
def func; begin; x; y; rescue; z end; end
^^^^^ Redundant `begin` block detected.
RUBY
expect_correction(<<~RUBY)
def func; ; x; y; rescue; z ; end
RUBY
end
it 'reports an offense for def with redundant begin block' do
expect_offense(<<~RUBY)
def func
begin
^^^^^ Redundant `begin` block detected.
ala
rescue => e
bala
end
end
RUBY
expect_correction(<<~RUBY)
def func
#{trailing_whitespace}
ala
rescue => e
bala
#{trailing_whitespace}
end
RUBY
end
it 'reports an offense for defs with redundant begin block' do
expect_offense(<<~RUBY)
def Test.func
begin
^^^^^ Redundant `begin` block detected.
ala
rescue => e
bala
end
end
RUBY
expect_correction(<<~RUBY)
def Test.func
#{trailing_whitespace}
ala
rescue => e
bala
#{trailing_whitespace}
end
RUBY
end
it 'accepts a def with required begin block' do
expect_no_offenses(<<~RUBY)
def func
begin
ala
rescue => e
bala
end
something
end
RUBY
end
it 'accepts a defs with required begin block' do
expect_no_offenses(<<~RUBY)
def Test.func
begin
ala
rescue => e
bala
end
something
end
RUBY
end
it 'accepts a def with a begin block after a statement' do
expect_no_offenses(<<~RUBY)
def Test.func
something
begin
ala
rescue => e
bala
end
end
RUBY
end
it "doesn't modify spacing when autocorrecting" do
expect_offense(<<~RUBY)
def method
begin
^^^^^ Redundant `begin` block detected.
BlockA do |strategy|
foo
end
BlockB do |portfolio|
foo
end
rescue => e # some problem
bar
end
end
RUBY
expect_correction(<<~RUBY)
def method
#{trailing_whitespace}
BlockA do |strategy|
foo
end
BlockB do |portfolio|
foo
end
rescue => e # some problem
bar
#{trailing_whitespace}
end
RUBY
end
it 'autocorrects when there are trailing comments' do
expect_offense(<<~RUBY)
def method
begin # comment 1
^^^^^ Redundant `begin` block detected.
do_some_stuff
rescue # comment 2
end # comment 3
end
RUBY
expect_correction(<<~RUBY)
def method
# comment 1
do_some_stuff
rescue # comment 2
# comment 3
end
RUBY
end
it 'registers an offense and corrects when using `begin` without `rescue` or `ensure`' do
expect_offense(<<~RUBY)
begin
^^^^^ Redundant `begin` block detected.
do_something
end
RUBY
expect_correction("\n do_something\n\n")
end
it 'registers an offense and corrects when using `begin` with multiple statements without `rescue` or `ensure`' do
expect_offense(<<~RUBY)
begin
^^^^^ Redundant `begin` block detected.
foo
bar
end
RUBY
expect_correction("\n foo\n bar\n\n")
end
it 'does not register an offense when using `begin` with `rescue`' do
expect_no_offenses(<<~RUBY)
begin
do_something
rescue
handle_exception
end
RUBY
end
it 'does not register an offense when using `begin` with `ensure`' do
expect_no_offenses(<<~RUBY)
begin
do_something
ensure
finalize
end
RUBY
end
it 'does not register an offense when using `begin` for assignment' do
expect_no_offenses(<<~RUBY)
var = begin
foo
bar
end
RUBY
end
it 'registers and corrects an offense when using `begin` with single statement for or assignment' do
expect_offense(<<~RUBY)
# outer comment
var ||= begin # inner comment 1
^^^^^ Redundant `begin` block detected.
# inner comment 2
foo
# inner comment 3
end
RUBY
expect_correction(<<~RUBY)
# outer comment
# inner comment 1
# inner comment 2
var ||= foo
# inner comment 3
RUBY
end
it 'registers and corrects an offense when using `begin` with single statement that called a block for or assignment' do
expect_offense(<<~RUBY)
var ||= begin
^^^^^ Redundant `begin` block detected.
foo do |arg|
bar
end
end
RUBY
expect_correction(<<~RUBY)
var ||= foo do |arg|
bar
end
RUBY
end
it 'registers and corrects an offense when using modifier `if` single statement in `begin` block' do
expect_offense(<<~RUBY)
var ||= begin
^^^^^ Redundant `begin` block detected.
foo if condition
end
RUBY
expect_correction(<<~RUBY)
var ||= (foo if condition)
RUBY
end
it 'registers and corrects an offense when using multi-line `if` in `begin` block' do
expect_offense(<<~RUBY)
var ||= begin
^^^^^ Redundant `begin` block detected.
if condition
foo
end
end
RUBY
expect_correction(<<~RUBY)
var ||= if condition
foo
end\n
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `if`' do
expect_offense(<<~RUBY)
if condition
begin
^^^^^ Redundant `begin` block detected.
foo
bar
end
end
RUBY
expect_correction(<<~RUBY)
if condition
#{trailing_whitespace}
foo
bar
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `unless`' do
expect_offense(<<~RUBY)
unless condition
begin
^^^^^ Redundant `begin` block detected.
foo
bar
end
end
RUBY
expect_correction(<<~RUBY)
unless condition
#{trailing_whitespace}
foo
bar
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `elsif`' do
expect_offense(<<~RUBY)
if condition
foo
elsif condition2
begin
^^^^^ Redundant `begin` block detected.
bar
baz
end
end
RUBY
expect_correction(<<~RUBY)
if condition
foo
elsif condition2
#{trailing_whitespace}
bar
baz
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `else`' do
expect_offense(<<~RUBY)
if condition
foo
else
begin
^^^^^ Redundant `begin` block detected.
bar
baz
end
end
RUBY
expect_correction(<<~RUBY)
if condition
foo
else
#{trailing_whitespace}
bar
baz
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `case`/`when`' do
expect_offense(<<~RUBY)
case condition
when foo
begin
^^^^^ Redundant `begin` block detected.
bar
baz
end
end
RUBY
expect_correction(<<~RUBY)
case condition
when foo
#{trailing_whitespace}
bar
baz
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `case`/`when`/`else`' do
expect_offense(<<~RUBY)
case condition
when foo
bar
else
begin
^^^^^ Redundant `begin` block detected.
baz
quux
end
end
RUBY
expect_correction(<<~RUBY)
case condition
when foo
bar
else
#{trailing_whitespace}
baz
quux
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `case`/`in`' do
expect_offense(<<~RUBY)
case condition
in foo
begin
^^^^^ Redundant `begin` block detected.
bar
baz
end
end
RUBY
expect_correction(<<~RUBY)
case condition
in foo
#{trailing_whitespace}
bar
baz
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `case`/`in`/`else`' do
expect_offense(<<~RUBY)
case condition
in foo
bar
else
begin
^^^^^ Redundant `begin` block detected.
baz
quux
end
end
RUBY
expect_correction(<<~RUBY)
case condition
in foo
bar
else
#{trailing_whitespace}
baz
quux
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `while`' do
expect_offense(<<~RUBY)
while condition
begin
^^^^^ Redundant `begin` block detected.
foo
bar
end
end
RUBY
expect_correction(<<~RUBY)
while condition
#{trailing_whitespace}
foo
bar
#{trailing_whitespace}
end
RUBY
end
it 'registers and corrects an offense when a multiline `begin` block is inside `until`' do
expect_offense(<<~RUBY)
until condition
begin
^^^^^ Redundant `begin` block detected.
foo
bar
end
end
RUBY
expect_correction(<<~RUBY)
until condition
#{trailing_whitespace}
foo
bar
#{trailing_whitespace}
end
RUBY
end
it 'does not register an offense when using `begin` with `rescue` inside an `if` statement' do
expect_no_offenses(<<~RUBY)
if condition
begin
foo
bar
rescue StandardError
baz
end
end
RUBY
end
it 'does not register an offense when using `begin` with `ensure` inside an `if` statement' do
expect_no_offenses(<<~RUBY)
if condition
begin
foo
bar
ensure
baz
end
end
RUBY
end
it 'does not register an offense when using `begin` with `rescue` inside an `case` statement' do
expect_no_offenses(<<~RUBY)
case condition
when foo
begin
bar
baz
rescue StandardError
quux
end
end
RUBY
end
it 'does not register an offense when using `begin` with `ensure` inside an `case` statement' do
expect_no_offenses(<<~RUBY)
case condition
when foo
begin
bar
baz
ensure
quux
end
end
RUBY
end
it 'does not register an offense when using `begin` with `rescue` inside an `while` statement' do
expect_no_offenses(<<~RUBY)
while condition
begin
foo
bar
rescue StandardError
baz
end
end
RUBY
end
it 'does not register an offense when using `begin` with `ensure` inside an `while` statement' do
expect_no_offenses(<<~RUBY)
while condition
begin
foo
bar
ensure
baz
end
end
RUBY
end
it 'does not register an offense when using `begin` with `rescue` inside an `until` statement' do
expect_no_offenses(<<~RUBY)
until condition
begin
foo
bar
rescue StandardError
baz
end
end
RUBY
end
it 'does not register an offense when using `begin` with `ensure` inside an `until` statement' do
expect_no_offenses(<<~RUBY)
until condition
begin
foo
bar
ensure
baz
end
end
RUBY
end
it 'does not register an offense when using `begin` with multiple statement for or assignment' do
expect_no_offenses(<<~RUBY)
var ||= begin
foo
bar
end
RUBY
end
it 'does not register an offense when using `begin` with no statements for or assignment' do
expect_no_offenses(<<~RUBY)
var ||= begin
end
RUBY
end
it 'does not register an offense when using `begin` with `while`' do
expect_no_offenses(<<~RUBY)
begin
do_first_thing
some_value = do_second_thing
end while some_value
RUBY
end
it 'does not register an offense when using `begin` with `until`' do
expect_no_offenses(<<~RUBY)
begin
do_first_thing
some_value = do_second_thing
end until some_value
RUBY
end
it 'does not register an offense when using body of `begin` is empty' do
expect_no_offenses(<<~RUBY)
begin
end
RUBY
end
it 'does not register an offense when using `begin` for or assignment and method call' do
expect_no_offenses(<<~RUBY)
var ||= begin
foo
bar
end.baz do
qux
end
RUBY
end
it 'does not register an offense when using `begin` for method argument' do
expect_no_offenses(<<~RUBY)
do_something begin
foo
bar
end
RUBY
end
it 'does not register an offense when using `begin` for logical operator conditions' do
expect_no_offenses(<<~RUBY)
condition && begin
foo
bar
end
RUBY
end
it 'does not register an offense when using `begin` for semantic operator conditions' do
expect_no_offenses(<<~RUBY)
condition and begin
foo
bar
end
RUBY
end
context '< Ruby 2.5', :ruby24, unsupported_on: :prism do
it 'accepts a do-end block with a begin-end' do
expect_no_offenses(<<~RUBY)
do_something do
begin
foo
rescue => e
bar
end
end
RUBY
end
end
context '>= ruby 2.5', :ruby25 do
it 'registers an offense for a do-end block with redundant begin-end' do
expect_offense(<<~RUBY)
do_something do
begin
^^^^^ Redundant `begin` block detected.
foo
rescue => e
bar
end
end
RUBY
expect_correction(<<~RUBY)
do_something do
#{trailing_whitespace}
foo
rescue => e
bar
#{trailing_whitespace}
end
RUBY
end
it 'accepts a {} block with a begin-end' do
expect_no_offenses(<<~RUBY)
do_something {
begin
foo
rescue => e
bar
end
}
RUBY
end
it 'accepts a block with a begin block after a statement' do
expect_no_offenses(<<~RUBY)
do_something do
something
begin
ala
rescue => e
bala
end
end
RUBY
end
it 'accepts a stabby lambda with a begin-end' do
expect_no_offenses(<<~RUBY)
-> do
begin
foo
rescue => e
bar
end
end
RUBY
end
it 'accepts super with block' do
expect_no_offenses(<<~RUBY)
def a_method
super do |arg|
foo
rescue => e
bar
end
end
RUBY
end
end
it 'accepts when one-liner `begin` block has multiple statements with modifier condition' do
expect_no_offenses(<<~RUBY)
begin foo; bar; end unless condition
RUBY
end
it 'accepts when multi-line `begin` block has multiple statements with modifier condition' do
expect_no_offenses(<<~RUBY)
begin
foo; bar
end unless condition
RUBY
end
it 'reports an offense when one-liner `begin` block has single statement with modifier condition' do
expect_offense(<<~RUBY)
begin foo end unless condition
^^^^^ Redundant `begin` block detected.
RUBY
expect_correction(" foo unless condition\n")
end
it 'reports an offense when multi-line `begin` block has single statement with modifier condition' do
expect_offense(<<~RUBY)
begin
^^^^^ Redundant `begin` block detected.
foo
end unless condition
RUBY
expect_correction("\n foo unless condition\n")
end
it 'reports an offense when multi-line `begin` block has single statement and it is inside condition' do
expect_offense(<<~RUBY)
unless condition
begin
^^^^^ Redundant `begin` block detected.
foo
end
end
RUBY
expect_correction("unless condition\n \n foo\n \nend\n")
end
it 'reports an offense when assigning nested `begin` blocks' do
expect_offense(<<~RUBY)
@foo ||= begin
@bar ||= begin
^^^^^ Redundant `begin` block detected.
baz
end
end
RUBY
expect_correction(<<~RUBY)
@foo ||= @bar ||= baz
#{trailing_whitespace * 2}
RUBY
end
it 'reports an offense when assigning nested blocks which contain `begin` blocks' do
expect_offense(<<~RUBY)
var = do_something do
begin
^^^^^ Redundant `begin` block detected.
do_something do
begin
^^^^^ Redundant `begin` block detected.
foo
ensure
bar
end
end
ensure
baz
end
end
RUBY
expect_correction(<<~RUBY)
var = do_something do
#{trailing_whitespace}
do_something do
#{trailing_whitespace}
foo
ensure
bar
#{trailing_whitespace}
end
ensure
baz
#{trailing_whitespace}
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'reports an offense when assigning nested blocks which contain `begin` blocks' do
expect_offense(<<~RUBY)
var = do_something do
begin
^^^^^ Redundant `begin` block detected.
do_something do
begin
^^^^^ Redundant `begin` block detected.
_1
ensure
bar
end
end
ensure
baz
end
end
RUBY
expect_correction(<<~RUBY)
var = do_something do
#{trailing_whitespace}
do_something do
#{trailing_whitespace}
_1
ensure
bar
#{trailing_whitespace}
end
ensure
baz
#{trailing_whitespace}
end
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'reports an offense when assigning nested blocks which contain `begin` blocks' do
expect_offense(<<~RUBY)
var = do_something do
begin
^^^^^ Redundant `begin` block detected.
do_something do
begin
^^^^^ Redundant `begin` block detected.
it
ensure
bar
end
end
ensure
baz
end
end
RUBY
expect_correction(<<~RUBY)
var = do_something do
#{trailing_whitespace}
do_something do
#{trailing_whitespace}
it
ensure
bar
#{trailing_whitespace}
end
ensure
baz
#{trailing_whitespace}
end
RUBY
end
end
context 'when using endless method definition', :ruby30 do
it 'registers when `begin` block has a single statement' do
expect_offense(<<~RUBY)
def foo = begin
^^^^^ Redundant `begin` block detected.
bar
end
RUBY
expect_correction("def foo = bar\n\n")
end
it 'accepts when `begin` block has multiple statements' do
expect_no_offenses(<<~RUBY)
def foo = begin
bar
baz
end
RUBY
end
it 'accepts when `begin` block has no statements' do
expect_no_offenses(<<~RUBY)
def foo = begin
end
RUBY
end
it 'accepts when `begin` block includes `rescue` clause' do
expect_no_offenses(<<~RUBY)
def func = begin
foo
rescue
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/redundant_conditional_spec.rb | spec/rubocop/cop/style/redundant_conditional_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantConditional, :config do
it 'registers an offense for ternary with boolean results' do
expect_offense(<<~RUBY)
x == y ? true : false
^^^^^^^^^^^^^^^^^^^^^ This conditional expression can just be replaced by `x == y`.
RUBY
expect_correction(<<~RUBY)
x == y
RUBY
end
it 'registers an offense for ternary with negated boolean results' do
expect_offense(<<~RUBY)
x == y ? false : true
^^^^^^^^^^^^^^^^^^^^^ This conditional expression can just be replaced by `!(x == y)`.
RUBY
expect_correction(<<~RUBY)
!(x == y)
RUBY
end
it 'allows ternary with non-boolean results' do
expect_no_offenses('x == y ? 1 : 10')
end
it 'registers an offense for if/else with boolean results' do
expect_offense(<<~RUBY)
if x == y
^^^^^^^^^ This conditional expression can just be replaced by `x == y`.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
x == y
RUBY
end
it 'registers an offense for if/else with negated boolean results' do
expect_offense(<<~RUBY)
if x == y
^^^^^^^^^ This conditional expression can just be replaced by `!(x == y)`.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
!(x == y)
RUBY
end
it 'registers an offense for unless/else with boolean results' do
expect_offense(<<~RUBY)
unless x == y
^^^^^^^^^^^^^ This conditional expression can just be replaced by `!(x == y)`.
true
else
false
end
RUBY
expect_correction(<<~RUBY)
!(x == y)
RUBY
end
it 'registers an offense for unless/else with negated boolean results' do
expect_offense(<<~RUBY)
unless x == y
^^^^^^^^^^^^^ This conditional expression can just be replaced by `x == y`.
false
else
true
end
RUBY
expect_correction(<<~RUBY)
x == y
RUBY
end
it 'registers an offense for if/elsif/else with boolean results' do
expect_offense(<<~RUBY)
if cond
false
elsif x == y
^^^^^^^^^^^^ This conditional expression can just be replaced by [...]
true
else
false
end
RUBY
expect_correction(<<~RUBY)
if cond
false
else
x == y
end
RUBY
end
it 'registers an offense for if/elsif/else with negated boolean results' do
expect_offense(<<~RUBY)
if cond
false
elsif x == y
^^^^^^^^^^^^ This conditional expression can just be replaced by [...]
false
else
true
end
RUBY
expect_correction(<<~RUBY)
if cond
false
else
!(x == y)
end
RUBY
end
it 'does not register an offense for if/else with non-boolean results' do
expect_no_offenses(<<~RUBY)
if x == y
1
else
2
end
RUBY
end
it 'does not register an offense for if/elsif/else with non-boolean results' do
expect_no_offenses(<<~RUBY)
if cond
1
elsif x == y
2
else
3
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/sole_nested_conditional_spec.rb | spec/rubocop/cop/style/sole_nested_conditional_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::SoleNestedConditional, :config do
let(:cop_config) { { 'AllowModifier' => false } }
it 'registers an offense and corrects when using nested `if` within `if`' do
expect_offense(<<~RUBY)
if foo
if bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `unless` within `if`' do
expect_offense(<<~RUBY)
if foo
unless bar
^^^^^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && !bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `unless`' do
expect_offense(<<~RUBY)
unless foo
if bar
^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if !foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `unless foo == bar`' do
expect_offense(<<~RUBY)
unless foo == bar
if baz
^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end
end
RUBY
# NOTE: `Style/InverseMethods` cop autocorrects from `(!foo == bar)` to `foo != bar`.
expect_correction(<<~RUBY)
if !(foo == bar) && baz
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo = bar`' do
expect_offense(<<~RUBY)
if foo = bar
if baz
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if (foo = bar) && baz
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo = bar` as the LHS of an `and`' do
# `and` is used in the source code for precedence without parentheses
expect_offense(<<~RUBY)
if foo = bar and baz
if quux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo = bar and baz && quux
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo = bar` as the RHS of an `and`' do
expect_offense(<<~RUBY)
if baz && foo = bar
if quux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if baz && (foo = bar) && quux
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo = bar` in a multiline `and`' do
expect_offense(<<~RUBY)
if baz &&
foo = bar
if quux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if baz &&
(foo = bar) && quux
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo = bar` in a nested `and`' do
expect_offense(<<~RUBY)
if baz && foo = bar and fred = garply
if corge
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if baz && foo = bar and (fred = garply) && corge
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if (foo = bar)` in an `and`' do
expect_offense(<<~RUBY)
if baz && (foo = bar)
if quux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if baz && (foo = bar) && quux
do_something
end
RUBY
end
it 'registers an offense and corrects assignment within nested `if`' do
expect_offense(<<~RUBY)
if foo
if bar = baz
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && (bar = baz)
do_something
end
RUBY
end
it 'registers an offense and corrects assignment within `and` within nested `if`' do
expect_offense(<<~RUBY)
if foo
if quux && bar = baz
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && quux && (bar = baz)
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo = bar` as the LHS of an `or`' do
# `or` is used in the source code for precedence without parentheses
expect_offense(<<~RUBY)
if foo = bar or baz
if quux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if (foo = bar or baz) && quux
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo = bar` as the RHS of an `or`' do
expect_offense(<<~RUBY)
if baz || foo = bar
if quux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if (baz || foo = bar) && quux
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `unless foo & bar`' do
expect_offense(<<~RUBY)
unless foo & bar
if baz
^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if !(foo & bar) && baz
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` within `if foo & bar`' do
expect_offense(<<~RUBY)
if foo & bar
if baz
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if (foo & bar) && baz
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `unless` within `unless`' do
expect_offense(<<~RUBY)
unless foo
unless bar
^^^^^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if !foo && !bar
do_something
end
RUBY
end
it 'does not register an offense when using nested conditional within `elsif`' do
expect_no_offenses(<<~RUBY)
if foo
elsif bar
if baz
end
end
RUBY
end
it 'registers an offense and corrects when using nested `if` modifier conditional' do
expect_offense(<<~RUBY)
if foo
do_something if bar
^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `unless` modifier conditional' do
expect_offense(<<~RUBY)
if foo
do_something unless bar
^^^^^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && !bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `unless` modifier with a single expression condition' do
expect_offense(<<~RUBY)
class A
def foo
if h[:a]
h[:b] = true unless h.has_key?(:b)
^^^^^^ Consider merging nested conditions into outer `if` conditions.
end
end
end
RUBY
# INFO: parentheses are removed by Style/RedundantParentheses
expect_correction(<<~RUBY)
class A
def foo
if (h[:a]) && !h.has_key?(:b)
h[:b] = true
end
end
end
RUBY
end
it 'registers an offense and corrects when using nested `unless` modifier multiple conditional' do
expect_offense(<<~RUBY)
if foo
do_something unless bar && baz
^^^^^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && !(bar && baz)
do_something
end
RUBY
end
it 'registers an offense and corrects when nested `||` operator condition' do
expect_offense(<<~RUBY)
if foo
if bar || baz
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && (bar || baz)
do_something
end
RUBY
end
it 'registers an offense and corrects when nested `||` operator modifier condition' do
expect_offense(<<~RUBY)
if foo
do_something if bar || baz
^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && (bar || baz)
do_something
end
RUBY
end
it 'registers an offense and corrects when using `||` in the outer condition' do
expect_offense(<<~RUBY)
if foo || bar
if baz || qux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if (foo || bar) && (baz || qux)
do_something
end
RUBY
end
it 'registers an offense and corrects when using `||` in the outer condition and nested modifier condition' do
expect_offense(<<~RUBY)
if foo || bar
do_something if baz || qux
^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if (foo || bar) && (baz || qux)
do_something
end
RUBY
end
it 'registers an offense and corrects when using `unless` and `||` and parens in the outer condition ' \
'and nested modifier condition' do
expect_offense(<<~RUBY)
unless (foo || bar)
do_something if baz
^^ Consider merging nested conditions into outer `unless` conditions.
end
RUBY
expect_correction(<<~RUBY)
if !(foo || bar) && baz
do_something
end
RUBY
end
it 'registers an offense and corrects when using `unless` and `||` without parens in the outer condition ' \
'and nested modifier condition' do
expect_offense(<<~RUBY)
unless foo || bar
do_something if baz
^^ Consider merging nested conditions into outer `unless` conditions.
end
RUBY
expect_correction(<<~RUBY)
if !(foo || bar) && baz
do_something
end
RUBY
end
it 'registers an offense and corrects when using `unless` and `===` without parens in the outer condition ' \
'and nested modifier condition' do
expect_offense(<<~RUBY)
if result
do_something unless foo === bar
^^^^^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if result && !(foo === bar)
do_something
end
RUBY
end
it 'registers an offense and corrects when using `unless` and `&&` without parens in the outer condition ' \
'and nested modifier condition' do
expect_offense(<<~RUBY)
unless foo && bar && baz
do_something unless qux
^^^^^^ Consider merging nested conditions into outer `unless` conditions.
end
RUBY
expect_correction(<<~RUBY)
if !(foo && bar && baz) && !qux
do_something
end
RUBY
end
it 'registers an offense and corrects when using `unless` and method arguments without parentheses ' \
'in the outer condition and nested modifier condition' do
expect_offense(<<~RUBY)
unless foo.is_a? Foo
do_something if bar
^^ Consider merging nested conditions into outer `unless` conditions.
end
RUBY
expect_correction(<<~RUBY)
if !foo.is_a?(Foo) && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using `unless` and method arguments with parentheses ' \
'in the outer condition and nested modifier condition' do
expect_offense(<<~RUBY)
unless foo.is_a?(Foo)
do_something if bar
^^ Consider merging nested conditions into outer `unless` conditions.
end
RUBY
expect_correction(<<~RUBY)
if !foo.is_a?(Foo) && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using `unless` and multiple method arguments with parentheses' \
'in the outer condition and nested modifier condition' do
expect_offense(<<~RUBY)
unless foo.bar arg1, arg2
do_something if baz
^^ Consider merging nested conditions into outer `unless` conditions.
end
RUBY
expect_correction(<<~RUBY)
if !foo.bar(arg1, arg2) && baz
do_something
end
RUBY
end
it 'registers an offense and corrects for multiple nested conditionals' do
expect_offense(<<~RUBY)
if foo
if bar
^^ Consider merging nested conditions into outer `if` conditions.
if baz
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
end
RUBY
expect_correction(<<~RUBY)
if foo && bar && baz
do_something
end
RUBY
end
it 'registers an offense and corrects for multiple nested conditionals with using method call outer condition by omitting parentheses' do
expect_offense(<<~RUBY)
if foo.is_a? Foo
if bar && baz
^^ Consider merging nested conditions into outer `if` conditions.
do_something if quux
^^ Consider merging nested conditions into outer `if` conditions.
end
end
RUBY
expect_correction(<<~RUBY)
if foo.is_a?(Foo) && bar && baz && quux
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested conditional and branch contains a comment' do
expect_offense(<<~RUBY)
if foo
# Comment.
if bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
# Comment.
if foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when there are outer and inline comments' do
expect_offense(<<~RUBY)
# Outer comment.
if foo
# Comment.
if bar # nested condition
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
# Outer comment.
# Comment.
if foo && bar # nested condition
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` and `not` in the inner condition' do
expect_offense(<<~RUBY)
if foo
if not bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && (not bar)
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` and `not` in the outer condition' do
expect_offense(<<~RUBY)
if not foo
if bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if (not foo) && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested `if` and `!` in the inner condition' do
expect_offense(<<~RUBY)
if foo
if !bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && !bar
do_something
end
RUBY
end
it 'registers an offense and corrects when using nested single line `if`' do
expect_offense(<<~RUBY)
if foo; if bar; end; end
^^ Consider merging nested conditions into outer `if` conditions.
RUBY
expect_correction(<<~RUBY)
if foo && bar; end;#{' '}
RUBY
end
context 'when disabling `Style/IfUnlessModifier`' do
let(:config) { RuboCop::Config.new('Style/IfUnlessModifier' => { 'Enabled' => false }) }
it 'registers an offense and corrects when using nested conditional and branch contains a comment' do
expect_offense(<<~RUBY)
if foo
# Comment.
if bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
# Comment.
if foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when there are outer and inline comments' do
expect_offense(<<~RUBY)
# Outer comment.
if foo
# Comment.
if bar # nested condition
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
# Outer comment.
# Comment.
if foo && bar # nested condition
do_something
end
RUBY
end
end
it 'registers an offense and corrects when using guard conditional with outer comment' do
expect_offense(<<~RUBY)
# Comment.
if foo
do_something if bar
^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
# Comment.
if foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when comment is in an empty nested `if` body' do
expect_offense(<<~RUBY)
if foo
if bar
^^ Consider merging nested conditions into outer `if` conditions.
# Comments.
end
end
RUBY
expect_correction(<<~RUBY)
if foo && bar
# Comments.
end
RUBY
end
it 'registers an offense and corrects when `if` foo do_something end `if` bar' do
expect_offense(<<~RUBY)
if foo
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end if bar
RUBY
expect_correction(<<~RUBY)
if bar && foo
do_something
end
RUBY
end
it 'registers an offense and corrects when `if` foo do_something end `unless` bar' do
expect_offense(<<~RUBY)
if foo
^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end unless bar
RUBY
expect_correction(<<~RUBY)
if !bar && foo
do_something
end
RUBY
end
it 'registers an offense and corrects when `unless` foo do_something end `if` bar' do
expect_offense(<<~RUBY)
unless foo
^^^^^^ Consider merging nested conditions into outer `if` conditions.
do_something
end if bar
RUBY
expect_correction(<<~RUBY)
if bar && !foo
do_something
end
RUBY
end
it 'registers an offense and corrects when `if` foo do_something end `if` bar && baz' do
expect_offense(<<~RUBY)
if foo
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end if bar && baz
RUBY
expect_correction(<<~RUBY)
if bar && baz && foo
do_something
end
RUBY
end
it 'registers an offense and corrects when `if` foo && bar do_something end `if` baz' do
expect_offense(<<~RUBY)
if foo && bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end if baz
RUBY
expect_correction(<<~RUBY)
if baz && foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when `if` foo do_something end `unless` bar && baz' do
expect_offense(<<~RUBY)
if foo
^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end unless bar && baz
RUBY
expect_correction(<<~RUBY)
if !(bar && baz) && foo
do_something
end
RUBY
end
it 'registers an offense and corrects when `if` foo && bar do_something end `unless` baz' do
expect_offense(<<~RUBY)
if foo && bar
^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end unless baz
RUBY
expect_correction(<<~RUBY)
if !baz && foo && bar
do_something
end
RUBY
end
it 'registers an offense and corrects when `unless` foo && bar do_something end `if` baz' do
expect_offense(<<~RUBY)
unless foo && bar
^^^^^^ Consider merging nested conditions into outer `if` conditions.
do_something
end if baz
RUBY
expect_correction(<<~RUBY)
if baz && !(foo && bar)
do_something
end
RUBY
end
it 'registers an offense when inner condition is an & operator' do
expect_offense(<<~RUBY)
if foo
unless bar & baz
^^^^^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && !(bar & baz)
do_something
end
RUBY
end
it 'registers an offense when inner condition is an || operator' do
expect_offense(<<~RUBY)
if foo
unless bar || baz
^^^^^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && !(bar || baz)
do_something
end
RUBY
end
it 'registers an offense when inner condition is an operator as a guard clause' do
expect_offense(<<~RUBY)
if foo
do_something unless bar & baz
^^^^^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && !(bar & baz)
do_something
end
RUBY
end
it 'does not register an offense when using nested ternary within conditional' do
expect_no_offenses(<<~RUBY)
if foo
bar ? baz : quux
end
RUBY
end
it 'does not register an offense when no nested conditionals' do
expect_no_offenses(<<~RUBY)
if foo
do_something
end
RUBY
end
it 'does not register an offense when using nested conditional is not the whole body' do
expect_no_offenses(<<~RUBY)
if foo
if bar
do_something
end
do_something_more
end
RUBY
end
it 'does not register an offense when nested conditional has an `else` branch' do
expect_no_offenses(<<~RUBY)
if foo
if bar
do_something
else
do_something_else
end
end
RUBY
end
it 'does not register an offense for nested conditionals when outer conditional has an `else` branch' do
expect_no_offenses(<<~RUBY)
if foo
do_something if bar
else
do_something_else
end
RUBY
end
it 'does not register an offense when using nested modifier on value assigned in single condition' do
expect_no_offenses(<<~RUBY)
if var = foo
do_something if var
end
RUBY
end
it 'does not register an offense when using nested modifier on value assigned in multiple conditions' do
expect_no_offenses(<<~RUBY)
if cond && var = foo
do_something if var
end
RUBY
end
context 'when the inner condition has a send node without parens' do
context 'in guard style' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
do_something if ok? bar
^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && ok?(bar)
do_something
end
RUBY
end
context 'with a `csend` node' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
do_something if obj&.ok? bar
^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && obj&.ok?(bar)
do_something
end
RUBY
end
end
end
context 'in modifier style' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
if ok? bar
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && ok?(bar)
do_something
end
RUBY
end
context 'with a `csend` node' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
if bar&.baz quux
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && bar&.baz(quux)
do_something
end
RUBY
end
end
context 'with a block' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
if ok? bar do
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
end
RUBY
expect_correction(<<~RUBY)
if foo && (ok? bar do
do_something
end)
end
RUBY
end
end
context 'with a numblock' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
if ok? bar do
^^ Consider merging nested conditions into outer `if` conditions.
_1
end
end
end
RUBY
expect_correction(<<~RUBY)
if foo && (ok? bar do
_1
end)
end
RUBY
end
end
end
end
context 'when the inner condition has a send node with parens' do
context 'in guard style' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
do_something if ok?(bar)
^^ Consider merging nested conditions into outer `if` conditions.
end
RUBY
expect_correction(<<~RUBY)
if foo && ok?(bar)
do_something
end
RUBY
end
end
context 'in modifier style' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
if foo
if ok?(bar)
^^ Consider merging nested conditions into outer `if` conditions.
do_something
end
end
RUBY
expect_correction(<<~RUBY)
if foo && ok?(bar)
do_something
end
RUBY
end
end
end
context 'when AllowModifier is true' do
let(:cop_config) { { 'AllowModifier' => true } }
it 'does not register an offense when using nested modifier conditional' do
expect_no_offenses(<<~RUBY)
if foo
do_something if bar
end if baz
RUBY
end
end
it 'registers an offense and corrects when using nested `unless` within `if` followed by another `if`' do
expect_offense(<<~RUBY)
if foo
unless bar
^^^^^^ Consider merging nested conditions into outer `if` conditions.
if baz
^^ Consider merging nested conditions into outer `unless` conditions.
do_something
end
end
end
RUBY
expect_correction(<<~RUBY)
if foo && !bar && baz
do_something
end
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_freeze_spec.rb | spec/rubocop/cop/style/redundant_freeze_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantFreeze, :config do
let(:prefix) { nil }
shared_examples 'immutable objects' do |o|
it "registers an offense for frozen #{o}" do
expect_offense([prefix, <<~RUBY].compact.join("\n"), o: o)
CONST = %{o}.freeze
^{o}^^^^^^^ Do not freeze immutable objects, as freezing them has no effect.
RUBY
expect_correction([prefix, <<~RUBY].compact.join("\n"))
CONST = #{o}
RUBY
end
end
it_behaves_like 'immutable objects', '1'
it_behaves_like 'immutable objects', '1.5'
it_behaves_like 'immutable objects', ':sym'
it_behaves_like 'immutable objects', ':""'
it_behaves_like 'immutable objects', "'foo'.count"
it_behaves_like 'immutable objects', '(1 + 2)'
it_behaves_like 'immutable objects', '(2 > 1)'
it_behaves_like 'immutable objects', "('a' > 'b')"
it_behaves_like 'immutable objects', '(a > b)'
it_behaves_like 'immutable objects', '[1, 2, 3].size'
it_behaves_like 'immutable objects', '[1, 2, 3].count { |x| bar?(x) }'
it_behaves_like 'immutable objects', '[1, 2, 3].count { bar?(_1) }'
shared_examples 'mutable objects' do |o|
it "allows #{o} with freeze" do
source = [prefix, "CONST = #{o}.freeze"].compact.join("\n")
expect_no_offenses(source)
end
end
it_behaves_like 'mutable objects', '[1, 2, 3]'
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', '"top#@foo"'
it_behaves_like 'mutable objects', '"top#@@foo"'
it_behaves_like 'mutable objects', '"top#$foo"'
it_behaves_like 'mutable objects', "('a' + 'b')"
it_behaves_like 'mutable objects', "('a' * 20)"
it_behaves_like 'mutable objects', '(a + b)'
it_behaves_like 'mutable objects', '([42] * 42)'
it_behaves_like 'mutable objects', "ENV['foo']"
it_behaves_like 'mutable objects', "::ENV['foo']"
it 'allows .freeze on method call' do
expect_no_offenses('TOP_TEST = Something.new.freeze')
end
context 'when `AllCops/StringLiteralsFrozenByDefault: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'StringLiteralsFrozenByDefault' => true })
end
context 'when the frozen string literal comment is missing' do
it_behaves_like 'immutable objects', '""'
end
context 'when the frozen string literal comment is true' do
let(:prefix) { '# frozen_string_literal: true' }
it_behaves_like 'immutable objects', '""'
end
context 'when the frozen string literal comment is false' do
let(:prefix) { '# frozen_string_literal: false' }
it_behaves_like 'mutable objects', '""'
end
end
context 'when `AllCops/StringLiteralsFrozenByDefault: false`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'StringLiteralsFrozenByDefault' => false })
end
context 'when the frozen string literal comment is missing' do
it_behaves_like 'mutable objects', '""'
end
context 'when the frozen string literal comment is true' do
let(:prefix) { '# frozen_string_literal: true' }
it_behaves_like 'immutable objects', '""'
end
context 'when the frozen string literal comment is false' do
let(:prefix) { '# frozen_string_literal: false' }
it_behaves_like 'mutable objects', '""'
end
end
context 'when the receiver is a 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}"'
it_behaves_like 'immutable objects', '"#@a"'
it_behaves_like 'immutable objects', '"#@@a"'
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}"'
it_behaves_like 'immutable objects', '"#@a"'
it_behaves_like 'immutable objects', '"#@@a"'
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}"'
it_behaves_like 'immutable objects', '"#@a"'
it_behaves_like 'immutable objects', '"#@@a"'
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}"'
it_behaves_like 'mutable objects', '"#@a"'
it_behaves_like 'mutable objects', '"#@@a"'
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 'mutable objects', '"#@a"'
it_behaves_like 'mutable objects', '"#@@a"'
it_behaves_like 'mutable objects', '"#$a"'
end
context 'when the frozen string literal comment is false' do
let(:prefix) { '# frozen_string_literal: false' }
it_behaves_like 'mutable objects', '"#{a}"'
it_behaves_like 'mutable objects', '"#@a"'
it_behaves_like 'mutable objects', '"#@@a"'
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}"'
it_behaves_like 'mutable objects', '"#@a"'
it_behaves_like 'mutable objects', '"#@@a"'
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', '"#@a"'
it_behaves_like 'immutable objects', '"#@@a"'
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 'mutable objects', '"#{a}"'
it_behaves_like 'mutable objects', '"#@a"'
it_behaves_like 'mutable objects', '"#@@a"'
it_behaves_like 'mutable objects', '"#$a"'
end
end
describe 'Regexp and Range literals' do
# 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
it_behaves_like 'immutable objects', '/./'
it_behaves_like 'immutable objects', '(1..5)'
it_behaves_like 'immutable objects', '(1...5)'
end
context 'Ruby 2.7 or lower', :ruby27, unsupported_on: :prism do
it_behaves_like 'mutable objects', '/./'
it_behaves_like 'mutable objects', '(1..5)'
it_behaves_like 'mutable objects', '(1...5)'
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/map_to_set_spec.rb | spec/rubocop/cop/style/map_to_set_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MapToSet, :config do
%i[map collect].each do |method|
context "for `#{method}.to_set` with block arity 1" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |x| [x, x * 2] }.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo.to_set { |x| [x, x * 2] }
RUBY
end
end
context "for `#{method}.to_set` with block arity 2" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |x, y| [x.to_s, y.to_i] }.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo.to_set { |x, y| [x.to_s, y.to_i] }
RUBY
end
end
context 'when using numbered parameters', :ruby27 do
context "for `#{method}.to_set` with block arity 1" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { [_1, _1 * 2] }.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo.to_set { [_1, _1 * 2] }
RUBY
end
end
context "for `#{method}.to_set` with block arity 2" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { [_1.to_s, _2.to_i] }.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo.to_set { [_1.to_s, _2.to_i] }
RUBY
end
end
end
context "for `#{method}.to_set` with symbol proc" do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method}(&:do_something).to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo.to_set(&:do_something)
RUBY
end
end
context 'when the receiver is an array' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].#{method} { |x| [x, x * 2] }.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].to_set { |x| [x, x * 2] }
RUBY
end
end
context 'when the receiver is a hash' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
{ foo: :bar }.#{method} { |x, y| [x.to_s, y.to_s] }.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
{ foo: :bar }.to_set { |x, y| [x.to_s, y.to_s] }
RUBY
end
end
context 'when chained further' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |x| x * 2 }.to_set.bar
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo.to_set { |x| x * 2 }.bar
RUBY
end
end
context "`#{method}` without `to_set`" do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }
RUBY
end
end
context "`#{method}` followed by `to_set` with a block passed to `to_set`" do
it 'does not register an offense but does not correct' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }.to_set { |x| [x.to_s, x] }
RUBY
end
end
context "`#{method}` followed by `to_set` with a numbered block passed to `to_set`", :ruby27 do
it 'does not register an offense but does not correct' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }.to_set { |x| [x.to_s, x] }
RUBY
end
end
context "`#{method}` followed by `to_set` with an `it` block passed to `to_set`", :ruby34 do
it 'does not register an offense but does not correct' do
expect_no_offenses(<<~RUBY)
foo.#{method} { |x| x * 2 }.to_set { |x| [x.to_s, x] }
RUBY
end
end
context "`map` and `#{method}.to_set` with newlines" do
it 'registers an offense and corrects with newline removal' do
expect_offense(<<~RUBY, method: method)
{foo: bar}
.#{method} { |k, v| [k.to_s, v.do_something] }
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
.to_set
.freeze
RUBY
expect_correction(<<~RUBY)
{foo: bar}
.to_set { |k, v| [k.to_s, v.do_something] }
.freeze
RUBY
end
end
context 'with safe navigation' do
it "registers an offense and corrects for `foo&.#{method}.to_set" do
expect_offense(<<~RUBY, method: method)
foo&.#{method} { |x| [x, x * 2] }.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo&.to_set { |x| [x, x * 2] }
RUBY
end
it "registers an offense and corrects for `foo.#{method}&.to_set" do
expect_offense(<<~RUBY, method: method)
foo.#{method} { |x| [x, x * 2] }&.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo.to_set { |x| [x, x * 2] }
RUBY
end
it "registers an offense and corrects for `foo&.#{method}&.to_set" do
expect_offense(<<~RUBY, method: method)
foo&.#{method} { |x| [x, x * 2] }&.to_set
^{method} Pass a block to `to_set` instead of calling `#{method}.to_set`.
RUBY
expect_correction(<<~RUBY)
foo&.to_set { |x| [x, x * 2] }
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/alias_spec.rb | spec/rubocop/cop/style/alias_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Alias, :config do
context 'when EnforcedStyle is prefer_alias_method' do
let(:cop_config) { { 'EnforcedStyle' => 'prefer_alias_method' } }
it 'registers an offense for alias with symbol args' do
expect_offense(<<~RUBY)
alias :ala :bala
^^^^^ Use `alias_method` instead of `alias`.
RUBY
expect_correction(<<~RUBY)
alias_method :ala, :bala
RUBY
end
it 'registers an offense for alias with bareword args' do
expect_offense(<<~RUBY)
alias ala bala
^^^^^ Use `alias_method` instead of `alias`.
RUBY
expect_correction(<<~RUBY)
alias_method :ala, :bala
RUBY
end
it 'registers an offense for `alias` with interpolated symbol argument' do
expect_offense(<<~'RUBY')
alias :"string#{interpolation}" :symbol
^^^^^ Use `alias_method` instead of `alias`.
RUBY
expect_correction(<<~'RUBY')
alias_method :"string#{interpolation}", :symbol
RUBY
end
it 'does not register an offense for alias_method' do
expect_no_offenses('alias_method :ala, :bala')
end
it 'does not register an offense for alias with gvars' do
expect_no_offenses('alias $ala $bala')
end
it 'does not register an offense for alias in an instance_eval block' do
expect_no_offenses(<<~RUBY)
module M
def foo
instance_eval {
alias bar baz
}
end
end
RUBY
end
it 'does not register an offense for alias_method when calling with no arguments' do
expect_no_offenses('alias_method')
end
it 'registers no offense for alias_method when calling with one argument' do
expect_no_offenses('alias_method :foo')
end
end
context 'when EnforcedStyle is prefer_alias' do
let(:cop_config) { { 'EnforcedStyle' => 'prefer_alias' } }
it 'registers an offense for alias with symbol args' do
expect_offense(<<~RUBY)
alias :ala :bala
^^^^^^^^^^ Use `alias ala bala` instead of `alias :ala :bala`.
RUBY
expect_correction(<<~RUBY)
alias ala bala
RUBY
end
it 'does not register an offense for alias with bareword args' do
expect_no_offenses('alias ala bala')
end
it 'registers an offense for alias_method at the top level' do
expect_offense(<<~RUBY)
alias_method :ala, :bala
^^^^^^^^^^^^ Use `alias` instead of `alias_method` at the top level.
RUBY
expect_correction(<<~RUBY)
alias ala bala
RUBY
end
it 'registers an offense for alias_method in a class block' do
expect_offense(<<~RUBY)
class C
alias_method :ala, :bala
^^^^^^^^^^^^ Use `alias` instead of `alias_method` in a class body.
end
RUBY
expect_correction(<<~RUBY)
class C
alias ala bala
end
RUBY
end
it 'registers an offense for alias_method in a module block' do
expect_offense(<<~RUBY)
module M
alias_method :ala, :bala
^^^^^^^^^^^^ Use `alias` instead of `alias_method` in a module body.
end
RUBY
expect_correction(<<~RUBY)
module M
alias ala bala
end
RUBY
end
it 'does not register an offense for alias in a def' do
expect_no_offenses(<<~RUBY)
def foo
alias :ala :bala
end
RUBY
end
it 'does not register an offense for multiple alias in a def' do
expect_no_offenses(<<~RUBY)
def foo
alias :foo :bar
alias :baz :qux
end
RUBY
end
it 'does not register an offense for `alias` with interpolated symbol argument' do
expect_no_offenses(<<~'RUBY')
alias :"string#{interpolation}" :symbol
RUBY
end
it 'registers an offense for alias in a defs' do
expect_offense(<<~RUBY)
def some_obj.foo
alias :ala :bala
^^^^^ Use `alias_method` instead of `alias`.
end
RUBY
expect_correction(<<~RUBY)
def some_obj.foo
alias_method :ala, :bala
end
RUBY
end
it 'registers an offense for alias in a block' do
expect_offense(<<~RUBY)
included do
alias :ala :bala
^^^^^ Use `alias_method` instead of `alias`.
end
RUBY
expect_correction(<<~RUBY)
included do
alias_method :ala, :bala
end
RUBY
end
it 'does not register an offense for alias_method with explicit receiver' do
expect_no_offenses(<<~RUBY)
class C
receiver.alias_method :ala, :bala
end
RUBY
end
it 'does not register an offense for alias_method in self.method def' do
expect_no_offenses(<<~RUBY)
def self.method
alias_method :ala, :bala
end
RUBY
end
it 'does not register an offense for alias_method in a block' do
expect_no_offenses(<<~RUBY)
dsl_method do
alias_method :ala, :bala
end
RUBY
end
it 'does not register an offense for alias_method with non-literal constant argument' do
expect_no_offenses(<<~RUBY)
alias_method :bar, FOO
RUBY
end
it 'does not register an offense for alias_method with non-literal method call argument' do
expect_no_offenses(<<~RUBY)
alias_method :baz, foo.bar
RUBY
end
it 'does not register an offense for alias in an instance_eval block' do
expect_no_offenses(<<~RUBY)
module M
def foo
instance_eval {
alias bar baz
}
end
end
RUBY
end
it 'registers no offense for alias_method when calling with no arguments' do
expect_no_offenses('alias_method')
end
it 'registers no offense for alias_method when calling with one argument' do
expect_no_offenses('alias_method :foo')
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_read_spec.rb | spec/rubocop/cop/style/file_read_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::FileRead, :config do
it 'does not register an offense when not reading from the block variable' do
expect_no_offenses(<<~RUBY)
File.open(filename) do |f|
something_else.read
end
RUBY
end
it 'registers an offense for and corrects `File.open(filename).read`' do
expect_offense(<<~RUBY)
File.open(filename).read
^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.read`.
RUBY
expect_correction(<<~RUBY)
File.read(filename)
RUBY
end
it 'registers an offense for and corrects `::File.open(filename).read`' do
expect_offense(<<~RUBY)
::File.open(filename).read
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.read`.
RUBY
expect_correction(<<~RUBY)
::File.read(filename)
RUBY
end
it 'registers an offense for and corrects the `File.open` with symbolic read proc (implicit text mode)' do
expect_offense(<<~RUBY)
File.open(filename, &:read)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.read`.
RUBY
expect_correction(<<~RUBY)
File.read(filename)
RUBY
end
it 'registers an offense for and corrects the `File.open` with inline read block (implicit text mode)' do
expect_offense(<<~RUBY)
File.open(filename) { |f| f.read }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.read`.
RUBY
expect_correction(<<~RUBY)
File.read(filename)
RUBY
end
it 'registers an offense for and corrects the `File.open` with multiline read block (implicit text mode)' do
expect_offense(<<~RUBY)
File.open(filename) do |f|
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `File.read`.
f.read
end
RUBY
expect_correction(<<~RUBY)
File.read(filename)
RUBY
end
described_class::READ_FILE_START_TO_FINISH_MODES.each do |mode|
it "registers an offense for and corrects `File.open(filename, '#{mode}').read`" do
read_method = mode.end_with?('b') ? :binread : :read
expect_offense(<<~RUBY)
File.open(filename, '#{mode}').read
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^ Use `File.#{read_method}`.
RUBY
expect_correction(<<~RUBY)
File.#{read_method}(filename)
RUBY
end
it "registers an offense for and corrects the `File.open` with symbolic read proc (mode '#{mode}')" do
read_method = mode.end_with?('b') ? :binread : :read
expect_offense(<<~RUBY)
File.open(filename, '#{mode}', &:read)
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^^ Use `File.#{read_method}`.
RUBY
expect_correction(<<~RUBY)
File.#{read_method}(filename)
RUBY
end
it "registers an offense for and corrects the `File.open` with inline read block (mode '#{mode}')" do
read_method = mode.end_with?('b') ? :binread : :read
expect_offense(<<~RUBY)
File.open(filename, '#{mode}') { |f| f.read }
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^^^^^^^^^ Use `File.#{read_method}`.
RUBY
expect_correction(<<~RUBY)
File.#{read_method}(filename)
RUBY
end
it "registers an offense for and corrects the `File.open` with multiline read block (mode '#{mode}')" do
read_method = mode.end_with?('b') ? :binread : :read
expect_offense(<<~RUBY)
File.open(filename, '#{mode}') do |f|
^^^^^^^^^^^^^^^^^^^^^#{'^' * mode.length}^^^^^^^^^ Use `File.#{read_method}`.
f.read
end
RUBY
expect_correction(<<~RUBY)
File.#{read_method}(filename)
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/method_call_without_args_parentheses_spec.rb | spec/rubocop/cop/style/method_call_without_args_parentheses_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MethodCallWithoutArgsParentheses, :config do
it 'registers an offense for parens in method call without args' do
expect_offense(<<~RUBY)
top.test()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
top.test
RUBY
end
it 'accepts parentheses for methods starting with an upcase letter' do
expect_no_offenses('Test()')
end
it 'accepts parens in method call with args' do
expect_no_offenses('top.test(a)')
end
it 'accepts special lambda call syntax' do
# Style/LambdaCall checks for this syntax
expect_no_offenses('thing.()')
end
it 'accepts parens after not' do
expect_no_offenses('not(something)')
end
it 'does not register an offense when using `it()` in a single line block' do
# `Lint/ItWithoutArgumentsInBlock` respects for this syntax.
expect_no_offenses(<<~RUBY)
0.times { it() }
RUBY
end
it 'registers an offense when using `foo.it()` in a single line block' do
# `Lint/ItWithoutArgumentsInBlock` respects for this syntax.
expect_offense(<<~RUBY)
0.times { foo.it() }
^^ Do not use parentheses for method calls with no arguments.
RUBY
end
it 'registers an offense when using `foo&.it()` in a single line block' do
# `Lint/ItWithoutArgumentsInBlock` respects for this syntax.
expect_offense(<<~RUBY)
0.times { foo&.it() }
^^ Do not use parentheses for method calls with no arguments.
RUBY
end
it 'does not register an offense when using `it()` in a multiline block' do
# `Lint/ItWithoutArgumentsInBlock` respects for this syntax.
expect_no_offenses(<<~RUBY)
0.times do
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
it()
^^ Do not use parentheses for method calls with no arguments.
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 { ||
it()
^^ Do not use parentheses for method calls with no arguments.
}
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|
it()
^^ Do not use parentheses for method calls with no arguments.
}
RUBY
end
context 'when AllowedMethods is enabled' do
let(:cop_config) { { 'AllowedMethods' => %w[s] } }
it 'allows a listed method' do
expect_no_offenses('s()')
end
it 'allows a listed method used with safe navigation' do
expect_no_offenses('foo&.s()')
end
end
context 'when AllowedPatterns is enabled' do
let(:cop_config) { { 'AllowedPatterns' => ['test'] } }
it 'allows a method that matches' do
expect_no_offenses('my_test()')
end
it 'allows a method that matches with safe navigation' do
expect_no_offenses('foo&.my_test()')
end
end
context 'assignment to a variable with the same name' do
it 'accepts parens in local variable assignment' do
expect_no_offenses('test = test()')
end
it 'registers an offense when calling method on a receiver' do
expect_offense(<<~RUBY)
test = x.test()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
test = x.test
RUBY
end
it 'registers an offense when calling method on a receiver with safe navigation' do
expect_offense(<<~RUBY)
test = x&.test()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
test = x&.test
RUBY
end
it 'accepts parens in default argument assignment' do
expect_no_offenses(<<~RUBY)
def foo(test = test())
end
RUBY
end
it 'accepts parens in shorthand assignment' do
expect_no_offenses('test ||= test()')
end
it 'accepts parens in parallel assignment' do
expect_no_offenses('one, test = 1, test()')
end
it 'accepts parens in complex assignment' do
expect_no_offenses(<<~RUBY)
test = begin
case a
when b
c = test() if d
end
end
RUBY
end
it 'registers an empty parens offense for array mass assignment with same name' do
expect_offense(<<~RUBY)
A = [1, 2]
def c; A; end
c[2], x = c()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
A = [1, 2]
def c; A; end
c[2], x = c
RUBY
end
end
it 'registers an offense for `obj.method ||= func()`' do
expect_offense(<<~RUBY)
obj.method ||= func()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
obj.method ||= func
RUBY
end
it 'registers an offense for `obj.method &&= func()`' do
expect_offense(<<~RUBY)
obj.method &&= func()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
obj.method &&= func
RUBY
end
it 'registers an offense for `obj.method += func()`' do
expect_offense(<<~RUBY)
obj.method += func()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
obj.method += func
RUBY
end
# These will be offenses for the EmptyLiteral cop. The autocorrect loop will
# handle that.
it 'autocorrects calls that could be empty literals' do
expect_offense(<<~RUBY)
Hash.new()
^^ Do not use parentheses for method calls with no arguments.
Array.new()
^^ Do not use parentheses for method calls with no arguments.
String.new()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
Hash.new
Array.new
String.new
RUBY
end
context 'method call as argument' do
it 'accepts without parens' do
expect_no_offenses('_a = c(d.e)')
end
it 'registers an offense with empty parens' do
expect_offense(<<~RUBY)
_a = c(d())
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
_a = c(d)
RUBY
end
it 'registers an empty parens offense for multiple assignment' do
expect_offense(<<~RUBY)
_a, _b, _c = d(e())
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
_a, _b, _c = d(e)
RUBY
end
it 'registers an empty parens offense for multiple assignment with safe navigation' do
expect_offense(<<~RUBY)
_a, _b, _c = d&.e()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
_a, _b, _c = d&.e
RUBY
end
end
it 'registers an empty parens offense for hash mass assignment' do
expect_offense(<<~RUBY)
h = {}
h[:a], h[:b] = c()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
h = {}
h[:a], h[:b] = c
RUBY
end
it 'registers an empty parens offense for array mass assignment' do
expect_offense(<<~RUBY)
a = []
a[0], a[10] = c()
^^ Do not use parentheses for method calls with no arguments.
RUBY
expect_correction(<<~RUBY)
a = []
a[0], a[10] = c
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/numeric_literal_prefix_spec.rb | spec/rubocop/cop/style/numeric_literal_prefix_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NumericLiteralPrefix, :config do
context 'octal literals' do
context 'when config is zero_with_o' do
let(:cop_config) { { 'EnforcedOctalStyle' => 'zero_with_o' } }
it 'registers an offense for prefixes `0` and `0O`' do
expect_offense(<<~RUBY)
a = 01234
^^^^^ Use 0o for octal literals.
b(0O1234)
^^^^^^ Use 0o for octal literals.
RUBY
expect_correction(<<~RUBY)
a = 0o1234
b(0o1234)
RUBY
end
it 'does not register offense for lowercase prefix' do
expect_no_offenses(<<~RUBY)
a = 0o101
b = 0o567
RUBY
end
end
context 'when config is zero_only' do
let(:cop_config) { { 'EnforcedOctalStyle' => 'zero_only' } }
it 'registers an offense for prefix `0O` and `0o`' do
expect_offense(<<~RUBY)
a = 0O1234
^^^^^^ Use 0 for octal literals.
b(0o1234)
^^^^^^ Use 0 for octal literals.
RUBY
expect_correction(<<~RUBY)
a = 01234
b(01234)
RUBY
end
it 'does not register offense for prefix `0`' do
expect_no_offenses('b = 0567')
end
end
end
context 'hex literals' do
it 'registers an offense for uppercase prefix' do
expect_offense(<<~RUBY)
a = 0X1AC
^^^^^ Use 0x for hexadecimal literals.
b(0XABC)
^^^^^ Use 0x for hexadecimal literals.
RUBY
expect_correction(<<~RUBY)
a = 0x1AC
b(0xABC)
RUBY
end
it 'does not register offense for lowercase prefix' do
expect_no_offenses('a = 0x101')
end
end
context 'binary literals' do
it 'registers an offense for uppercase prefix' do
expect_offense(<<~RUBY)
a = 0B10101
^^^^^^^ Use 0b for binary literals.
b(0B111)
^^^^^ Use 0b for binary literals.
RUBY
expect_correction(<<~RUBY)
a = 0b10101
b(0b111)
RUBY
end
it 'does not register offense for lowercase prefix' do
expect_no_offenses('a = 0b101')
end
end
context 'decimal literals' do
it 'registers an offense for prefixes' do
expect_offense(<<~RUBY)
a = 0d1234
^^^^^^ Do not use prefixes for decimal literals.
b(0D1990)
^^^^^^ Do not use prefixes for decimal literals.
RUBY
expect_correction(<<~RUBY)
a = 1234
b(1990)
RUBY
end
it 'does not register offense for no prefix' do
expect_no_offenses('a = 101')
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/word_array_spec.rb | spec/rubocop/cop/style/word_array_spec.rb | # frozen_string_literal: true
require 'timeout'
RSpec.describe RuboCop::Cop::Style::WordArray, :config do
include EncodingHelper
before do
# Reset data which is shared by all instances of WordArray
described_class.largest_brackets = -Float::INFINITY
end
let(:other_cops) do
{
'Style/PercentLiteralDelimiters' => {
'PreferredDelimiters' => {
'default' => '()'
}
}
}
end
context 'when EnforcedStyle is percent' do
let(:cop_config) do
{ 'MinSize' => 0,
'WordRegex' => /\A(?:\p{Word}|\p{Word}-\p{Word}|\n|\t)+\z/,
'EnforcedStyle' => 'percent' }
end
it 'registers an offense for arrays of single quoted strings' do
expect_offense(<<~RUBY)
['one', 'two', 'three']
^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w(one two three)
RUBY
end
it 'registers an offense for arrays of double quoted strings' do
expect_offense(<<~RUBY)
["one", "two", "three"]
^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w(one two three)
RUBY
end
it 'registers an offense for arrays of strings containing hyphens' do
expect_offense(<<~RUBY)
['foo', 'bar', 'foo-bar']
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w(foo bar foo-bar)
RUBY
end
context 'when the default external encoding is UTF-8' do
around do |example|
with_default_external_encoding(Encoding::UTF_8) { example.run }
end
it 'registers an offense for arrays of unicode word characters' do
expect_offense(<<~RUBY, wide: '中文网')
["ВУЗ", "вуз", "%{wide}"]
^^^^^^^^^^^^^^^^^{wide}^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w(ВУЗ вуз 中文网)
RUBY
end
end
context 'when the default external encoding is US-ASCII' do
around do |example|
with_default_external_encoding(Encoding::US_ASCII) { example.run }
end
it 'registers an offense for arrays of unicode word characters' do
expect_offense(<<~RUBY, wide: '中文网')
["ВУЗ", "вуз", "%{wide}"]
^^^^^^^^^^^^^^^^^{wide}^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%W(\u0412\u0423\u0417 \u0432\u0443\u0437 \u4E2D\u6587\u7F51)
RUBY
end
end
it 'registers an offense for arrays with character constants' do
expect_offense(<<~'RUBY')
["one", ?\n]
^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%W(one \n)
RUBY
end
it 'uses %W when autocorrecting strings with embedded newlines and tabs' do
expect_offense(<<~RUBY)
["one
^^^^^ Use `%w` or `%W` for an array of words.
", "hi\tthere"]
RUBY
expect_correction(<<~'RUBY')
%W(one\n hi\tthere)
RUBY
end
it 'registers an offense for strings with newline and tab escapes' do
expect_offense(<<~'RUBY')
["one\n", "hi\tthere"]
^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%W(one\n hi\tthere)
RUBY
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 starting with %w' do
expect_no_offenses('%w(one two three)')
end
it 'does not register an offense for array with empty strings' do
expect_no_offenses('["", "two", "three"]')
end
it 'does not register an offense on non-word strings' do
expect_no_offenses("['-', '----']")
end
it 'registers an offense in a non-ambiguous block context' do
expect_offense(<<~RUBY)
foo(['bar', 'baz']) { qux }
^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
foo(%w(bar baz)) { qux }
RUBY
end
it 'does not register offense for array with allowed number of strings' do
cop_config['MinSize'] = 4
expect_no_offenses('["one", "two", "three"]')
end
it 'does not register an offense for an array with comments in it' do
expect_no_offenses(<<~RUBY)
[
"foo", # comment here
"bar", # this thing was done because of a bug
"baz" # do not delete this line
]
RUBY
end
it 'registers an offense for an array with comments outside of it' do
expect_offense(<<~RUBY)
[
^ Use `%w` or `%W` for an array of words.
"foo",
"bar",
"baz"
] # test
RUBY
expect_correction(<<~RUBY)
%w(
foo
bar
baz
) # test
RUBY
end
it 'autocorrects an array of words' do
expect_offense(<<~RUBY)
['one', %q(two), 'three']
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w(one two three)
RUBY
end
it 'autocorrects an array with one element' do
expect_offense(<<~RUBY)
['one']
^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w(one)
RUBY
end
it 'autocorrects an array of words and character constants' do
expect_offense(<<~'RUBY')
[%|one|, %Q(two), ?\n, ?\t]
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%W(one two \n \t)
RUBY
end
it 'keeps the line breaks in place after autocorrect' do
expect_offense(<<~RUBY)
['one',
^^^^^^^ Use `%w` or `%W` for an array of words.
'two', 'three']
RUBY
expect_correction(<<~RUBY)
%w(one
two three)
RUBY
end
it 'autocorrects an array of words in multiple lines' do
expect_offense(<<~RUBY)
[
^ Use `%w` or `%W` for an array of words.
"foo",
"bar",
"baz"
]
RUBY
expect_correction(<<~RUBY)
%w(
foo
bar
baz
)
RUBY
end
it 'autocorrects an array of words using partial newlines' do
expect_offense(<<~RUBY)
["foo", "bar", "baz",
^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
"boz", "buz",
"biz"]
RUBY
expect_correction(<<~RUBY)
%w(foo bar baz
boz buz
biz)
RUBY
end
it 'detects right value of MinSize to use for --auto-gen-config' do
expect_offense(<<~RUBY)
['one', 'two', 'three']
^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
%w(a b c d)
RUBY
expect_correction(<<~RUBY)
%w(one two three)
%w(a b c d)
RUBY
expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'percent', 'MinSize' => 4)
end
it 'detects when the cop must be disabled to avoid offenses' do
expect_offense(<<~RUBY)
['one', 'two', 'three']
^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
%w(a b)
RUBY
expect_correction(<<~RUBY)
%w(one two three)
%w(a b)
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it "doesn't fail in wacky ways when multiple cop instances are used" do
# Regression test for GH issue #2740
cop1 = described_class.new(config)
cop2 = described_class.new(config)
RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
# Don't use `expect_offense`; it resets `config_to_allow_offenses` each
# time, which suppresses the bug we are checking for
_investigate(cop1, parse_source("['g', 'h']"))
_investigate(cop2, parse_source('%w(a b c)'))
expect(cop2.config_to_allow_offenses).to eq('EnforcedStyle' => 'percent', 'MinSize' => 3)
end
it 'registers an offense for a %w() array containing spaces' do
expect_offense(<<~'RUBY')
%w(one\ two three\ four)
^^^^^^^^^^^^^^^^^^^^^^^^ Use `['one two', 'three four']` for an array of words.
RUBY
expect_correction(<<~RUBY)
['one two', 'three four']
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
end
it 'does not register an offense for a %w() array containing non word characters' do
expect_no_offenses(<<~RUBY)
%w(% %i %I %q %Q %r %s %w %W %x)
RUBY
end
it 'corrects properly when there is an extra trailing comma' do
expect_offense(<<~RUBY)
A = ["one", "two",]
^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
A = %w(one two)
RUBY
end
it 'registers an offense and corrects for array within 2d array' do
expect_offense(<<~RUBY)
[
['one', 'One'],
^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
['two', 'Two']
^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
]
RUBY
expect_correction(<<~RUBY)
[
%w(one One),
%w(two Two)
]
RUBY
end
it 'does not register an offense for array within 2d array containing subarrays with complex content' do
expect_no_offenses(<<~RUBY)
[
['one', 'One'],
['two', 'Two'],
['forty two', 'Forty Two']
]
RUBY
end
it 'investigates a large matrix in a reasonable amount of time' do
expect do
Timeout.timeout(5) do # Should take under a second, but 5 seconds is plenty of margin
expect_no_offenses(<<~RUBY)
[
#{Array.new(999) do |n|
"['#{n}', 'simple_content'],"
end.join("\n ")}
['100', 'complex content'],
]
RUBY
end
end.not_to raise_error, 'did not complete investigation in reasonable time'
end
it 'registers an offense and corrects for nested arrays' do
expect_offense(<<~RUBY)
[['one', 'One'], 2, 3]
^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
[%w(one One), 2, 3]
RUBY
end
end
context 'when EnforcedStyle is array' do
let(:cop_config) do
{ 'MinSize' => 0,
'WordRegex' => /\A(?:\p{Word}|\p{Word}-\p{Word}|\n|\t)+\z/,
'EnforcedStyle' => 'brackets' }
end
it 'does not register an offense for arrays of single quoted strings' do
expect_no_offenses("['one', 'two', 'three']")
end
it 'does not register an offense for arrays of double quoted strings' do
expect_no_offenses('["one", "two", "three"]')
end
it 'does not register an offense for arrays of strings with hyphens' do
expect_no_offenses("['foo', 'bar', 'foo-bar']")
end
it 'does not register an offense for arrays of strings with spaces' do
expect_no_offenses("['foo bar', 'baz quux']")
end
it 'registers an offense for a %w() array' do
expect_offense(<<~RUBY)
%w(one two three)
^^^^^^^^^^^^^^^^^ Use `['one', 'two', 'three']` for an array of words.
RUBY
expect_correction(<<~RUBY)
['one', 'two', 'three']
RUBY
end
it 'registers an offense when assigning `%w()` array' do
expect_offense(<<~RUBY)
FOO = %w(one@example.com two@example.com)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `['one@example.com', 'two@example.com']` for an array of words.
RUBY
expect_correction(<<~RUBY)
FOO = ['one@example.com', 'two@example.com']
RUBY
end
it 'registers an offense when assigning multiline `%w()` array' do
expect_offense(<<~RUBY)
FOO = %w(
^^^ Use an array literal `[...]` for an array of words.
one@example.com
two@example.com
)
RUBY
expect_correction(<<~RUBY)
FOO = [
'one@example.com',
'two@example.com'
]
RUBY
end
it 'registers an offense for an empty %w() array' do
expect_offense(<<~RUBY)
%w()
^^^^ Use `[]` for an array of words.
RUBY
expect_correction(<<~RUBY)
[]
RUBY
end
it 'autocorrects a %w() array which uses single quotes' do
expect_offense(<<~RUBY)
%w(one's two's three's)
^^^^^^^^^^^^^^^^^^^^^^^ Use `["one's", "two's", "three's"]` for an array of words.
RUBY
expect_correction(<<~RUBY)
["one's", "two's", "three's"]
RUBY
end
it 'autocorrects a %W() array which uses escapes' do
expect_offense(<<~'RUBY')
%W(\n \t \b \v \f)
^^^^^^^^^^^^^^^^^^ Use `["\n", "\t", "\b", "\v", "\f"]` for an array of words.
RUBY
expect_correction(<<~'RUBY')
["\n", "\t", "\b", "\v", "\f"]
RUBY
end
it 'autocorrects a %w() array which uses string with hyphen' do
expect_offense(<<~RUBY)
%w(foo bar foo-bar)
^^^^^^^^^^^^^^^^^^^ Use `['foo', 'bar', 'foo-bar']` for an array of words.
RUBY
expect_correction(<<~RUBY)
['foo', 'bar', 'foo-bar']
RUBY
end
it 'autocorrects multiline %w() array' do
expect_offense(<<~RUBY)
%w(
^^^ Use an array literal `[...]` for an array of words.
foo
bar
)
RUBY
expect_correction(<<~RUBY)
[
'foo',
'bar'
]
RUBY
end
it 'autocorrects a %W() array which uses string with hyphen' do
expect_offense(<<~'RUBY')
%W(foo bar #{foo}-bar)
^^^^^^^^^^^^^^^^^^^^^^ Use `['foo', 'bar', "#{foo}-bar"]` for an array of words.
RUBY
expect_correction(<<~'RUBY')
['foo', 'bar', "#{foo}-bar"]
RUBY
end
it 'autocorrects a %W() array which uses string interpolation' do
expect_offense(<<~'RUBY')
%W(#{foo}bar baz)
^^^^^^^^^^^^^^^^^ Use `["#{foo}bar", 'baz']` for an array of words.
RUBY
expect_correction(<<~'RUBY')
["#{foo}bar", 'baz']
RUBY
end
it "doesn't fail on strings which are not valid UTF-8" do
# Regression test, see GH issue 2671
expect_no_offenses(<<~'RUBY')
["\xC0",
"\xC2\x4a",
"\xC2\xC2",
"\x4a\x82",
"\x82\x82",
"\xe1\x82\x4a",
]
RUBY
end
it "doesn't fail with `encoding: binary`" do
expect_no_offenses(<<~'RUBY')
# -*- encoding: binary -*-
["\xC0"] # Invalid as UTF-8
['a'] # Valid as UTF-8 and ASCII
["あ"] # Valid as UTF-8
RUBY
end
end
context 'with a custom WordRegex configuration' do
let(:cop_config) { { 'MinSize' => 0, 'WordRegex' => /\A[\w@.]+\z/ } }
it 'registers an offense for arrays of email addresses' do
expect_offense(<<~RUBY)
['a@example.com', 'b@example.com']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w(a@example.com b@example.com)
RUBY
end
end
context 'when the WordRegex configuration is not a Regexp' do
let(:cop_config) { { 'WordRegex' => 'just_a_string' } }
it 'still parses the code without raising an error' do
expect { expect_no_offenses('') }.not_to raise_error
end
end
context 'with a WordRegex configuration which accepts almost anything' do
let(:cop_config) { { 'MinSize' => 0, 'WordRegex' => /\S+/ } }
it 'uses %W when autocorrecting strings with non-printable chars' do
expect_offense(<<~'RUBY')
["\x1f\x1e", "hello"]
^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%W(\u001F\u001E hello)
RUBY
end
it 'uses %w for strings which only appear to have an escape' do
expect_offense(<<~'RUBY')
['hi\tthere', 'again\n']
^^^^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%w(hi\tthere again\n)
RUBY
end
end
context 'with a treacherous WordRegex configuration' do
let(:cop_config) { { 'MinSize' => 0, 'WordRegex' => /[\w \[\]()]/ } }
it "doesn't break when words contain whitespace" do
expect_no_offenses(<<~RUBY)
['hi there', 'something\telse']
RUBY
end
it "doesn't break when words contain delimiters" do
expect_offense(<<~RUBY)
[')', ']', '(']
^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%w(\) ] \()
RUBY
end
context 'when PreferredDelimiters is specified' do
let(:other_cops) do
{
'Style/PercentLiteralDelimiters' => {
'PreferredDelimiters' => {
'default' => '[]'
}
}
}
end
it 'autocorrects an array with delimiters' do
expect_offense(<<~RUBY)
[')', ']', '(', '[']
^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~'RUBY')
%w[) \] ( \[]
RUBY
end
it 'autocorrects balanced pairs of delimiters without excessive escaping' do
expect_offense(<<~RUBY)
['a', 'b[]', 'c[][]']
^^^^^^^^^^^^^^^^^^^^^ Use `%w` or `%W` for an array of words.
RUBY
expect_correction(<<~RUBY)
%w[a b[] c[][]]
RUBY
end
end
end
context 'with non-default MinSize' do
let(:cop_config) do
{ 'MinSize' => 2,
'WordRegex' => /\A(?:\p{Word}|\p{Word}-\p{Word}|\n|\t)+\z/,
'EnforcedStyle' => 'percent' }
end
it 'does not autocorrect arrays of one symbol if MinSize > 1' do
expect_no_offenses('["one"]')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/array_first_last_spec.rb | spec/rubocop/cop/style/array_first_last_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ArrayFirstLast, :config do
it 'registers an offense when using `[0]`' do
expect_offense(<<~RUBY)
arr[0]
^^^ Use `first`.
RUBY
expect_correction(<<~RUBY)
arr.first
RUBY
end
it 'registers an offense when using `[-1]`' do
expect_offense(<<~RUBY)
arr[-1]
^^^^ Use `last`.
RUBY
expect_correction(<<~RUBY)
arr.last
RUBY
end
it 'does not register an offense when using `[1]`' do
expect_no_offenses(<<~RUBY)
arr[1]
RUBY
end
it 'does not register an offense when using `[index]`' do
expect_no_offenses(<<~RUBY)
arr[index]
RUBY
end
it 'does not register an offense when using `[0]=`' do
expect_no_offenses(<<~RUBY)
arr[0] = 1
RUBY
end
it 'does not register an offense when using `first`' do
expect_no_offenses(<<~RUBY)
arr.first
RUBY
end
it 'does not register an offense when using `last`' do
expect_no_offenses(<<~RUBY)
arr.last
RUBY
end
it 'does not register an offense when using `[0][0]`' do
expect_no_offenses(<<~RUBY)
arr[0][-1]
RUBY
end
it 'registers an offense when using `arr.[](0)`' do
expect_offense(<<~RUBY)
arr.[](0)
^^^^^ Use `first`.
RUBY
expect_correction(<<~RUBY)
arr.first
RUBY
end
it 'registers an offense when using `arr&.[](0)`' do
expect_offense(<<~RUBY)
arr&.[](0)
^^^^^ Use `first`.
RUBY
expect_correction(<<~RUBY)
arr&.first
RUBY
end
it 'registers an offense when using `arr.[] 0`' do
expect_offense(<<~RUBY)
arr.[] 0
^^^^ Use `first`.
RUBY
expect_correction(<<~RUBY)
arr.first
RUBY
end
it 'registers an offense when using `arr&.[] 0`' do
expect_offense(<<~RUBY)
arr&.[] 0
^^^^ Use `first`.
RUBY
expect_correction(<<~RUBY)
arr&.first
RUBY
end
it 'registers an offense when using `arr.[](-1)`' do
expect_offense(<<~RUBY)
arr.[](-1)
^^^^^^ Use `last`.
RUBY
expect_correction(<<~RUBY)
arr.last
RUBY
end
it 'registers an offense when using `arr&.[](-1)`' do
expect_offense(<<~RUBY)
arr&.[](-1)
^^^^^^ Use `last`.
RUBY
expect_correction(<<~RUBY)
arr&.last
RUBY
end
it 'registers an offense when using `arr.[] -1`' do
expect_offense(<<~RUBY)
arr.[] -1
^^^^^ Use `last`.
RUBY
expect_correction(<<~RUBY)
arr.last
RUBY
end
it 'registers an offense when using `arr&.[] -1`' do
expect_offense(<<~RUBY)
arr&.[] -1
^^^^^ Use `last`.
RUBY
expect_correction(<<~RUBY)
arr&.last
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/return_nil_spec.rb | spec/rubocop/cop/style/return_nil_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ReturnNil, :config do
context 'when enforced style is `return`' do
let(:config) do
RuboCop::Config.new(
'Style/ReturnNil' => {
'EnforcedStyle' => 'return',
'SupportedStyles' => %w[return return_nil]
}
)
end
it 'registers an offense for return nil' do
expect_offense(<<~RUBY)
return nil
^^^^^^^^^^ Use `return` instead of `return nil`.
RUBY
expect_correction(<<~RUBY)
return
RUBY
end
it 'does not register an offense for returning others' do
expect_no_offenses('return 2')
end
it 'does not register an offense for return nil from iterators' do
expect_no_offenses(<<~RUBY)
loop do
return if x
end
RUBY
end
end
context 'when enforced style is `return_nil`' do
let(:config) do
RuboCop::Config.new(
'Style/ReturnNil' => {
'EnforcedStyle' => 'return_nil',
'SupportedStyles' => %w[return return_nil]
}
)
end
it 'registers an offense for return' do
expect_offense(<<~RUBY)
return
^^^^^^ Use `return nil` instead of `return`.
RUBY
expect_correction(<<~RUBY)
return nil
RUBY
end
it 'does not register an offense for returning others' do
expect_no_offenses('return 2')
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_else_spec.rb | spec/rubocop/cop/style/empty_else_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyElse, :config do
let(:missing_else_config) { {} }
shared_examples 'autocorrect' do |keyword|
context 'MissingElse is disabled' do
it 'does autocorrection' do
expect_offense(source)
expect_correction(corrected_source)
end
end
%w[both if case].each do |missing_else_style|
context "MissingElse is #{missing_else_style}" do
let(:missing_else_config) do
{ 'Enabled' => true,
'EnforcedStyle' => missing_else_style }
end
if ['both', keyword].include? missing_else_style
it 'does not autocorrect' do
expect_offense(source)
expect_no_corrections
end
else
it 'does autocorrection' do
expect_offense(source)
expect_correction(corrected_source)
end
end
end
end
end
context 'configured to warn on empty else' do
let(:config) do
RuboCop::Config.new('Style/EmptyElse' => {
'EnforcedStyle' => 'empty',
'SupportedStyles' => %w[empty nil both]
},
'Style/MissingElse' => missing_else_config)
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
context 'using semicolons' do
let(:source) { <<~RUBY }
if a; foo else end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
if a; foo end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'not using semicolons' do
let(:source) { <<~RUBY }
if a
foo
else
^^^^ Redundant `else`-clause.
end
RUBY
let(:corrected_source) { <<~RUBY }
if a
foo
end
RUBY
it_behaves_like 'autocorrect', 'if'
end
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo elsif b; bar else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo end')
end
end
context 'in an if-statement' do
let(:source) { <<~RUBY }
if cond
if cond2
something
else
^^^^ Redundant `else`-clause.
end
end
RUBY
let(:corrected_source) { <<~RUBY }
if cond
if cond2
something
end
end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with an empty comment' do
it 'does not autocorrect' do
expect_offense(<<~RUBY)
if cond
something
else
^^^^ Redundant `else`-clause.
# TODO
end
RUBY
expect_no_corrections
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
let(:source) { <<~RUBY }
unless cond; foo else end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
unless cond; foo end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo end')
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
let(:source) { <<~RUBY }
case v; when a; foo else end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
case v; when a; foo end
RUBY
it_behaves_like 'autocorrect', 'case'
end
context 'with an else-clause containing only the literal nil' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; else nil end')
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; end')
end
end
end
end
context 'configured to warn on nil in else' do
let(:config) do
RuboCop::Config.new('Style/EmptyElse' => {
'EnforcedStyle' => 'nil',
'SupportedStyles' => %w[empty nil both]
},
'Style/MissingElse' => missing_else_config)
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
context 'when standalone' do
let(:source) { <<~RUBY }
if a
foo
elsif b
bar
else
^^^^ Redundant `else`-clause.
nil
end
RUBY
let(:corrected_source) { <<~RUBY }
if a
foo
elsif b
bar
end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'when the result is assigned to a variable' do
let(:source) { <<~RUBY }
foobar = if a
foo
elsif b
bar
else
^^^^ Redundant `else`-clause.
nil
end
RUBY
let(:corrected_source) { <<~RUBY }
foobar = if a
foo
elsif b
bar
end
RUBY
it_behaves_like 'autocorrect', 'if'
end
end
context 'with an else-clause containing only the literal nil using semicolons' do
context 'with one elsif' do
let(:source) { <<~RUBY }
if a; foo elsif b; bar else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
if a; foo elsif b; bar end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with multiple elsifs' do
let(:source) { <<~RUBY }
if a; foo elsif b; bar; elsif c; bar else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
if a; foo elsif b; bar; elsif c; bar end
RUBY
it_behaves_like 'autocorrect', 'if'
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo end')
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
let(:source) { <<~RUBY }
unless cond; foo else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
unless cond; foo end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo end')
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo else end')
end
end
context 'with an else-clause containing only the literal nil' do
context 'using semicolons' do
let(:source) { <<~RUBY }
case v; when a; foo; when b; bar; else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
case v; when a; foo; when b; bar; end
RUBY
it_behaves_like 'autocorrect', 'case'
end
context 'when the result is assigned to a variable' do
let(:source) { <<~RUBY }
foobar = case v
when a
foo
when b
bar
else
^^^^ Redundant `else`-clause.
nil
end
RUBY
let(:corrected_source) { <<~RUBY }
foobar = case v
when a
foo
when b
bar
end
RUBY
it_behaves_like 'autocorrect', 'case'
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; end')
end
end
end
end
context 'configured to warn on empty else and nil in else' do
let(:config) do
RuboCop::Config.new('Style/EmptyElse' => {
'EnforcedStyle' => 'both',
'SupportedStyles' => %w[empty nil both]
},
'Style/MissingElse' => missing_else_config)
end
context 'given an if-statement' do
context 'with a completely empty else-clause' do
let(:source) { <<~RUBY }
if a; foo else end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
if a; foo end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with an else-clause containing only the literal nil' do
context 'with one elsif' do
let(:source) { <<~RUBY }
if a; foo elsif b; bar else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
if a; foo elsif b; bar end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with multiple elsifs' do
let(:source) { <<~RUBY }
if a; foo elsif b; bar; elsif c; bar else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
if a; foo elsif b; bar; elsif c; bar end
RUBY
it_behaves_like 'autocorrect', 'if'
end
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('if cond; foo end')
end
end
end
context 'given an unless-statement' do
context 'with a completely empty else-clause' do
let(:source) { <<~RUBY }
unless cond; foo else end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
unless cond; foo end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with an else-clause containing only the literal nil' do
let(:source) { <<~RUBY }
unless cond; foo else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
unless cond; foo end
RUBY
it_behaves_like 'autocorrect', 'if'
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo else bar; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('unless cond; foo end')
end
end
end
context 'given a case statement' do
context 'with a completely empty else-clause' do
let(:source) { <<~RUBY }
case v; when a; foo else end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
case v; when a; foo end
RUBY
it_behaves_like 'autocorrect', 'case'
end
context 'with an else-clause containing only the literal nil' do
let(:source) { <<~RUBY }
case v; when a; foo; when b; bar; else nil end
^^^^ Redundant `else`-clause.
RUBY
let(:corrected_source) { <<~RUBY }
case v; when a; foo; when b; bar; end
RUBY
it_behaves_like 'autocorrect', 'case'
end
context 'with an else-clause with side-effects' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; else b; nil end')
end
end
context 'with no else-clause' do
it "doesn't register an offense" do
expect_no_offenses('case v; when a; foo; when b; bar; end')
end
end
end
end
context 'when `AllowComments: true`' do
let(:config) do
RuboCop::Config.new('Style/EmptyElse' => {
'AllowComments' => true,
'EnforcedStyle' => 'both',
'SupportedStyles' => %w[empty nil both]
},
'Style/MissingElse' => missing_else_config)
end
context 'given an if-statement' do
context 'with not comment and empty else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if condition
statement
else
^^^^ Redundant `else`-clause.
end
RUBY
end
end
context 'with no comment and nil else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if condition
statement
else
^^^^ Redundant `else`-clause.
nil
end
RUBY
end
end
context 'with comment and empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if condition
statement
else
# some comment
end
RUBY
end
end
context 'with comment and nil else-clause' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if condition
statement
else
nil # some comment
end
RUBY
end
end
context 'with no comment and empty else-clause after `elsif`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if condition
foo
elsif condition2
bar
else
^^^^ Redundant `else`-clause.
end
RUBY
end
end
context 'with no comment and nil else-clause after `elsif`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if condition
foo
elsif condition2
bar
else
^^^^ Redundant `else`-clause.
nil
end
RUBY
end
end
context 'with comment and empty else-clause after `elsif`' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if condition
foo
elsif condition2
bar
else
# some comment
end
RUBY
end
end
context 'with comment and nil else-clause after `elsif`' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
if condition
foo
elsif condition2
bar
else
nil # some comment
end
RUBY
end
end
context 'without an else' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
if condition
statement
end
RUBY
end
end
end
context 'given an unless-statement' do
context 'with no comment and empty else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless condition
statement
else
^^^^ Redundant `else`-clause.
end
RUBY
end
end
context 'with no comment and nil else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
unless condition
statement
else
^^^^ Redundant `else`-clause.
nil
end
RUBY
end
end
context 'with comment and empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
unless condition
statement
else
# some comment
end
RUBY
end
end
context 'with comment and nil else-clause' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
unless condition
statement
else
nil # some comment
end
RUBY
end
end
context 'without an else' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
unless condition
statement
end
RUBY
end
end
end
context 'given a case statement' do
context 'with no comment and empty else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
case a
when condition
statement
else
^^^^ Redundant `else`-clause.
end
RUBY
end
end
context 'with no comment and nil else-clause' do
it 'registers an offense' do
expect_offense(<<~RUBY)
case a
when condition
statement
else
^^^^ Redundant `else`-clause.
nil
end
RUBY
end
end
context 'with comment and empty else-clause' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
case a
when condition
statement
else
# some comment
end
RUBY
end
end
context 'with comment and nil else-clause' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
case a
when condition
statement
else
nil # some comment
end
RUBY
end
end
context 'without an else' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
case a
when condition
statement
end
RUBY
end
end
end
end
context 'with nested if and case statement' do
let(:config) do
RuboCop::Config.new('Style/EmptyElse' => {
'EnforcedStyle' => 'nil',
'SupportedStyles' => %w[empty nil both]
},
'Style/MissingElse' => missing_else_config)
end
let(:source) { <<~RUBY }
def foo
if @params
case @params[:x]
when :a
:b
else
^^^^ Redundant `else`-clause.
nil
end
else
:c
end
end
RUBY
let(:corrected_source) { <<~RUBY }
def foo
if @params
case @params[:x]
when :a
:b
end
else
:c
end
end
RUBY
it_behaves_like 'autocorrect', 'case'
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_exception_spec.rb | spec/rubocop/cop/style/redundant_exception_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantException, :config do
shared_examples 'common behavior' do |keyword, runtime_error|
it "reports an offense for a #{keyword} with #{runtime_error}" do
expect_offense(<<~RUBY, keyword: keyword, runtime_error: runtime_error)
%{keyword} %{runtime_error}, "message"
^{keyword}^^{runtime_error}^^^^^^^^^^^ Redundant `RuntimeError` argument can be removed.
RUBY
expect_correction(<<~RUBY)
#{keyword} "message"
RUBY
end
it "reports an offense for a #{keyword} with #{runtime_error} and ()" do
expect_offense(<<~RUBY, keyword: keyword, runtime_error: runtime_error)
%{keyword}(%{runtime_error}, "message")
^{keyword}^^{runtime_error}^^^^^^^^^^^^ Redundant `RuntimeError` argument can be removed.
RUBY
expect_correction(<<~RUBY)
#{keyword}("message")
RUBY
end
it "reports an offense for a #{keyword} with #{runtime_error}.new" do
expect_offense(<<~RUBY, keyword: keyword, runtime_error: runtime_error)
%{keyword} %{runtime_error}.new "message"
^{keyword}^^{runtime_error}^^^^^^^^^^^^^^ Redundant `RuntimeError.new` call can be replaced with just the message.
RUBY
expect_correction(<<~RUBY)
#{keyword} "message"
RUBY
end
it "reports an offense for a #{keyword} with #{runtime_error}.new" do
expect_offense(<<~RUBY, keyword: keyword, runtime_error: runtime_error)
%{keyword} %{runtime_error}.new("message")
^{keyword}^^{runtime_error}^^^^^^^^^^^^^^^ Redundant `RuntimeError.new` call can be replaced with just the message.
RUBY
expect_correction(<<~RUBY)
#{keyword} "message"
RUBY
end
it "accepts a #{keyword} with #{runtime_error} if it does not have 2 args" do
expect_no_offenses("#{keyword} #{runtime_error}, 'message', caller")
end
it 'accepts rescue w/ non redundant error' do
expect_no_offenses "#{keyword} OtherError, 'message'"
end
end
it_behaves_like 'common behavior', 'raise', 'RuntimeError'
it_behaves_like 'common behavior', 'raise', '::RuntimeError'
it_behaves_like 'common behavior', 'fail', 'RuntimeError'
it_behaves_like 'common behavior', 'fail', '::RuntimeError'
it 'registers an offense for raise with RuntimeError, "#{message}"' do
expect_offense(<<~'RUBY')
raise RuntimeError, "#{message}"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Redundant `RuntimeError` argument can be removed.
RUBY
expect_correction(<<~'RUBY')
raise "#{message}"
RUBY
end
it 'registers an offense for raise with RuntimeError, `command`' do
expect_offense(<<~RUBY)
raise RuntimeError, `command`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Redundant `RuntimeError` argument can be removed.
RUBY
expect_correction(<<~RUBY)
raise `command`
RUBY
end
it 'registers an offense for raise with RuntimeError, Object.new' do
expect_offense(<<~RUBY)
raise RuntimeError, Object.new
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Redundant `RuntimeError` argument can be removed.
RUBY
expect_correction(<<~RUBY)
raise Object.new.to_s
RUBY
end
it 'registers an offense for raise with RuntimeError.new, Object.new and parans' do
expect_offense(<<~RUBY)
raise RuntimeError.new(Object.new)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Redundant `RuntimeError.new` call can be replaced with just the message.
RUBY
expect_correction(<<~RUBY)
raise Object.new.to_s
RUBY
end
it 'registers an offense for raise with RuntimeError.new, Object.new no parens' do
expect_offense(<<~RUBY)
raise RuntimeError.new Object.new
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Redundant `RuntimeError.new` call can be replaced with just the message.
RUBY
expect_correction(<<~RUBY)
raise Object.new.to_s
RUBY
end
it 'registers an offense for raise with RuntimeError, variable' do
expect_offense(<<~RUBY)
raise RuntimeError, variable
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Redundant `RuntimeError` argument can be removed.
RUBY
expect_correction(<<~RUBY)
raise variable.to_s
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/next_spec.rb | spec/rubocop/cop/style/next_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Next, :config do
let(:cop_config) { { 'MinBodyLength' => 1 } }
shared_examples 'iterators' do |condition|
let(:opposite) { condition == 'if' ? 'unless' : 'if' }
it "registers an offense for #{condition} inside of downto" do
expect_offense(<<~RUBY, condition: condition)
3.downto(1) do
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
RUBY
expect_correction(<<~RUBY)
3.downto(1) do
next #{opposite} o == 1
puts o
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it "registers an offense for #{condition} inside of downto numblock" do
expect_offense(<<~RUBY, condition: condition)
3.downto(1) do
%{condition} _1 == 1
^{condition}^^^^^^^^ Use `next` to skip iteration.
puts _1
end
end
RUBY
expect_correction(<<~RUBY)
3.downto(1) do
next #{opposite} _1 == 1
puts _1
end
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it "registers an offense for #{condition} inside of downto itblock" do
expect_offense(<<~RUBY, condition: condition)
3.downto(1) do
%{condition} it == 1
^{condition}^^^^^^^^ Use `next` to skip iteration.
puts it
end
end
RUBY
expect_correction(<<~RUBY)
3.downto(1) do
next #{opposite} it == 1
puts it
end
RUBY
end
end
it "registers an offense for #{condition} inside of each" do
expect_offense(<<~RUBY, condition: condition)
[].each do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
RUBY
expect_correction(<<~RUBY)
[].each do |o|
next #{opposite} o == 1
puts o
end
RUBY
end
it "registers an offense for #{condition} inside of safe navigation `each` call" do
expect_offense(<<~RUBY, condition: condition)
[]&.each do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
RUBY
expect_correction(<<~RUBY)
[]&.each do |o|
next #{opposite} o == 1
puts o
end
RUBY
end
it "registers an offense for #{condition} inside of each_with_object" do
expect_offense(<<~RUBY, condition: condition)
[].each_with_object({}) do |o, a|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
a[o] = {}
end
end
RUBY
expect_correction(<<~RUBY)
[].each_with_object({}) do |o, a|
next #{opposite} o == 1
a[o] = {}
end
RUBY
end
it "registers an offense for #{condition} inside of for" do
expect_offense(<<~RUBY, condition: condition)
for o in 1..3 do
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
RUBY
expect_correction(<<~RUBY)
for o in 1..3 do
next #{opposite} o == 1
puts o
end
RUBY
end
it "registers an offense for #{condition} inside of loop" do
expect_offense(<<~RUBY, condition: condition)
loop do
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
RUBY
expect_correction(<<~RUBY)
loop do
next #{opposite} o == 1
puts o
end
RUBY
end
it "registers an offense for #{condition} inside of map" do
expect_offense(<<~RUBY, condition: condition)
loop do
{}.map do |k, v|
%{condition} v == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts k
end
end
end
RUBY
expect_correction(<<~RUBY)
loop do
{}.map do |k, v|
next #{opposite} v == 1
puts k
end
end
RUBY
end
it "registers an offense for #{condition} inside of times" do
expect_offense(<<~RUBY, condition: condition)
loop do
3.times do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
end
RUBY
expect_correction(<<~RUBY)
loop do
3.times do |o|
next #{opposite} o == 1
puts o
end
end
RUBY
end
it "registers an offense for #{condition} inside of collect" do
expect_offense(<<~RUBY, condition: condition)
[].collect do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
true
end
end
RUBY
expect_correction(<<~RUBY)
[].collect do |o|
next #{opposite} o == 1
true
end
RUBY
end
it "registers an offense for #{condition} inside of select" do
expect_offense(<<~RUBY, condition: condition)
[].select do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
true
end
end
RUBY
expect_correction(<<~RUBY)
[].select do |o|
next #{opposite} o == 1
true
end
RUBY
end
it "registers an offense for #{condition} inside of select!" do
expect_offense(<<~RUBY, condition: condition)
[].select! do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
true
end
end
RUBY
expect_correction(<<~RUBY)
[].select! do |o|
next #{opposite} o == 1
true
end
RUBY
end
it "registers an offense for #{condition} inside of reject" do
expect_offense(<<~RUBY, condition: condition)
[].reject do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
true
end
end
RUBY
expect_correction(<<~RUBY)
[].reject do |o|
next #{opposite} o == 1
true
end
RUBY
end
it "registers an offense for #{condition} inside of reject!" do
expect_offense(<<~RUBY, condition: condition)
[].reject! do |o|
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
true
end
end
RUBY
expect_correction(<<~RUBY)
[].reject! do |o|
next #{opposite} o == 1
true
end
RUBY
end
it "registers an offense for #{condition} inside of nested iterators" do
expect_offense(<<~RUBY, condition: condition)
loop do
until false
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
end
RUBY
expect_correction(<<~RUBY)
loop do
until false
next #{opposite} o == 1
puts o
end
end
RUBY
end
it "registers an offense for #{condition} inside of nested iterators" do
expect_offense(<<~RUBY, condition: condition)
loop do
while true
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
end
RUBY
expect_correction(<<~RUBY)
loop do
while true
next #{opposite} o == 1
puts o
end
end
RUBY
end
it 'registers an offense for a condition at the end of an iterator ' \
'when there is more in the iterator than the condition' do
expect_offense(<<~RUBY, condition: condition)
[].each do |o|
puts o
%{condition} o == 1
^{condition}^^^^^^^ Use `next` to skip iteration.
puts o
end
end
RUBY
expect_correction(<<~RUBY)
[].each do |o|
puts o
next #{opposite} o == 1
puts o
end
RUBY
end
it 'registers an offense when line break before condition' do
expect_offense(<<~RUBY)
array.each do |item|
if
^^ Use `next` to skip iteration.
condition
next if item.zero?
do_something
end
end
RUBY
expect_correction(<<~RUBY)
array.each do |item|
next unless condition
next if item.zero?
do_something
end
RUBY
end
it 'allows loops with conditional break' do
expect_no_offenses(<<~RUBY)
loop do
puts ''
break #{condition} o == 1
end
RUBY
end
it 'allows loops with conditional return' do
expect_no_offenses(<<~RUBY)
loop do
puts ''
return #{condition} o == 1
end
RUBY
end
it "allows loops with #{condition} being the entire body with else" do
expect_no_offenses(<<~RUBY)
[].each do |o|
#{condition} o == 1
puts o
else
puts 'no'
end
end
RUBY
end
it "allows loops with #{condition} with else, nested in another condition" do
expect_no_offenses(<<~RUBY)
[].each do |o|
if foo
#{condition} o == 1
puts o
else
puts 'no'
end
end
end
RUBY
end
it "allows loops with #{condition} with else at the end" do
expect_no_offenses(<<~RUBY)
[].each do |o|
puts o
#{condition} o == 1
puts o
else
puts 'no'
end
end
RUBY
end
it "reports an offense for #{condition} whose body has 3 lines" do
expect_offense(<<~RUBY, condition: condition)
arr.each do |e|
%{condition} something
^{condition}^^^^^^^^^^ Use `next` to skip iteration.
work
work
work
end
end
RUBY
expect_correction(<<~RUBY)
arr.each do |e|
next #{opposite} something
work
work
work
end
RUBY
end
context 'EnforcedStyle: skip_modifier_ifs' do
let(:cop_config) { { 'EnforcedStyle' => 'skip_modifier_ifs' } }
it "allows modifier #{condition}" do
expect_no_offenses(<<~RUBY)
[].each do |o|
puts o #{condition} o == 1
end
RUBY
end
end
context 'EnforcedStyle: always' do
let(:cop_config) { { 'EnforcedStyle' => 'always' } }
let(:opposite) { condition == 'if' ? 'unless' : 'if' }
it "registers an offense for modifier #{condition}" do
expect_offense(<<~RUBY, condition: condition)
[].each do |o|
puts o #{condition} o == 1 # comment
^^^^^^^^{condition}^^^^^^^ Use `next` to skip iteration.
end
RUBY
expect_correction(<<~RUBY)
[].each do |o|
next #{opposite} o == 1
puts o # comment
end
RUBY
end
end
it 'autocorrects a misaligned end' do
expect_offense(<<~RUBY)
[1, 2, 3, 4].each do |num|
if !opts.nil?
^^^^^^^^^^^^^ Use `next` to skip iteration.
puts num
if num != 2
puts 'hello'
puts 'world'
end
end
end
RUBY
expect_correction(<<~RUBY)
[1, 2, 3, 4].each do |num|
next unless !opts.nil?
puts num
next unless num != 2
puts 'hello'
puts 'world'
end
RUBY
end
end
it 'keeps comments when autocorrecting' do
expect_offense(<<~RUBY)
loop do
if test # keep me
^^^^^^^ Use `next` to skip iteration.
# keep me
something # keep me
# keep me
end # keep me
end
RUBY
expect_correction(<<~RUBY)
loop do
next unless test # keep me
# keep me
something # keep me
# keep me
# keep me
end
RUBY
end
it 'handles `then` when autocorrecting' do
expect_offense(<<~RUBY)
loop do
if test then
^^^^^^^ Use `next` to skip iteration.
something
end
end
RUBY
expect_correction(<<~RUBY)
loop do
next unless test
something
end
RUBY
end
it "doesn't reindent heredoc bodies when autocorrecting" do
expect_offense(<<~RUBY)
loop do
if test
^^^^^^^ Use `next` to skip iteration.
str = <<-BLAH
this is a heredoc
nice eh?
BLAH
something
end
end
RUBY
expect_correction(<<~RUBY)
loop do
next unless test
str = <<-BLAH
this is a heredoc
nice eh?
BLAH
something
end
RUBY
end
it 'handles nested autocorrections' do
expect_offense(<<~RUBY)
loop do
if test
^^^^^^^ Use `next` to skip iteration.
loop do
if test
^^^^^^^ Use `next` to skip iteration.
something
end
end
end
end
RUBY
expect_correction(<<~RUBY)
loop do
next unless test
loop do
next unless test
something
end
end
RUBY
end
it_behaves_like 'iterators', 'if'
it_behaves_like 'iterators', 'unless'
it 'allows empty blocks' do
expect_no_offenses(<<~RUBY)
[].each do
end
[].each { }
RUBY
end
it 'allows loops with conditions at the end with ternary op' do
expect_no_offenses(<<~RUBY)
[].each do |o|
o == x ? y : z
end
RUBY
end
it 'allows super nodes' do
# https://github.com/rubocop/rubocop/issues/1115
expect_no_offenses(<<~RUBY)
def foo
super(a, a) { a }
end
RUBY
end
it 'does not blow up on empty body until block' do
expect_no_offenses('until sup; end')
end
it 'does not blow up on empty body while block' do
expect_no_offenses('while sup; end')
end
it 'does not blow up on empty body for block' do
expect_no_offenses('for x in y; end')
end
it 'does not crash with an empty body branch' do
expect_no_offenses(<<~RUBY)
loop do
if true
end
end
RUBY
end
it 'does not crash with empty brackets' do
expect_no_offenses(<<~RUBY)
loop do
()
end
RUBY
end
context 'MinBodyLength: 3' do
let(:cop_config) { { 'MinBodyLength' => 3 } }
it 'accepts if whose body has 1 line' do
expect_no_offenses(<<~RUBY)
arr.each do |e|
if something
work
end
end
RUBY
end
end
context 'Invalid MinBodyLength' do
let(:cop_config) { { 'MinBodyLength' => -2 } }
it 'fails with an error' do
source = <<~RUBY
loop do
if o == 1
puts o
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, 'MinBodyLength' => 1 } }
it 'registers an offense and corrects when another conditional statements is at the same depth' do
expect_offense(<<~RUBY)
[].each do
if foo?
work
end
if bar?
^^^^^^^ Use `next` to skip iteration.
work
end
end
RUBY
expect_correction(<<~RUBY)
[].each do
if foo?
work
end
next unless bar?
work
end
RUBY
end
end
context 'AllowConsecutiveConditionals: true' do
let(:cop_config) { { 'AllowConsecutiveConditionals' => true, 'MinBodyLength' => 1 } }
it 'does not register an offense when other conditional statements are at the same depth' do
expect_no_offenses(<<~RUBY)
[].each do
if foo?
work
end
if bar?
work
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/array_join_spec.rb | spec/rubocop/cop/style/array_join_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ArrayJoin, :config do
it 'registers an offense for an array followed by string' do
expect_offense(<<~RUBY)
%w(one two three) * ", "
^ Favor `Array#join` over `Array#*`.
RUBY
expect_correction(<<~RUBY)
%w(one two three).join(", ")
RUBY
end
it "autocorrects '*' to 'join' when there are no spaces" do
expect_offense(<<~RUBY)
%w(one two three)*", "
^ Favor `Array#join` over `Array#*`.
RUBY
expect_correction(<<~RUBY)
%w(one two three).join(", ")
RUBY
end
it "autocorrects '*' to 'join' when setting to a variable" do
expect_offense(<<~RUBY)
foo = %w(one two three)*", "
^ Favor `Array#join` over `Array#*`.
RUBY
expect_correction(<<~RUBY)
foo = %w(one two three).join(", ")
RUBY
end
it 'does not register an offense for numbers' do
expect_no_offenses('%w(one two three) * 4')
end
it 'does not register an offense for ambiguous cases' do
expect_no_offenses('%w(one two three) * test')
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/when_then_spec.rb | spec/rubocop/cop/style/when_then_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::WhenThen, :config do
it 'registers an offense for when b;' do
expect_offense(<<~RUBY)
case a
when b; c
^ Do not use `when b;`. Use `when b then` instead.
end
RUBY
expect_correction(<<~RUBY)
case a
when b then c
end
RUBY
end
it 'registers an offense for when b, c;' do
expect_offense(<<~RUBY)
case a
when b, c; d
^ Do not use `when b, c;`. Use `when b, c then` instead.
end
RUBY
expect_correction(<<~RUBY)
case a
when b, c then d
end
RUBY
end
it 'accepts ; separating statements in the body of when' do
expect_no_offenses(<<~RUBY)
case a
when b then c; d
end
case e
when f
g; h
end
RUBY
end
# Regression: https://github.com/rubocop/rubocop/issues/3868
context 'when inspecting a case statement with an empty branch' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
case value
when cond1
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/return_nil_in_predicate_method_definition_spec.rb | spec/rubocop/cop/style/return_nil_in_predicate_method_definition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ReturnNilInPredicateMethodDefinition, :config do
context 'when defining predicate method' do
it 'registers an offense when using `return`' do
expect_offense(<<~RUBY)
def foo?
return if condition
^^^^^^ Return `false` instead of `nil` in predicate methods.
bar?
end
RUBY
expect_correction(<<~RUBY)
def foo?
return false if condition
bar?
end
RUBY
end
it 'registers an offense when using `return nil`' do
expect_offense(<<~RUBY)
def foo?
return nil if condition
^^^^^^^^^^ Return `false` instead of `nil` in predicate methods.
bar?
end
RUBY
expect_correction(<<~RUBY)
def foo?
return false if condition
bar?
end
RUBY
end
it 'registers an offense when using `nil` at the end of the predicate method definition and using guard condition' do
expect_offense(<<~RUBY)
def foo?
return true if condition
nil
^^^ Return `false` instead of `nil` in predicate methods.
end
RUBY
expect_correction(<<~RUBY)
def foo?
return true if condition
false
end
RUBY
end
it 'registers an offense when using `nil` at the end of the predicate method definition' do
expect_offense(<<~RUBY)
def foo?
nil
^^^ Return `false` instead of `nil` in predicate methods.
end
RUBY
expect_correction(<<~RUBY)
def foo?
false
end
RUBY
end
it 'does not register an offense when using `return true`' do
expect_no_offenses(<<~RUBY)
def foo?
return true if condition
bar?
end
RUBY
end
it 'does not register an offense when using `return value`' do
expect_no_offenses(<<~RUBY)
def foo?
return value if condition
bar?
end
RUBY
end
it 'does not register an offense when using `nil` at the middle of method definition' do
expect_no_offenses(<<~RUBY)
def foo?
do_something
nil
do_something
end
RUBY
end
it 'does not register an offense when the last safe navigation method argument in method definition is `nil`' do
expect_no_offenses(<<~RUBY)
def foo?
bar&.baz(nil)
end
RUBY
end
it 'does not register an offense when the last method argument in method definition is `nil`' do
expect_no_offenses(<<~RUBY)
def foo?
bar.baz(nil)
end
RUBY
end
it 'does not register an offense when assigning `nil` to a variable in predicate method definition' do
expect_no_offenses(<<~RUBY)
def foo?
bar = nil
end
RUBY
end
it 'does not register an offense when using `return false`' do
expect_no_offenses(<<~RUBY)
def foo?
return false if condition
bar?
end
RUBY
end
it 'does not register an offense when not using `return`' do
expect_no_offenses(<<~RUBY)
def foo?
do_something
end
RUBY
end
it 'does not register an offense when empty body' do
expect_no_offenses(<<~RUBY)
def foo?
end
RUBY
end
it 'does not register an offense when empty body with `rescue`' do
expect_no_offenses(<<~RUBY)
def foo?
return false unless condition
rescue
end
RUBY
end
context 'conditional implicit return nil' do
it 'registers an offense when in `if` branch' do
expect_offense(<<~RUBY)
def foo?
if bar
nil
^^^ Return `false` instead of `nil` in predicate methods.
else
true
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
if bar
false
else
true
end
end
RUBY
end
it 'registers an offense when in `else` branch' do
expect_offense(<<~RUBY)
def foo?
if bar
true
else
nil
^^^ Return `false` instead of `nil` in predicate methods.
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
if bar
true
else
false
end
end
RUBY
end
it 'registers an offense when in nested `if`' do
expect_offense(<<~RUBY)
def foo?
if bar
if baz
true
else
nil
^^^ Return `false` instead of `nil` in predicate methods.
end
end
end
RUBY
expect_correction(<<~RUBY)
def foo?
if bar
if baz
true
else
false
end
end
end
RUBY
end
it 'does not register an offense when the `if` statement is not an implicit return' do
expect_no_offenses(<<~RUBY)
def foo?
if bar
true
else
nil
end
baz
end
RUBY
end
end
end
context 'when defining predicate class method' do
it 'registers an offense when using `return`' do
expect_offense(<<~RUBY)
def self.foo?
return if condition
^^^^^^ Return `false` instead of `nil` in predicate methods.
bar?
end
RUBY
expect_correction(<<~RUBY)
def self.foo?
return false if condition
bar?
end
RUBY
end
it 'registers an offense when using `return nil`' do
expect_offense(<<~RUBY)
def self.foo?
return nil if condition
^^^^^^^^^^ Return `false` instead of `nil` in predicate methods.
bar?
end
RUBY
expect_correction(<<~RUBY)
def self.foo?
return false if condition
bar?
end
RUBY
end
it 'does not register an offense when using `return false`' do
expect_no_offenses(<<~RUBY)
def self.foo?
return false if condition
bar?
end
RUBY
end
context 'conditional implicit return nil' do
it 'registers an offense when in `if` branch' do
expect_offense(<<~RUBY)
def self.foo?
if bar
nil
^^^ Return `false` instead of `nil` in predicate methods.
else
true
end
end
RUBY
expect_correction(<<~RUBY)
def self.foo?
if bar
false
else
true
end
end
RUBY
end
it 'registers an offense when in `else` branch' do
expect_offense(<<~RUBY)
def self.foo?
if bar
true
else
nil
^^^ Return `false` instead of `nil` in predicate methods.
end
end
RUBY
expect_correction(<<~RUBY)
def self.foo?
if bar
true
else
false
end
end
RUBY
end
it 'registers an offense when in nested `if`' do
expect_offense(<<~RUBY)
def self.foo?
if bar
if baz
true
else
nil
^^^ Return `false` instead of `nil` in predicate methods.
end
end
end
RUBY
expect_correction(<<~RUBY)
def self.foo?
if bar
if baz
true
else
false
end
end
end
RUBY
end
it 'does not register an offense when the `if` statement is not an implicit return' do
expect_no_offenses(<<~RUBY)
def self.foo?
if bar
true
else
nil
end
baz
end
RUBY
end
end
end
context 'when not defining predicate method' do
it 'does not register an offense when using `return`' do
expect_no_offenses(<<~RUBY)
def foo
return if condition
bar?
end
RUBY
end
it 'does not register an offense when using `if`' do
expect_no_offenses(<<~RUBY)
def foo
if bar
nil
else
true
end
end
RUBY
end
end
context "when `AllowedMethod: ['foo?']`" do
let(:cop_config) { { 'AllowedMethods' => ['foo?'] } }
context 'when defining predicate method' do
it 'does not register an offense when using `return`' do
expect_no_offenses(<<~RUBY)
def foo?
return if condition
bar?
end
RUBY
end
it 'does not register an offense when using `return nil`' do
expect_no_offenses(<<~RUBY)
def foo?
return nil if condition
bar?
end
RUBY
end
it 'does not register an offense when returning nil in an `if`' do
expect_no_offenses(<<~RUBY)
def foo?
if bar
nil
else
true
end
end
RUBY
end
end
context 'when defining predicate class method' do
it 'does not register an offense when using `return`' do
expect_no_offenses(<<~RUBY)
def self.foo?
return if condition
bar?
end
RUBY
end
it 'does not register an offense when using `return nil`' do
expect_no_offenses(<<~RUBY)
def self.foo?
return nil if condition
bar?
end
RUBY
end
it 'does not register an offense when returning nil in an `if`' do
expect_no_offenses(<<~RUBY)
def self.foo?
if bar
nil
else
true
end
end
RUBY
end
end
end
context 'when `AllowedPattern: [/foo/]`' do
let(:cop_config) { { 'AllowedPatterns' => [/foo/] } }
context 'when defining predicate method' do
it 'does not register an offense when using `return`' do
expect_no_offenses(<<~RUBY)
def foo?
return if condition
bar?
end
RUBY
end
it 'does not register an offense when using `return nil`' do
expect_no_offenses(<<~RUBY)
def foo?
return nil if condition
bar?
end
RUBY
end
it 'does not register an offense when returning nil in an `if`' do
expect_no_offenses(<<~RUBY)
def foo?
if bar
nil
else
true
end
end
RUBY
end
end
context 'when defining predicate class method' do
it 'does not register an offense when using `return`' do
expect_no_offenses(<<~RUBY)
def self.foo?
return if condition
bar?
end
RUBY
end
it 'does not register an offense when using `return nil`' do
expect_no_offenses(<<~RUBY)
def self.foo?
return nil if condition
bar?
end
RUBY
end
it 'does not register an offense when returning nil in an `if`' do
expect_no_offenses(<<~RUBY)
def self.foo?
if bar
nil
else
true
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/redundant_return_spec.rb | spec/rubocop/cop/style/redundant_return_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RedundantReturn, :config do
let(:cop_config) { { 'AllowMultipleReturnValues' => false } }
it 'reports an offense for def with only a return' do
expect_offense(<<~RUBY)
def func
return something
^^^^^^ Redundant `return` detected.
ensure
2
end
RUBY
expect_correction(<<~RUBY)
def func
something
ensure
2
end
RUBY
end
it 'reports an offense for defs with only a return' do
expect_offense(<<~RUBY)
def Test.func
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
def Test.func
something
end
RUBY
end
it 'reports an offense for def ending with return' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
def func
some_preceding_statements
something
end
RUBY
end
it 'reports an offense for define_method with only a return' do
expect_offense(<<~RUBY)
define_method(:foo) do
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
define_method(:foo) do
something
end
RUBY
end
it 'reports an offense for define_singleton_method with only a return' do
expect_offense(<<~RUBY)
define_singleton_method(:foo) do
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
define_singleton_method(:foo) do
something
end
RUBY
end
it 'reports an offense for define_method ending with return' do
expect_offense(<<~RUBY)
define_method(:foo) do
some_preceding_statements
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
define_method(:foo) do
some_preceding_statements
something
end
RUBY
end
it 'reports an offense for define_singleton_method ending with return' do
expect_offense(<<~RUBY)
define_singleton_method(:foo) do
some_preceding_statements
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
define_singleton_method(:foo) do
some_preceding_statements
something
end
RUBY
end
it 'reports an offense for lambda ending with return' do
expect_offense(<<~RUBY)
lambda do
some_preceding_statements
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
lambda do
some_preceding_statements
something
end
RUBY
end
it 'reports an offense for -> ending with return' do
expect_offense(<<~RUBY)
-> do
some_preceding_statements
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
-> do
some_preceding_statements
something
end
RUBY
end
it 'does not register an offense for proc ending with return' do
expect_no_offenses(<<~RUBY)
proc do
some_preceding_statements
return something
end
RUBY
end
it 'reports an offense for def ending with return with splat argument' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
return *something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
def func
some_preceding_statements
something
end
RUBY
end
it 'reports an offense for defs ending with return' do
expect_offense(<<~RUBY)
def self.func
some_preceding_statements
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
def self.func
some_preceding_statements
something
end
RUBY
end
it 'registers an offense when returning value with guard clause and `return` is used' do
expect_offense(<<~RUBY)
def func
return something if something_else
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
def func
something if something_else
end
RUBY
end
it 'does not register an offense when returning value with guard clause and `return` is not used' do
expect_no_offenses(<<~RUBY)
def func
something if something_else
end
RUBY
end
it 'does not blow up on empty method body' do
expect_no_offenses(<<~RUBY)
def func
end
RUBY
end
it 'does not blow up on empty if body' do
expect_no_offenses(<<~RUBY)
def func
if x
elsif y
else
end
end
RUBY
end
it 'autocorrects by removing redundant returns' do
expect_offense(<<~RUBY)
def func
one
two
return something
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
def func
one
two
something
end
RUBY
end
context 'when return has no arguments' do
shared_examples 'common behavior' do |ret|
it "registers an offense for #{ret} and autocorrects replacing #{ret} with nil" do
expect_offense(<<~RUBY, ret: ret)
def func
one
two
%{ret}
^^^^^^ Redundant `return` detected.
# comment
end
RUBY
expect_correction(<<~RUBY)
def func
one
two
nil
# comment
end
RUBY
end
end
it_behaves_like 'common behavior', 'return'
it_behaves_like 'common behavior', 'return()'
end
context 'when multi-value returns are not allowed' do
it 'reports an offense for def with only a return' do
expect_offense(<<~RUBY)
def func
return something, test
^^^^^^ Redundant `return` detected. To return multiple values, use an array.
end
RUBY
expect_correction(<<~RUBY)
def func
[something, test]
end
RUBY
end
it 'reports an offense for defs with only a return' do
expect_offense(<<~RUBY)
def Test.func
return something, test
^^^^^^ Redundant `return` detected. To return multiple values, use an array.
end
RUBY
expect_correction(<<~RUBY)
def Test.func
[something, test]
end
RUBY
end
it 'reports an offense for def ending with return' do
expect_offense(<<~RUBY)
def func
one
two
return something, test
^^^^^^ Redundant `return` detected. To return multiple values, use an array.
end
RUBY
expect_correction(<<~RUBY)
def func
one
two
[something, test]
end
RUBY
end
it 'reports an offense for defs ending with return' do
expect_offense(<<~RUBY)
def self.func
one
two
return something, test
^^^^^^ Redundant `return` detected. To return multiple values, use an array.
end
RUBY
expect_correction(<<~RUBY)
def self.func
one
two
[something, test]
end
RUBY
end
it 'autocorrects by removing return when using an explicit hash' do
expect_offense(<<~RUBY)
def func
return {:a => 1, :b => 2}
^^^^^^ Redundant `return` detected.
end
RUBY
# :a => 1, :b => 2 is not valid Ruby
expect_correction(<<~RUBY)
def func
{:a => 1, :b => 2}
end
RUBY
end
it 'autocorrects by making an implicit hash explicit' do
expect_offense(<<~RUBY)
def func
return :a => 1, :b => 2
^^^^^^ Redundant `return` detected.
end
RUBY
# :a => 1, :b => 2 is not valid Ruby
expect_correction(<<~RUBY)
def func
{:a => 1, :b => 2}
end
RUBY
end
it 'reports an offense when multiple return values have a parenthesized return value' do
expect_offense(<<~RUBY)
def do_something
return (foo && bar), 42
^^^^^^ Redundant `return` detected. To return multiple values, use an array.
end
RUBY
expect_correction(<<~RUBY)
def do_something
[(foo && bar), 42]
end
RUBY
end
end
context 'when multi-value returns are allowed' do
let(:cop_config) { { 'AllowMultipleReturnValues' => true } }
it 'accepts def with only a return' do
expect_no_offenses(<<~RUBY)
def func
return something, test
end
RUBY
end
it 'accepts defs with only a return' do
expect_no_offenses(<<~RUBY)
def Test.func
return something, test
end
RUBY
end
it 'accepts def ending with return' do
expect_no_offenses(<<~RUBY)
def func
one
two
return something, test
end
RUBY
end
it 'accepts defs ending with return' do
expect_no_offenses(<<~RUBY)
def self.func
one
two
return something, test
end
RUBY
end
end
context 'when return is inside begin-end body' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
begin
return 1
^^^^^^ Redundant `return` detected.
end
end
RUBY
expect_correction(<<~RUBY)
def func
some_preceding_statements
begin
1
end
end
RUBY
end
end
context 'when rescue and return blocks present' do
it 'registers an offense and autocorrects when inside function or rescue block' do
expect_offense(<<~RUBY)
def func
1
2
return 3
^^^^^^ Redundant `return` detected.
rescue SomeException
4
return 5
^^^^^^ Redundant `return` detected.
rescue AnotherException
return 6
^^^^^^ Redundant `return` detected.
ensure
return 7
end
RUBY
expect_correction(<<~RUBY)
def func
1
2
3
rescue SomeException
4
5
rescue AnotherException
6
ensure
return 7
end
RUBY
end
it 'registers an offense and autocorrects when rescue has else clause' do
expect_offense(<<~RUBY)
def func
return 3
rescue SomeException
else
return 4
^^^^^^ Redundant `return` detected.
end
RUBY
expect_correction(<<~RUBY)
def func
return 3
rescue SomeException
else
4
end
RUBY
end
end
context 'when return is inside an if-branch' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
if x
return 1
^^^^^^ Redundant `return` detected.
elsif y
return 2
^^^^^^ Redundant `return` detected.
else
return 3
^^^^^^ Redundant `return` detected.
end
end
RUBY
expect_correction(<<~RUBY)
def func
some_preceding_statements
if x
1
elsif y
2
else
3
end
end
RUBY
end
end
context 'when return is inside a when-branch' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
case x
when y then return 1
^^^^^^ Redundant `return` detected.
when z then return 2
^^^^^^ Redundant `return` detected.
when q
else
return 3
^^^^^^ Redundant `return` detected.
end
end
RUBY
expect_correction(<<~RUBY)
def func
some_preceding_statements
case x
when y then 1
when z then 2
when q
else
3
end
end
RUBY
end
end
context 'when case nodes are empty' do
it 'accepts empty when nodes' do
expect_no_offenses(<<~RUBY)
def func
case x
when y then 1
when z # do nothing
else
3
end
end
RUBY
end
end
context 'when return is inside an in-branch' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
def func
some_preceding_statements
case x
in y then return 1
^^^^^^ Redundant `return` detected.
in z then return 2
^^^^^^ Redundant `return` detected.
in q
else
return 3
^^^^^^ Redundant `return` detected.
end
end
RUBY
expect_correction(<<~RUBY)
def func
some_preceding_statements
case x
in y then 1
in z then 2
in q
else
3
end
end
RUBY
end
end
context 'when case match nodes are empty' do
it 'accepts empty in nodes' do
expect_no_offenses(<<~RUBY)
def func
case x
in y then 1
in z # do nothing
else
3
end
end
RUBY
end
end
it 'does not register an offense when using `lambda.call(block)`' do
expect_no_offenses(<<~RUBY)
lambda.call(block)
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/conditional_assignment_assign_in_condition_spec.rb | spec/rubocop/cop/style/conditional_assignment_assign_in_condition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ConditionalAssignment, :config do
shared_examples 'all variable types' do |variable|
it 'registers an offense assigning any variable type to ternary' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = foo? ? 1 : 2
^{variable}^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
RUBY
expect_correction(<<~RUBY)
foo? ? #{variable} = 1 : #{variable} = 2
RUBY
end
it 'registers an offense assigning any variable type to if else' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = if foo
^{variable}^^^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
if foo
#{variable} = 1
else
#{variable} = 2
end
RUBY
end
it 'registers an offense assigning any variable type to if elsif else' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = if foo
^{variable}^^^^^^^^^ Assign variables inside of conditionals.
1
elsif baz
2
else
3
end
RUBY
expect_correction(<<~RUBY)
if foo
#{variable} = 1
elsif baz
#{variable} = 2
else
#{variable} = 3
end
RUBY
end
it 'registers an offense assigning any variable type to if else with multiple assignment' do
expect_offense(<<~RUBY, variable: variable)
%{variable}, %{variable} = if foo
^{variable}^^^{variable}^^^^^^^^^ Assign variables inside of conditionals.
something
else
something_else
end
RUBY
expect_correction(<<~RUBY)
if foo
#{variable}, #{variable} = something
else
#{variable}, #{variable} = something_else
end
RUBY
end
it 'allows assignment to if without else' do
expect_no_offenses(<<~RUBY)
#{variable} = if foo
1
end
RUBY
end
it 'registers an offense assigning any variable type to unless else' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = unless foo
^{variable}^^^^^^^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
unless foo
#{variable} = 1
else
#{variable} = 2
end
RUBY
end
it 'registers an offense for assigning any variable type to case when' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = case foo
^{variable}^^^^^^^^^^^ Assign variables inside of conditionals.
when "a"
1
when "b"
2
else
3
end
RUBY
expect_correction(<<~RUBY)
case foo
when "a"
#{variable} = 1
when "b"
#{variable} = 2
else
#{variable} = 3
end
RUBY
end
context '>= Ruby 2.7', :ruby27 do
it 'registers an offense for assigning any variable type to case in' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = case foo
^{variable}^^^^^^^^^^^ Assign variables inside of conditionals.
in "a"
1
in "b"
2
else
3
end
RUBY
expect_correction(<<~RUBY)
case foo
in "a"
#{variable} = 1
in "b"
#{variable} = 2
else
#{variable} = 3
end
RUBY
end
end
it 'does not crash for rescue assignment' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue => #{variable}
bar
end
RUBY
end
end
shared_examples 'all assignment types' do |assignment|
it 'registers an offense for any assignment to ternary' do
expect_offense(<<~RUBY, assignment: assignment)
bar %{assignment} (foo? ? 1 : 2)
^^^^^{assignment}^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
RUBY
expect_correction(<<~RUBY)
foo? ? bar #{assignment} 1 : bar #{assignment} 2
RUBY
end
it 'registers an offense any assignment to if else' do
expect_offense(<<~RUBY, assignment: assignment)
bar %{assignment} if foo
^^^^^{assignment}^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
if foo
bar #{assignment} 1
else
bar #{assignment} 2
end
RUBY
end
it 'allows any assignment to if without else' do
expect_no_offenses(<<~RUBY)
bar #{assignment} if foo
1
end
RUBY
end
it 'registers an offense for any assignment to unless else' do
expect_offense(<<~RUBY, assignment: assignment)
bar %{assignment} unless foo
^^^^^{assignment}^^^^^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
unless foo
bar #{assignment} 1
else
bar #{assignment} 2
end
RUBY
end
it 'registers an offense any assignment to case when' do
expect_offense(<<~RUBY, assignment: assignment)
bar %{assignment} case foo
^^^^^{assignment}^^^^^^^^^ Assign variables inside of conditionals.
when "a"
1
else
2
end
RUBY
expect_correction(<<~RUBY)
case foo
when "a"
bar #{assignment} 1
else
bar #{assignment} 2
end
RUBY
end
it 'does not crash when used inside rescue' do
expect_no_offenses(<<~RUBY)
begin
bar #{assignment} 2
rescue
bar #{assignment} 1
end
RUBY
end
end
shared_examples 'multiline all variable types offense' do |variable|
it 'assigning any variable type to a multiline if else' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = if foo
^{variable}^^^^^^^^^ Assign variables inside of conditionals.
something
1
else
something_else
2
end
RUBY
expect_correction(<<~RUBY)
if foo
something
#{variable} = 1
else
something_else
#{variable} = 2
end
RUBY
end
it 'assigning any variable type to an if else with multiline in one branch' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = if foo
^{variable}^^^^^^^^^ Assign variables inside of conditionals.
1
else
something_else
2
end
RUBY
expect_correction(<<~RUBY)
if foo
#{variable} = 1
else
something_else
#{variable} = 2
end
RUBY
end
it 'assigning any variable type to a multiline if elsif else' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = if foo
^{variable}^^^^^^^^^ Assign variables inside of conditionals.
something
1
elsif bar
something_other
2
elsif baz
something_other_again
3
else
something_else
4
end
RUBY
expect_correction(<<~RUBY)
if foo
something
#{variable} = 1
elsif bar
something_other
#{variable} = 2
elsif baz
something_other_again
#{variable} = 3
else
something_else
#{variable} = 4
end
RUBY
end
it 'assigning any variable type to a multiline unless else' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = unless foo
^{variable}^^^^^^^^^^^^^ Assign variables inside of conditionals.
something
1
else
something_else
2
end
RUBY
expect_correction(<<~RUBY)
unless foo
something
#{variable} = 1
else
something_else
#{variable} = 2
end
RUBY
end
it 'assigning any variable type to a multiline case when' do
expect_offense(<<~RUBY, variable: variable)
%{variable} = case foo
^{variable}^^^^^^^^^^^ Assign variables inside of conditionals.
when "a"
something
1
else
something_else
2
end
RUBY
expect_correction(<<~RUBY)
case foo
when "a"
something
#{variable} = 1
else
something_else
#{variable} = 2
end
RUBY
end
end
shared_examples 'multiline all variable types allow' do |variable|
it 'assigning any variable type to a multiline if else' do
expect_no_offenses(<<~RUBY)
#{variable} = if foo
something
1
else
something_else
2
end
RUBY
end
it 'assigning any variable type to an if else with multiline in one branch' do
expect_no_offenses(<<~RUBY)
#{variable} = if foo
1
else
something_else
2
end
RUBY
end
it 'assigning any variable type to a multiline if elsif else' do
expect_no_offenses(<<~RUBY)
#{variable} = if foo
something
1
elsif
something_other
2
elsif
something_other_again
3
else
something_else
4
end
RUBY
end
it 'assigning any variable type to a multiline unless else' do
expect_no_offenses(<<~RUBY)
#{variable} = unless foo
something
1
else
something_else
2
end
RUBY
end
it 'assigning any variable type to a multiline case when' do
expect_no_offenses(<<~RUBY)
#{variable} = case foo
when "a"
something
1
else
something_else
2
end
RUBY
end
end
shared_examples 'multiline all assignment types offense' do |assignment|
it 'any assignment to a multiline if else' do
expect_offense(<<~RUBY, assignment: assignment)
bar %{assignment} if foo
^^^^^{assignment}^^^^^^^ Assign variables inside of conditionals.
something
1
else
something_else
2
end
RUBY
expect_correction(<<~RUBY)
if foo
something
bar #{assignment} 1
else
something_else
bar #{assignment} 2
end
RUBY
end
it 'any assignment to a multiline unless else' do
expect_offense(<<~RUBY, assignment: assignment)
bar %{assignment} unless foo
^^^^^{assignment}^^^^^^^^^^^ Assign variables inside of conditionals.
something
1
else
something_else
2
end
RUBY
expect_correction(<<~RUBY)
unless foo
something
bar #{assignment} 1
else
something_else
bar #{assignment} 2
end
RUBY
end
it 'any assignment to a multiline case when' do
expect_offense(<<~RUBY, assignment: assignment)
bar %{assignment} case foo
^^^^^{assignment}^^^^^^^^^ Assign variables inside of conditionals.
when "a"
something
1
else
something_else
2
end
RUBY
expect_correction(<<~RUBY)
case foo
when "a"
something
bar #{assignment} 1
else
something_else
bar #{assignment} 2
end
RUBY
end
end
shared_examples 'multiline all assignment types allow' do |assignment|
it 'any assignment to a multiline if else' do
expect_no_offenses(<<~RUBY)
bar #{assignment} if foo
something
1
else
something_else
2
end
RUBY
end
it 'any assignment to a multiline unless else' do
expect_no_offenses(<<~RUBY)
bar #{assignment} unless foo
something
1
else
something_else
2
end
RUBY
end
it 'any assignment to a multiline case when' do
expect_no_offenses(<<~RUBY)
bar #{assignment} case foo
when "a"
something
1
else
something_else
2
end
RUBY
end
end
shared_examples 'single line condition autocorrect' do
it 'corrects assignment to an if else condition' do
expect_offense(<<~RUBY)
bar = if foo
^^^^^^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
if foo
bar = 1
else
bar = 2
end
RUBY
end
it 'corrects assignment to an if elsif else condition' do
expect_offense(<<~RUBY)
bar = if foo
^^^^^^^^^^^^ Assign variables inside of conditionals.
1
elsif foobar
2
else
3
end
RUBY
expect_correction(<<~RUBY)
if foo
bar = 1
elsif foobar
bar = 2
else
bar = 3
end
RUBY
end
it 'corrects assignment to an if elsif else with multiple elsifs' do
expect_offense(<<~RUBY)
bar = if foo
^^^^^^^^^^^^ Assign variables inside of conditionals.
1
elsif foobar
2
elsif baz
3
else
4
end
RUBY
expect_correction(<<~RUBY)
if foo
bar = 1
elsif foobar
bar = 2
elsif baz
bar = 3
else
bar = 4
end
RUBY
end
it 'corrects assignment to an unless condition' do
expect_offense(<<~RUBY)
value = unless condition
^^^^^^^^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
1
end
RUBY
expect_correction(<<~RUBY)
unless condition
value = 1
end
RUBY
end
it 'corrects assignment to an unless else condition' do
expect_offense(<<~RUBY)
bar = unless foo
^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
unless foo
bar = 1
else
bar = 2
end
RUBY
end
it 'corrects assignment to a case when else condition' do
expect_offense(<<~RUBY)
bar = case foo
^^^^^^^^^^^^^^ Assign variables inside of conditionals.
when foobar
1
else
2
end
RUBY
expect_correction(<<~RUBY)
case foo
when foobar
bar = 1
else
bar = 2
end
RUBY
end
it 'corrects assignment to a case when else with multiple whens' do
expect_offense(<<~RUBY)
bar = case foo
^^^^^^^^^^^^^^ Assign variables inside of conditionals.
when foobar
1
when baz
2
else
3
end
RUBY
expect_correction(<<~RUBY)
case foo
when foobar
bar = 1
when baz
bar = 2
else
bar = 3
end
RUBY
end
it 'corrects assignment to a ternary operator' do
expect_offense(<<~RUBY)
bar = foo? ? 1 : 2
^^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
RUBY
expect_correction(<<~RUBY)
foo? ? bar = 1 : bar = 2
RUBY
end
end
shared_examples 'with `dstr` node in branch' do
it 'registers an offense for heredoc inside branch' do
expect_offense(<<~RUBY)
value = if a
^^^^^^^^^^^^ Assign variables inside of conditionals.
239
else
raise(ArgumentError, <<~ANSWER)
4
2
ANSWER
end
RUBY
expect_correction(<<~RUBY)
if a
value = 239
else
value = raise(ArgumentError, <<~ANSWER)
4
2
ANSWER
end
RUBY
end
it 'registers an offense for string interpolation inside branch' do
expect_offense(<<~'RUBY')
value = if a
^^^^^^^^^^^^ Assign variables inside of conditionals.
239
else
"#{foo} \
#{bar} \
"
end
RUBY
expect_correction(<<~'RUBY')
if a
value = 239
else
value = "#{foo} \
#{bar} \
"
end
RUBY
end
end
shared_examples 'with multiline regex in branch' do
it 'registers an offense for a multiline %r{} regex' do
expect_offense(<<~RUBY)
x = if condition
^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
%r{a
b}x
else
%r{c
d}x
end
RUBY
expect_correction(<<~RUBY)
if condition
x = %r{a
b}x
else
x = %r{c
d}x
end
RUBY
end
it 'registers an offense for a multiline regex assignment with interpolation and comments' do
expect_offense(<<~'RUBY')
x = if condition
^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
%r{#{foo}
b}x
else
%r{#{bar}
d}x
end
RUBY
expect_correction(<<~'RUBY')
if condition
x = %r{#{foo}
b}x
else
x = %r{#{bar}
d}x
end
RUBY
end
end
shared_examples 'with indexed assignment without arguments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo.[]=()
RUBY
end
end
context 'SingleLineConditionsOnly true' do
let(:config) do
RuboCop::Config.new('Style/ConditionalAssignment' => {
'Enabled' => true,
'SingleLineConditionsOnly' => true,
'IncludeTernaryExpressions' => true,
'EnforcedStyle' => 'assign_inside_condition',
'SupportedStyles' => %w[assign_to_condition
assign_inside_condition]
},
'Layout/EndAlignment' => {
'EnforcedStyleAlignWith' => 'keyword',
'Enabled' => true
},
'Layout/LineLength' => {
'Max' => 80,
'Enabled' => true
})
end
it_behaves_like('all variable types', 'bar')
it_behaves_like('all variable types', 'BAR')
it_behaves_like('all variable types', 'FOO::BAR')
it_behaves_like('all variable types', '@bar')
it_behaves_like('all variable types', '@@bar')
it_behaves_like('all variable types', '$BAR')
it_behaves_like('all variable types', 'foo.bar')
it_behaves_like('multiline all variable types allow', 'bar')
it_behaves_like('multiline all variable types allow', 'BAR')
it_behaves_like('multiline all variable types allow', 'FOO::BAR')
it_behaves_like('multiline all variable types allow', '@bar')
it_behaves_like('multiline all variable types allow', '@@bar')
it_behaves_like('multiline all variable types allow', '$BAR')
it_behaves_like('multiline all variable types allow', 'foo.bar')
it_behaves_like('all assignment types', '=')
it_behaves_like('all assignment types', '==')
it_behaves_like('all assignment types', '===')
it_behaves_like('all assignment types', '+=')
it_behaves_like('all assignment types', '-=')
it_behaves_like('all assignment types', '*=')
it_behaves_like('all assignment types', '**=')
it_behaves_like('all assignment types', '/=')
it_behaves_like('all assignment types', '%=')
it_behaves_like('all assignment types', '^=')
it_behaves_like('all assignment types', '&=')
it_behaves_like('all assignment types', '|=')
it_behaves_like('all assignment types', '<=')
it_behaves_like('all assignment types', '>=')
it_behaves_like('all assignment types', '<<=')
it_behaves_like('all assignment types', '>>=')
it_behaves_like('all assignment types', '||=')
it_behaves_like('all assignment types', '&&=')
it_behaves_like('all assignment types', '<<')
it_behaves_like('multiline all assignment types allow', '=')
it_behaves_like('multiline all assignment types allow', '==')
it_behaves_like('multiline all assignment types allow', '===')
it_behaves_like('multiline all assignment types allow', '+=')
it_behaves_like('multiline all assignment types allow', '-=')
it_behaves_like('multiline all assignment types allow', '*=')
it_behaves_like('multiline all assignment types allow', '**=')
it_behaves_like('multiline all assignment types allow', '/=')
it_behaves_like('multiline all assignment types allow', '%=')
it_behaves_like('multiline all assignment types allow', '^=')
it_behaves_like('multiline all assignment types allow', '&=')
it_behaves_like('multiline all assignment types allow', '|=')
it_behaves_like('multiline all assignment types allow', '<=')
it_behaves_like('multiline all assignment types allow', '>=')
it_behaves_like('multiline all assignment types allow', '<<=')
it_behaves_like('multiline all assignment types allow', '>>=')
it_behaves_like('multiline all assignment types allow', '||=')
it_behaves_like('multiline all assignment types allow', '&&=')
it_behaves_like('multiline all assignment types allow', '<<')
it_behaves_like('with `dstr` node in branch')
it_behaves_like('with multiline regex in branch')
it_behaves_like('with indexed assignment without arguments')
it 'allows a method call in the subject of a ternary operator' do
expect_no_offenses('bar << foo? ? 1 : 2')
end
it 'registers an offense for assignment using a method that ends with an equal sign' do
expect_offense(<<~RUBY)
self.attributes = foo? ? 1 : 2
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
RUBY
expect_correction(<<~RUBY)
foo? ? self.attributes = 1 : self.attributes = 2
RUBY
end
it 'registers an offense for assignment using []=' do
expect_offense(<<~RUBY)
foo[:a] = if bar?
^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
if bar?
foo[:a] = 1
else
foo[:a] = 2
end
RUBY
end
it 'registers an offense for assignment to an if then else' do
expect_offense(<<~RUBY)
bar = if foo then 1
^^^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
else 2
end
RUBY
expect_correction(<<~RUBY)
if foo then bar = 1
else bar = 2
end
RUBY
end
it 'registers an offense for assignment to an one-line if then else' do
expect_offense(<<~RUBY)
bar = if foo then 1 else 2 end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
RUBY
expect_correction(<<~RUBY)
if foo then bar = 1 else bar = 2 end
RUBY
end
it 'registers an offense for assignment with one-line `else` and `end`' do
expect_offense(<<~RUBY)
bar = if foo
^^^^^^^^^^^^ Assign variables inside of conditionals.
1
else 2 end
RUBY
expect_correction(<<~RUBY)
if foo
bar = 1
else bar = 2 end
RUBY
end
it 'registers an offense for assignment with one-line `else` and `end` with nested branch' do
expect_offense(<<~RUBY)
bar = if foo
^^^^^^^^^^^^ Assign variables inside of conditionals.
1
elsif baz
2
else 3 end
RUBY
expect_correction(<<~RUBY)
if foo
bar = 1
elsif baz
bar = 2
else bar = 3 end
RUBY
end
it 'registers an offense for an assignment that uses if branch bodies including a block' do
expect_offense(<<~RUBY)
result = if condition
^^^^^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
foo do
end
else
bar do
end
end
RUBY
expect_correction(<<~RUBY)
if condition
result = foo do
end
else
result = bar do
end
end
RUBY
end
it 'registers an offense for assignment to case when then else' do
expect_offense(<<~RUBY)
baz = case foo
^^^^^^^^^^^^^^ Assign variables inside of conditionals.
when bar then 1
else 2
end
RUBY
expect_correction(<<~RUBY)
case foo
when bar then baz = 1
else baz = 2
end
RUBY
end
it 'registers an offense when empty `case` condition' do
expect_offense(<<~RUBY)
var = case
^^^^^^^^^^ Assign variables inside of conditionals.
when foo
bar
else
baz
end
RUBY
expect_correction(<<~RUBY)
case
when foo
var = bar
else
var = baz
end
RUBY
end
context 'for loop' do
it 'ignores pseudo assignments in a for loop' do
expect_no_offenses('for i in [1, 2, 3]; puts i; end')
end
end
it_behaves_like('single line condition autocorrect')
it 'corrects assignment to a namespaced constant' do
expect_offense(<<~RUBY)
FOO::BAR = if baz?
^^^^^^^^^^^^^^^^^^ Assign variables inside of conditionals.
1
else
2
end
RUBY
expect_correction(<<~RUBY)
if baz?
FOO::BAR = 1
else
FOO::BAR = 2
end
RUBY
end
it 'corrects assignment when without `else` branch' do
expect_offense(<<~RUBY)
var = if foo
^^^^^^^^^^^^ Assign variables inside of conditionals.
bar
elsif baz
qux
end
RUBY
expect_correction(<<~RUBY)
if foo
var = bar
elsif baz
var = qux
end
RUBY
end
end
context 'SingleLineConditionsOnly false' do
let(:config) do
RuboCop::Config.new('Style/ConditionalAssignment' => {
'Enabled' => true,
'SingleLineConditionsOnly' => false,
'IncludeTernaryExpressions' => true,
'EnforcedStyle' => 'assign_inside_condition',
'SupportedStyles' => %w[assign_to_condition
assign_inside_condition]
},
'Layout/EndAlignment' => {
'EnforcedStyleAlignWith' => 'keyword',
'Enabled' => true
},
'Layout/LineLength' => {
'Max' => 80,
'Enabled' => true
})
end
it_behaves_like('all variable types', 'bar')
it_behaves_like('all variable types', 'BAR')
it_behaves_like('all variable types', 'FOO::BAR')
it_behaves_like('all variable types', '@bar')
it_behaves_like('all variable types', '@@bar')
it_behaves_like('all variable types', '$BAR')
it_behaves_like('all variable types', 'foo.bar')
it_behaves_like('multiline all variable types offense', 'bar')
it_behaves_like('multiline all variable types offense', 'BAR')
it_behaves_like('multiline all variable types offense', 'FOO::BAR')
it_behaves_like('multiline all variable types offense', '@bar')
it_behaves_like('multiline all variable types offense', '@@bar')
it_behaves_like('multiline all variable types offense', '$BAR')
it_behaves_like('multiline all variable types offense', 'foo.bar')
it_behaves_like('all assignment types', '=')
it_behaves_like('all assignment types', '==')
it_behaves_like('all assignment types', '===')
it_behaves_like('all assignment types', '+=')
it_behaves_like('all assignment types', '-=')
it_behaves_like('all assignment types', '*=')
it_behaves_like('all assignment types', '**=')
it_behaves_like('all assignment types', '/=')
it_behaves_like('all assignment types', '%=')
it_behaves_like('all assignment types', '^=')
it_behaves_like('all assignment types', '&=')
it_behaves_like('all assignment types', '|=')
it_behaves_like('all assignment types', '<=')
it_behaves_like('all assignment types', '>=')
it_behaves_like('all assignment types', '<<=')
it_behaves_like('all assignment types', '>>=')
it_behaves_like('all assignment types', '||=')
it_behaves_like('all assignment types', '&&=')
it_behaves_like('all assignment types', '<<')
it_behaves_like('multiline all assignment types offense', '=')
it_behaves_like('multiline all assignment types offense', '==')
it_behaves_like('multiline all assignment types offense', '===')
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/collection_methods_spec.rb | spec/rubocop/cop/style/collection_methods_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::CollectionMethods, :config do
cop_config = {
'PreferredMethods' => {
'collect' => 'map',
'inject' => 'reduce',
'detect' => 'find',
'find_all' => 'select',
'member?' => 'include?'
}
}
let(:cop_config) { cop_config }
cop_config['PreferredMethods'].each do |method, preferred_method|
context "#{method} with block" do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method} { |e| e + 1 }
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{preferred_method} { |e| e + 1 }
RUBY
end
context 'safe navigation' do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3]&.%{method} { |e| e + 1 }
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.#{preferred_method} { |e| e + 1 }
RUBY
end
end
end
context 'Ruby 2.7', :ruby27 do
context "#{method} with numblock" do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method} { _1 + 1 }
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{preferred_method} { _1 + 1 }
RUBY
end
context 'with safe navigation' do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3]&.%{method} { _1 + 1 }
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.#{preferred_method} { _1 + 1 }
RUBY
end
end
end
end
context 'Ruby 3.4', :ruby34 do
context "#{method} with itblock" do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method} { it + 1 }
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{preferred_method} { it + 1 }
RUBY
end
context 'with safe navigation' do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3]&.%{method} { it + 1 }
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.#{preferred_method} { it + 1 }
RUBY
end
end
end
end
context "#{method} with proc param" do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method}(&:test)
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{preferred_method}(&:test)
RUBY
end
context 'safe navigation' do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3]&.%{method}(&:test)
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.#{preferred_method}(&:test)
RUBY
end
end
end
context "#{method} with an argument and proc param" do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3].%{method}(0, &:test)
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].#{preferred_method}(0, &:test)
RUBY
end
context 'with safe navigation' do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
[1, 2, 3]&.%{method}(0, &:test)
^{method} Prefer `#{preferred_method}` over `#{method}`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.#{preferred_method}(0, &:test)
RUBY
end
end
end
context "#{method} without a block" do
it "accepts #{method} without a block" do
expect_no_offenses(<<~RUBY)
[1, 2, 3].#{method}
RUBY
end
context 'with safe navigation' do
it "accepts #{method} without a block" do
expect_no_offenses(<<~RUBY)
[1, 2, 3]&.#{method}
RUBY
end
end
end
end
context 'for methods that accept a symbol as implicit block' do
context 'with a final symbol param' do
it 'registers an offense with a final symbol param' do
expect_offense(<<~RUBY)
[1, 2, 3].inject(:+)
^^^^^^ Prefer `reduce` over `inject`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].reduce(:+)
RUBY
end
context 'with safe navigation' do
it 'registers an offense with a final symbol param' do
expect_offense(<<~RUBY)
[1, 2, 3]&.inject(:+)
^^^^^^ Prefer `reduce` over `inject`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.reduce(:+)
RUBY
end
end
end
context 'with an argument and final symbol param' do
it 'registers an offense' do
expect_offense(<<~RUBY)
[1, 2, 3].inject(0, :+)
^^^^^^ Prefer `reduce` over `inject`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].reduce(0, :+)
RUBY
end
context 'with safe navigation' do
it 'registers an offense' do
expect_offense(<<~RUBY)
[1, 2, 3]&.inject(0, :+)
^^^^^^ Prefer `reduce` over `inject`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3]&.reduce(0, :+)
RUBY
end
end
end
end
context 'for methods that do not accept a symbol as implicit block' do
context 'for a final symbol param' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].collect(:+)
RUBY
end
context 'with safe navigation' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
[1, 2, 3]&.collect(:+)
RUBY
end
end
end
context 'for a final symbol param with extra args' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].collect(0, :+)
RUBY
end
context 'with safe navigation' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
[1, 2, 3]&.collect(0, :+)
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/mixin_grouping_spec.rb | spec/rubocop/cop/style/mixin_grouping_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::MixinGrouping, :config do
context 'when configured with separated style' do
let(:cop_config) { { 'EnforcedStyle' => 'separated' } }
context 'when using `include`' do
it 'registers an offense for several mixins in one call' do
expect_offense(<<~RUBY)
class Foo
include Bar, Qux
^^^^^^^^^^^^^^^^ Put `include` mixins in separate statements.
end
RUBY
expect_correction(<<~RUBY)
class Foo
include Qux
include Bar
end
RUBY
end
it 'allows include call as an argument to another method' do
expect_no_offenses('expect(foo).to include { { bar: baz } }')
end
it 'registers an offense for several mixins in separate calls' do
expect_offense(<<~RUBY)
class Foo
include Bar, Baz
^^^^^^^^^^^^^^^^ Put `include` mixins in separate statements.
include Qux
end
RUBY
expect_correction(<<~RUBY)
class Foo
include Baz
include Bar
include Qux
end
RUBY
end
it 'does not register an offense when `include` has no arguments' do
expect_no_offenses(<<~RUBY)
class Foo
include
end
RUBY
end
end
context 'when using `extend`' do
it 'registers an offense for several mixins in one call' do
expect_offense(<<~RUBY)
class Foo
extend Bar, Qux
^^^^^^^^^^^^^^^ Put `extend` mixins in separate statements.
end
RUBY
expect_correction(<<~RUBY)
class Foo
extend Qux
extend Bar
end
RUBY
end
it 'does not register an offense when `extend` has no arguments' do
expect_no_offenses(<<~RUBY)
class Foo
extend
end
RUBY
end
end
context 'when using `prepend`' do
it 'registers an offense for several mixins in one call' do
expect_offense(<<~RUBY)
class Foo
prepend Bar, Qux
^^^^^^^^^^^^^^^^ Put `prepend` mixins in separate statements.
end
RUBY
expect_correction(<<~RUBY)
class Foo
prepend Qux
prepend Bar
end
RUBY
end
it 'does not register an offense when `prepend` has no arguments' do
expect_no_offenses(<<~RUBY)
class Foo
prepend
end
RUBY
end
end
context 'when using a mix of different methods' do
it 'registers an offense for some calls having several mixins' do
expect_offense(<<~RUBY)
class Foo
include Bar, Baz
^^^^^^^^^^^^^^^^ Put `include` mixins in separate statements.
extend Qux
end
RUBY
expect_correction(<<~RUBY)
class Foo
include Baz
include Bar
extend Qux
end
RUBY
end
end
end
context 'when configured with grouped style' do
let(:cop_config) { { 'EnforcedStyle' => 'grouped' } }
context 'when using include' do
it 'registers an offense for single mixins in separate calls' do
expect_offense(<<~RUBY)
class Foo
include Bar
^^^^^^^^^^^ Put `include` mixins in a single statement.
include Baz
^^^^^^^^^^^ Put `include` mixins in a single statement.
include Qux
^^^^^^^^^^^ Put `include` mixins in a single statement.
end
RUBY
expect_correction(<<~RUBY)
class Foo
include Qux, Baz, Bar
end
RUBY
end
it 'allows include with an explicit receiver' do
expect_no_offenses(<<~RUBY)
config.include Foo
config.include Bar
RUBY
end
it 'registers an offense for several mixins in separate calls' do
expect_offense(<<~RUBY)
class Foo
include Bar, Baz
^^^^^^^^^^^^^^^^ Put `include` mixins in a single statement.
include FooBar, FooBaz
^^^^^^^^^^^^^^^^^^^^^^ Put `include` mixins in a single statement.
include Qux, FooBarBaz
^^^^^^^^^^^^^^^^^^^^^^ Put `include` mixins in a single statement.
end
RUBY
expect_correction(<<~RUBY)
class Foo
include Qux, FooBarBaz, FooBar, FooBaz, Bar, Baz
end
RUBY
end
end
context 'when using `extend`' do
it 'registers an offense for single mixins in separate calls' do
expect_offense(<<~RUBY)
class Foo
extend Bar
^^^^^^^^^^ Put `extend` mixins in a single statement.
extend Baz
^^^^^^^^^^ Put `extend` mixins in a single statement.
end
RUBY
expect_correction(<<~RUBY)
class Foo
extend Baz, Bar
end
RUBY
end
end
context 'when using `prepend`' do
it 'registers an offense for single mixins in separate calls' do
expect_offense(<<~RUBY)
class Foo
prepend Bar
^^^^^^^^^^^ Put `prepend` mixins in a single statement.
prepend Baz
^^^^^^^^^^^ Put `prepend` mixins in a single statement.
end
RUBY
expect_correction(<<~RUBY)
class Foo
prepend Baz, Bar
end
RUBY
end
it 'registers an offense for single mixins in separate calls, interspersed' do
expect_offense(<<~RUBY)
class Foo
prepend Bar
^^^^^^^^^^^ Put `prepend` mixins in a single statement.
prepend Baz
^^^^^^^^^^^ Put `prepend` mixins in a single statement.
do_something_else
prepend Qux
^^^^^^^^^^^ Put `prepend` mixins in a single statement.
end
RUBY
# empty line left by prepend Qux
expect_correction(<<~RUBY)
class Foo
prepend Qux, Baz, Bar
do_something_else
#{trailing_whitespace}
end
RUBY
end
it 'registers an offense when other mixins have receivers' do
expect_offense(<<~RUBY)
class Foo
prepend Bar
^^^^^^^^^^^ Put `prepend` mixins in a single statement.
Other.prepend Baz
do_something_else
prepend Qux
^^^^^^^^^^^ Put `prepend` mixins in a single statement.
end
RUBY
# empty line left by prepend Qux
expect_correction(<<~RUBY)
class Foo
prepend Qux, Bar
Other.prepend Baz
do_something_else
#{trailing_whitespace}
end
RUBY
end
end
context 'when using a mix of different methods' do
it 'registers an offense with some duplicated mixin methods' do
expect_offense(<<~RUBY)
class Foo
include Bar
^^^^^^^^^^^ Put `include` mixins in a single statement.
include Baz
^^^^^^^^^^^ Put `include` mixins in a single statement.
extend Baz
end
RUBY
expect_correction(<<~RUBY)
class Foo
include Baz, Bar
extend Baz
end
RUBY
end
it 'allows all different mixin methods' do
expect_no_offenses(<<~RUBY)
class Foo
include Bar
prepend Baz
extend 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/lambda_call_spec.rb | spec/rubocop/cop/style/lambda_call_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::LambdaCall, :config do
context 'when style is set to call' do
let(:cop_config) { { 'EnforcedStyle' => 'call' } }
it 'registers an offense for x.()' do
expect_offense(<<~RUBY)
x.(a, b)
^^^^^^^^ Prefer the use of `x.call(a, b)` over `x.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x.call(a, b)
RUBY
end
it 'registers an offense for x&.()' do
expect_offense(<<~RUBY)
x&.(a, b)
^^^^^^^^^ Prefer the use of `x&.call(a, b)` over `x&.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x&.call(a, b)
RUBY
end
it 'registers an offense for x.().()' do
expect_offense(<<~RUBY)
x.(a, b).(c)
^^^^^^^^^^^^ Prefer the use of `x.(a, b).call(c)` over `x.(a, b).(c)`.
^^^^^^^^ Prefer the use of `x.call(a, b)` over `x.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x.(a, b).call(c)
RUBY
end
it 'registers an offense for x&.()&.()' do
expect_offense(<<~RUBY)
x&.(a, b)&.(c)
^^^^^^^^^^^^^^ Prefer the use of `x&.(a, b)&.call(c)` over `x&.(a, b)&.(c)`.
^^^^^^^^^ Prefer the use of `x&.call(a, b)` over `x&.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x&.(a, b)&.call(c)
RUBY
end
it 'registers an offense for x.() with no arguments' do
expect_offense(<<~RUBY)
x.()
^^^^ Prefer the use of `x.call` over `x.()`.
RUBY
expect_correction(<<~RUBY)
x.call
RUBY
end
it 'registers an offense for correct + opposite' do
expect_offense(<<~RUBY)
x.call(a, b)
x.(a, b)
^^^^^^^^ Prefer the use of `x.call(a, b)` over `x.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x.call(a, b)
x.call(a, b)
RUBY
end
it 'registers an offense for correct + opposite with safe navigation' do
expect_offense(<<~RUBY)
x&.call(a, b)
x&.(a, b)
^^^^^^^^^ Prefer the use of `x&.call(a, b)` over `x&.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x&.call(a, b)
x&.call(a, b)
RUBY
end
it 'registers an offense for correct + multiple opposite styles' do
expect_offense(<<~RUBY)
x.call(a, b)
x.(a, b)
^^^^^^^^ Prefer the use of `x.call(a, b)` over `x.(a, b)`.
x.(a, b)
^^^^^^^^ Prefer the use of `x.call(a, b)` over `x.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x.call(a, b)
x.call(a, b)
x.call(a, b)
RUBY
end
it 'registers an offense for correct + multiple opposite styles with safe navigation' do
expect_offense(<<~RUBY)
x&.call(a, b)
x&.(a, b)
^^^^^^^^^ Prefer the use of `x&.call(a, b)` over `x&.(a, b)`.
x&.(a, b)
^^^^^^^^^ Prefer the use of `x&.call(a, b)` over `x&.(a, b)`.
RUBY
expect_correction(<<~RUBY)
x&.call(a, b)
x&.call(a, b)
x&.call(a, b)
RUBY
end
end
context 'when style is set to braces' do
let(:cop_config) { { 'EnforcedStyle' => 'braces' } }
it 'registers an offense for x.call()' do
expect_offense(<<~RUBY)
x.call(a, b)
^^^^^^^^^^^^ Prefer the use of `x.(a, b)` over `x.call(a, b)`.
RUBY
expect_correction(<<~RUBY)
x.(a, b)
RUBY
end
it 'registers an offense for x&.call()' do
expect_offense(<<~RUBY)
x&.call(a, b)
^^^^^^^^^^^^^ Prefer the use of `x&.(a, b)` over `x&.call(a, b)`.
RUBY
expect_correction(<<~RUBY)
x&.(a, b)
RUBY
end
it 'registers an offense for opposite + correct' do
expect_offense(<<~RUBY)
x.call(a, b)
^^^^^^^^^^^^ Prefer the use of `x.(a, b)` over `x.call(a, b)`.
x.(a, b)
RUBY
expect_correction(<<~RUBY)
x.(a, b)
x.(a, b)
RUBY
end
it 'registers an offense for opposite + correct with safe navigation' do
expect_offense(<<~RUBY)
x&.call(a, b)
^^^^^^^^^^^^^ Prefer the use of `x&.(a, b)` over `x&.call(a, b)`.
x&.(a, b)
RUBY
expect_correction(<<~RUBY)
x&.(a, b)
x&.(a, b)
RUBY
end
it 'registers an offense for correct + multiple opposite styles' do
expect_offense(<<~RUBY)
x.call(a, b)
^^^^^^^^^^^^ Prefer the use of `x.(a, b)` over `x.call(a, b)`.
x.(a, b)
x.call(a, b)
^^^^^^^^^^^^ Prefer the use of `x.(a, b)` over `x.call(a, b)`.
RUBY
expect_correction(<<~RUBY)
x.(a, b)
x.(a, b)
x.(a, b)
RUBY
end
it 'registers an offense for correct + multiple opposite styles with safe navigation' do
expect_offense(<<~RUBY)
x&.call(a, b)
^^^^^^^^^^^^^ Prefer the use of `x&.(a, b)` over `x&.call(a, b)`.
x&.(a, b)
x&.call(a, b)
^^^^^^^^^^^^^ Prefer the use of `x&.(a, b)` over `x&.call(a, b)`.
RUBY
expect_correction(<<~RUBY)
x&.(a, b)
x&.(a, b)
x&.(a, b)
RUBY
end
it 'accepts a call without receiver' do
expect_no_offenses('call(a, b)')
end
it 'autocorrects x.call to x.()' do
expect_offense(<<~RUBY)
a.call
^^^^^^ Prefer the use of `a.()` over `a.call`.
RUBY
expect_correction(<<~RUBY)
a.()
RUBY
end
it 'autocorrects x.call asdf, x123 to x.(asdf, x123)' do
expect_offense(<<~RUBY)
a.call asdf, x123
^^^^^^^^^^^^^^^^^ Prefer the use of `a.(asdf, x123)` over `a.call asdf, x123`.
RUBY
expect_correction(<<~RUBY)
a.(asdf, x123)
RUBY
end
it 'autocorrects x&.call asdf, x123 to x&.(asdf, x123)' do
expect_offense(<<~RUBY)
a&.call asdf, x123
^^^^^^^^^^^^^^^^^^ Prefer the use of `a&.(asdf, x123)` over `a&.call asdf, x123`.
RUBY
expect_correction(<<~RUBY)
a&.(asdf, x123)
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/bitwise_predicate_spec.rb | spec/rubocop/cop/style/bitwise_predicate_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::BitwisePredicate, :config do
context 'when checking any set bits' do
context 'when Ruby >= 2.5', :ruby25 do
it 'registers an offense when using `&` in conjunction with `predicate` for comparisons' do
expect_offense(<<~RUBY)
(variable & flags).positive?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.anybits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.anybits?(flags)
RUBY
end
it 'registers an offense when using `&` in conjunction with `> 0` for comparisons' do
expect_offense(<<~RUBY)
(variable & flags) > 0
^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.anybits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.anybits?(flags)
RUBY
end
it 'registers an offense when using `&` in conjunction with `>= 1` for comparisons' do
expect_offense(<<~RUBY)
(variable & flags) >= 1
^^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.anybits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.anybits?(flags)
RUBY
end
it 'registers an offense when using `&` in conjunction with `!= 0` for comparisons' do
expect_offense(<<~RUBY)
(variable & flags) != 0
^^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.anybits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.anybits?(flags)
RUBY
end
it 'does not register an offense when using `anybits?` method' do
expect_no_offenses(<<~RUBY)
variable.anybits?(flags)
RUBY
end
it 'does not register an offense when using `&` in conjunction with `> 1` for comparisons' do
expect_no_offenses(<<~RUBY)
(variable & flags) > 1
RUBY
end
it 'does not register an offense when comparing with no parentheses' do
expect_no_offenses(<<~RUBY)
foo == bar
RUBY
end
end
context 'when Ruby <= 2.4', :ruby24, unsupported_on: :prism do
it 'does not register an offense when using `&` in conjunction with `predicate` for comparisons' do
expect_no_offenses(<<~RUBY)
(variable & flags).positive?
RUBY
end
end
end
context 'when checking all set bits' do
context 'when Ruby >= 2.5', :ruby25 do
it 'registers an offense when using `&` with RHS flags in conjunction with `==` for comparisons' do
expect_offense(<<~RUBY)
(variable & flags) == flags
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.allbits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.allbits?(flags)
RUBY
end
it 'registers an offense when using `&` with LHS flags in conjunction with `==` for comparisons' do
expect_offense(<<~RUBY)
(flags & variable) == flags
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.allbits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.allbits?(flags)
RUBY
end
it 'does not register an offense when using `allbits?` method' do
expect_no_offenses(<<~RUBY)
variable.allbits?(flags)
RUBY
end
it 'does not register an offense when flag variable names are mismatched' do
expect_no_offenses(<<~RUBY)
(flags & variable) == flagments
RUBY
end
end
context 'when Ruby <= 2.4', :ruby24, unsupported_on: :prism do
it 'does not register an offense when using `&` with RHS flags in conjunction with `==` for comparisons' do
expect_no_offenses(<<~RUBY)
(variable & flags) == flags
RUBY
end
end
end
context 'when checking no set bits' do
context 'when Ruby >= 2.5', :ruby25 do
it 'registers an offense when using `&` in conjunction with `zero?` for comparisons' do
expect_offense(<<~RUBY)
(variable & flags).zero?
^^^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.nobits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.nobits?(flags)
RUBY
end
it 'registers an offense when using `&` in conjunction with `== 0` for comparisons' do
expect_offense(<<~RUBY)
(variable & flags) == 0
^^^^^^^^^^^^^^^^^^^^^^^ Replace with `variable.nobits?(flags)` for comparison with bit flags.
RUBY
expect_correction(<<~RUBY)
variable.nobits?(flags)
RUBY
end
it 'does not register an offense when using `nobits?` method' do
expect_no_offenses(<<~RUBY)
variable.nobits?(flags)
RUBY
end
end
context 'when Ruby <= 2.4', :ruby24, unsupported_on: :prism do
it 'does not register an offense when using `&` in conjunction with `zero?` for comparisons' do
expect_no_offenses(<<~RUBY)
(variable & flags).zero?
RUBY
end
end
end
context 'when using a simple method call' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
zero?
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trailing_body_on_method_definition_spec.rb | spec/rubocop/cop/style/trailing_body_on_method_definition_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrailingBodyOnMethodDefinition, :config do
let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 2 }) }
it 'registers an offense when body trails after method definition' do
expect_offense(<<~RUBY)
def some_method; body
^^^^ Place the first line of a multi-line method definition's body on its own line.
end
def extra_large; { size: 15 };
^^^^^^^^^^^^ Place the first line of a multi-line method definition's body on its own line.
end
def seven_times(stuff) 7.times { do_this(stuff) }
^^^^^^^^^^^^^^^^^^^^^^^^^^ Place the first line of a multi-line method definition's body on its own line.
end
RUBY
expect_correction(<<~RUBY)
def some_method#{trailing_whitespace}
body
end
def extra_large#{trailing_whitespace}
{ size: 15 };
end
def seven_times(stuff)#{trailing_whitespace}
7.times { do_this(stuff) }
end
RUBY
end
it 'registers when body starts on def line & continues one more line' do
expect_offense(<<~RUBY)
def some_method; foo = {}
^^^^^^^^ Place the first line of a multi-line method definition's body on its own line.
more_body(foo)
end
RUBY
expect_correction(<<~RUBY)
def some_method#{trailing_whitespace}
foo = {}
more_body(foo)
end
RUBY
end
it 'registers when body starts on def line & continues many more lines' do
expect_offense(<<~RUBY)
def do_stuff(thing) process(thing)
^^^^^^^^^^^^^^ Place the first line of a multi-line method definition's body on its own line.
8.times { thing + 9 }
even_more(thing)
end
RUBY
expect_correction(<<~RUBY)
def do_stuff(thing)#{trailing_whitespace}
process(thing)
8.times { thing + 9 }
even_more(thing)
end
RUBY
end
it 'registers an offense when an expression precedes a method definition on the same line with a semicolon' do
expect_offense(<<~RUBY)
foo;def some_method; body
^^^^ Place the first line of a multi-line method definition's body on its own line.
end
RUBY
expect_correction(<<~RUBY)
foo;def some_method#{trailing_whitespace}
body
end
RUBY
end
it 'accepts a method with one line of body' do
expect_no_offenses(<<~RUBY)
def some_method
body
end
RUBY
end
it 'accepts a method with multiple lines of body' do
expect_no_offenses(<<~RUBY)
def stuff_method
stuff
9.times { process(stuff) }
more_stuff
end
RUBY
end
it 'does not register offense with trailing body on method end' do
expect_no_offenses(<<~RUBY)
def some_method
body
foo; end
RUBY
end
context 'Ruby 3.0 or higher', :ruby30 do
it 'does not register offense when endless method definition body is after newline in opening parenthesis' do
expect_no_offenses(<<~RUBY)
def some_method = (
body
)
RUBY
end
end
it 'autocorrects with comment after body' do
expect_offense(<<-RUBY.strip_margin('|'))
| def some_method; body # stuff
| ^^^^ Place the first line of a multi-line method definition's body on its own line.
| end
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| # stuff
| def some_method#{trailing_whitespace}
| body#{trailing_whitespace}
| end
RUBY
end
it 'autocorrects body with method definition with args not in parens' do
expect_offense(<<-RUBY.strip_margin('|'))
| def some_method arg1, arg2; body
| ^^^^ Place the first line of a multi-line method definition's body on its own line.
| end
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| def some_method arg1, arg2#{trailing_whitespace}
| body
| end
RUBY
end
it 'removes semicolon from method definition but not body when autocorrecting' do
expect_offense(<<-RUBY.strip_margin('|'))
| def some_method; body; more_body;
| ^^^^ Place the first line of a multi-line method definition's body on its own line.
| end
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| def some_method#{trailing_whitespace}
| body; more_body;
| end
RUBY
end
context 'when method is not on first line of processed_source' do
it 'autocorrects offense' do
expect_offense(<<-RUBY.strip_margin('|'))
|
| def some_method; body
| ^^^^ Place the first line of a multi-line method definition's body on its own line.
| end
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
|
| def some_method#{trailing_whitespace}
| body
| 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/semicolon_spec.rb | spec/rubocop/cop/style/semicolon_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::Semicolon, :config do
let(:cop_config) { { 'AllowAsExpressionSeparator' => false } }
it 'registers an offense for a single expression' do
expect_offense(<<~RUBY)
puts "this is a test";
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
puts "this is a test"
RUBY
end
it 'registers an offense for several expressions' do
expect_offense(<<~RUBY)
puts "this is a test"; puts "So is this"
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
puts "this is a test"
puts "So is this"
RUBY
end
it 'registers an offense for one line method with two statements' do
expect_offense(<<~RUBY)
def foo(a) x(1); y(2); z(3); end
^ Do not use semicolons to terminate expressions.
^ Do not use semicolons to terminate expressions.
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
def foo(a) x(1)
y(2)
z(3)
end
RUBY
end
it 'registers an offense when using a semicolon between a closing parenthesis after a line break and a consequent expression' do
expect_offense(<<~RUBY)
foo(
bar); baz
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
foo(
bar)
baz
RUBY
end
it 'accepts semicolon before end if so configured' do
expect_no_offenses('def foo(a) z(3); end')
end
it 'accepts semicolon after params if so configured' do
expect_no_offenses('def foo(a); z(3) end')
end
it 'accepts one line method definitions' do
expect_no_offenses(<<~RUBY)
def foo1; x(3) end
def initialize(*_); end
def foo2() x(3); end
def foo3; x(3); end
RUBY
end
it 'accepts one line empty class definitions' do
expect_no_offenses(<<~RUBY)
# Prefer a single-line format for class ...
class Foo < Exception; end
class Bar; end
RUBY
end
it 'accepts one line empty method definitions' do
expect_no_offenses(<<~RUBY)
# One exception to the rule are empty-body methods
def no_op; end
def foo; end
RUBY
end
it 'accepts one line empty module definitions' do
expect_no_offenses('module Foo; end')
end
it 'registers an offense for semicolon at the end no matter what' do
expect_offense(<<~RUBY)
module Foo; end;
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
module Foo; end
RUBY
end
it 'accepts semicolons inside strings' do
expect_no_offenses(<<~RUBY)
string = ";
multi-line string"
RUBY
end
it 'registers an offense for a semicolon at the beginning of a line' do
expect_offense(<<~RUBY)
; puts 1
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(" puts 1\n")
end
it 'registers an offense for a semicolon at the beginning of a block' do
expect_offense(<<~RUBY)
foo {; bar }
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
foo { bar }
RUBY
end
it 'registers an offense for a semicolon at the beginning of a lambda block' do
expect_offense(<<~RUBY)
foo -> {; bar }
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
foo -> { bar }
RUBY
end
it 'registers an offense for a semicolon at the end of a block' do
expect_offense(<<~RUBY)
foo { bar; }
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
foo { bar }
RUBY
end
it 'registers an offense for a semicolon at the middle of a block' do
expect_offense(<<~RUBY)
foo { bar; baz }
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
foo { bar
baz }
RUBY
end
it 'does not register an offense when using a comment containing a semicolon before a block' do
expect_no_offenses(<<~RUBY)
# ;
foo {
}
RUBY
end
it 'registers an offense when a semicolon at before a closing brace of string interpolation' do
expect_offense(<<~'RUBY')
"#{foo;}"
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~'RUBY')
"#{foo}"
RUBY
end
it 'registers an offense when a semicolon at after an opening brace of string interpolation' do
expect_offense(<<~'RUBY')
"#{;foo}"
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~'RUBY')
"#{foo}"
RUBY
end
it 'registers an offense for range (`1..42`) with semicolon' do
expect_offense(<<~RUBY)
1..42;
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
1..42
RUBY
end
it 'registers an offense for range (`1...42`) with semicolon' do
expect_offense(<<~RUBY)
1...42;
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
1...42
RUBY
end
context 'Ruby >= 2.6', :ruby26 do
it 'registers an offense for endless range with semicolon (irange only)' do
expect_offense(<<~RUBY)
42..;
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
(42..)
RUBY
end
it 'registers an offense for endless range with semicolon (irange and erange)' do
expect_offense(<<~RUBY)
42..;
^ Do not use semicolons to terminate expressions.
42...;
^ Do not use semicolons to terminate expressions.
RUBY
expect_correction(<<~RUBY)
(42..)
(42...)
RUBY
end
it 'registers an offense for endless range with semicolon in the method definition' do
expect_offense(<<~RUBY)
def foo
42..;
^ Do not use semicolons to terminate expressions.
end
RUBY
expect_correction(<<~RUBY)
def foo
(42..)
end
RUBY
end
it 'does not register an offense for endless range without semicolon' do
expect_no_offenses(<<~RUBY)
42..
RUBY
end
end
it 'registers an offense for a method call with keyword arguments without parentheses when terminated with a semicolon' do
expect_offense(<<~RUBY)
m key: value;
^ Do not use semicolons to terminate expressions.
do_something
RUBY
expect_correction(<<~RUBY)
m key: value
do_something
RUBY
end
context 'Ruby >= 3.1', :ruby31 do
it 'registers an offense for a method call using multiple hash value omission without parentheses when terminated with a semicolon' do
expect_offense(<<~RUBY)
m key1:, key2:;
^ Do not use semicolons to terminate expressions.
do_something
RUBY
expect_correction(<<~RUBY)
m(key1:, key2:)
do_something
RUBY
end
it 'registers an offense for a method call using hash value omission with parentheses when terminated with a semicolon' do
expect_offense(<<~RUBY)
m(key:);
^ Do not use semicolons to terminate expressions.
do_something
RUBY
expect_correction(<<~RUBY)
m(key:)
do_something
RUBY
end
it 'registers an offense for a safe navigation method call using hash value omission without parentheses when terminated with a semicolon' do
expect_offense(<<~RUBY)
obj&.m key:;
^ Do not use semicolons to terminate expressions.
do_something
RUBY
expect_correction(<<~RUBY)
obj&.m(key:)
do_something
RUBY
end
end
context 'with a multi-expression line without a semicolon' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo
bar = baz if qux rescue quux
end
RUBY
end
end
context 'when AllowAsExpressionSeparator is true' do
let(:cop_config) { { 'AllowAsExpressionSeparator' => true } }
it 'accepts several expressions' do
expect_no_offenses('puts "this is a test"; puts "So is this"')
end
it 'accepts one line method with two statements' do
expect_no_offenses('def foo(a) x(1); y(2); z(3); 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/numeric_literals_spec.rb | spec/rubocop/cop/style/numeric_literals_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::NumericLiterals, :config do
let(:cop_config) { { 'MinDigits' => 5 } }
it 'registers an offense for a long undelimited integer' do
expect_offense(<<~RUBY)
a = 12345
^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = 12_345
RUBY
end
it 'registers an offense for a float with a long undelimited integer part' do
expect_offense(<<~RUBY)
a = 123456.789
^^^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = 123_456.789
RUBY
end
it 'accepts integers with less than three places at the end' do
expect_no_offenses(<<~RUBY)
a = 123_456_789_00
b = 819_2
RUBY
end
it 'registers an offense for an integer with misplaced underscore' do
expect_offense(<<~RUBY)
a = 123_456_78_90_00
^^^^^^^^^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
b = 1_8192
^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
expect_correction(<<~RUBY)
a = 123_456_789_000
b = 18_192
RUBY
end
it 'accepts long numbers with underscore' do
expect_no_offenses(<<~RUBY)
a = 123_456
b = 123_456.55
RUBY
end
it 'accepts a short integer without underscore' do
expect_no_offenses('a = 123')
end
it 'does not count a leading minus sign as a digit' do
expect_no_offenses('a = -1230')
end
it 'accepts short numbers without underscore' do
expect_no_offenses(<<~RUBY)
a = 123
b = 123.456
RUBY
end
it 'ignores non-decimal literals' do
expect_no_offenses(<<~RUBY)
a = 0b1010101010101
b = 01717171717171
c = 0xab11111111bb
RUBY
end
it 'handles numeric literal with exponent' do
expect_offense(<<~RUBY)
a = 10e10
b = 3e12345
c = 12.345e3
d = 12345e3
^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = 10e10
b = 3e12345
c = 12.345e3
d = 12_345e3
RUBY
end
it 'autocorrects negative numbers' do
expect_offense(<<~RUBY)
a = -123456
^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = -123_456
RUBY
end
it 'autocorrects negative floating-point numbers' do
expect_offense(<<~RUBY)
a = -123456.78
^^^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = -123_456.78
RUBY
end
it 'autocorrects numbers with spaces between leading minus and numbers' do
expect_offense(<<~RUBY)
a = -
^ Use underscores(_) as thousands separator and separate every 3 digits with them.
12345
RUBY
expect_correction(<<~RUBY)
a = -12_345
RUBY
end
it 'autocorrects numeric literal with exponent and dot' do
expect_offense(<<~RUBY)
a = 12345.6e3
^^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = 12_345.6e3
RUBY
end
it 'autocorrects numeric literal with exponent (large E) and dot' do
expect_offense(<<~RUBY)
a = 12345.6E3
^^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = 12_345.6E3
RUBY
end
context 'strict' do
let(:cop_config) { { 'MinDigits' => 5, 'Strict' => true } }
it 'registers an offense for an integer with misplaced underscore' do
expect_offense(<<~RUBY)
a = 123_456_78_90_00
^^^^^^^^^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
a = 123_456_789_000
RUBY
end
end
context 'for --auto-gen-config' do
let(:enabled) { cop.config_to_allow_offenses['Enabled'] }
let(:min_digits) { cop.config_to_allow_offenses.dig(:exclude_limit, 'MinDigits') }
context 'when the number is only digits' do
it 'detects right value of MinDigits based on the longest number' do
expect_offense(<<~RUBY)
1234567890
^^^^^^^^^^ [...]
12345678901234567890
^^^^^^^^^^^^^^^^^^^^ [...]
123456789012
^^^^^^^^^^^^ [...]
RUBY
expect(min_digits).to eq(21)
expect(enabled).to be_nil
end
it 'sets the right value if one is disabled inline' do
expect_offense(<<~RUBY)
1234567890
^^^^^^^^^^ [...]
12345678901234567890 # rubocop:disable Style/NumericLiterals
123456789012
^^^^^^^^^^^^ [...]
RUBY
expect(min_digits).to eq(13)
expect(enabled).to be_nil
end
end
context 'with separators' do
it 'disables the cop' do
expect_offense(<<~RUBY)
1234_5678_90
^^^^^^^^^^^^ [...]
RUBY
expect(enabled).to be(false)
expect(min_digits).to be_nil
end
it 'does not disable the cop if the line is disabled' do
expect_no_offenses(<<~RUBY)
1234_5678_90 # rubocop:disable Style/NumericLiterals
RUBY
expect(enabled).to be_nil
expect(min_digits).to be_nil
end
end
end
context 'when `3000` is specified for `AllowedNumbers`' do
let(:cop_config) { { 'MinDigits' => 4, 'AllowedNumbers' => [3000] } }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
3000
RUBY
end
it 'registers an offense' do
expect_offense(<<~RUBY)
1234
^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
end
end
context "when `'3000'` is specified for `AllowedNumbers`" do
let(:cop_config) { { 'MinDigits' => 4, 'AllowedNumbers' => ['3000'] } }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
3000
RUBY
end
it 'registers an offense' do
expect_offense(<<~RUBY)
1234
^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
end
end
context 'AllowedPatterns' do
let(:cop_config) { { 'AllowedPatterns' => ['\d{2}_\d{2}_\d{4}'] } }
it 'does not register an offense for numbers that exactly match the pattern' do
expect_no_offenses(<<~RUBY)
12_34_5678
RUBY
end
it 'registers an offense for numbers that do not exactly match the pattern' do
expect_offense(<<~RUBY)
1234_56_78_9012
^^^^^^^^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
end
it 'corrects by inserting underscores every 3 digits' do
expect_offense(<<~RUBY)
12345678
^^^^^^^^ Use underscores(_) as thousands separator and separate every 3 digits with them.
RUBY
expect_correction(<<~RUBY)
12_345_678
RUBY
end
context 'AllowedPatterns with repetition' do
let(:cop_config) { { 'AllowedPatterns' => ['\d{4}(_\d{4})+'] } }
it 'does not register an offense for numbers that match the pattern' do
expect_no_offenses(<<~RUBY)
1234_5678_9012_3456
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/global_vars_spec.rb | spec/rubocop/cop/style/global_vars_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::GlobalVars, :config do
cop_config = { 'AllowedVariables' => ['$allowed'] }
let(:cop_config) { cop_config }
it 'registers an offense for $custom' do
expect_offense(<<~RUBY)
puts $custom
^^^^^^^ Do not introduce global variables.
RUBY
end
it 'allows user permitted variables' do
expect_no_offenses('puts $allowed')
end
described_class::BUILT_IN_VARS.each do |var|
it "does not register an offense for built-in variable #{var}" do
expect_no_offenses(<<~RUBY)
puts #{var}
RUBY
end
end
it 'does not register an offense for backrefs like $1' do
expect_no_offenses('puts $1')
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/regexp_literal_spec.rb | spec/rubocop/cop/style/regexp_literal_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RegexpLiteral, :config do
let(:config) do
supported_styles = { 'SupportedStyles' => %w[slashes percent_r mixed] }
RuboCop::Config.new('Style/PercentLiteralDelimiters' =>
percent_literal_delimiters_config,
'Style/MethodCallWithArgsParentheses' =>
method_call_with_args_parentheses_config,
'Style/RegexpLiteral' =>
cop_config.merge(supported_styles))
end
let(:percent_literal_delimiters_config) { { 'PreferredDelimiters' => { '%r' => '{}' } } }
let(:method_call_with_args_parentheses_config) { { 'EnforcedStyle' => 'require_parentheses' } }
describe 'when regex contains slashes in interpolation' do
let(:cop_config) { { 'EnforcedStyle' => 'slashes' } }
it 'ignores the slashes that do not belong // regex' do
expect_no_offenses('x =~ /\s{#{x[/\s+/].length}}/')
end
end
describe '%r regex with other delimiters than curly braces' do
let(:cop_config) { { 'EnforcedStyle' => 'slashes' } }
it 'registers an offense' do
expect_offense(<<~RUBY)
%r_ls_
^^^^^^ Use `//` around regular expression.
RUBY
end
end
describe 'when PercentLiteralDelimiters is configured with brackets' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_r' } }
let(:percent_literal_delimiters_config) { { 'PreferredDelimiters' => { '%r' => '[]' } } }
it 'respects the configuration when autocorrecting' do
expect_offense(<<~RUBY)
/a/
^^^ Use `%r` around regular expression.
RUBY
expect_correction(<<~RUBY)
%r[a]
RUBY
end
end
describe 'when PercentLiteralDelimiters is configured with slashes' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_r' } }
let(:percent_literal_delimiters_config) { { 'PreferredDelimiters' => { '%r' => '//' } } }
it 'respects the configuration when autocorrecting' do
expect_offense(<<~'RUBY')
/\//
^^^^ Use `%r` around regular expression.
RUBY
expect_correction(<<~'RUBY')
%r/\//
RUBY
end
end
context 'when EnforcedStyle is set to slashes' do
let(:cop_config) { { 'EnforcedStyle' => 'slashes' } }
describe 'a single-line `//` regex without slashes' do
it 'is accepted' do
expect_no_offenses('foo = /a/')
end
end
describe 'a single-line `//` regex with slashes' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = /home\//
^^^^^^^^ Use `%r` around regular expression.
RUBY
expect_correction(<<~RUBY)
foo = %r{home/}
RUBY
end
describe 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'is accepted' do
expect_no_offenses('foo = /home\\//')
end
end
end
describe 'a single-line `//` regex with slashes and interpolation' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = /users\/#{user.id}\/forms/
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `%r` around regular expression.
RUBY
expect_correction(<<~'RUBY')
foo = %r{users/#{user.id}/forms}
RUBY
end
describe 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'is accepted' do
expect_no_offenses('foo = /users\/#{user.id}\/forms/')
end
end
end
describe 'a single-line `%r//` regex with slashes' do
it 'is accepted' do
expect_no_offenses('foo = %r/\\//')
end
context 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'preserves slashes after autocorrection' do
expect_offense(<<~'RUBY')
foo = %r/\//
^^^^^^ Use `//` around regular expression.
RUBY
expect_correction(<<~'RUBY')
foo = /\//
RUBY
end
end
end
describe 'a multi-line `//` regex without slashes' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = /
foo
bar
/x
RUBY
end
end
describe 'a multi-line `//` regex with slashes' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = /
^ Use `%r` around regular expression.
https?:\/\/
example\.com
/x
RUBY
expect_correction(<<~'RUBY')
foo = %r{
https?://
example\.com
}x
RUBY
end
describe 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'is accepted' do
expect_no_offenses(<<~'RUBY')
foo = /
https?:\/\/
example\.com
/x
RUBY
end
end
end
describe 'a single-line %r regex without slashes' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = %r{a}
^^^^^ Use `//` around regular expression.
RUBY
expect_correction(<<~RUBY)
foo = /a/
RUBY
end
end
describe 'a single-line %r regex with slashes' do
it 'is accepted' do
expect_no_offenses('foo = %r{home/}')
end
describe 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = %r{home/}
^^^^^^^^^ Use `//` around regular expression.
RUBY
expect_correction(<<~'RUBY')
foo = /home\//
RUBY
end
end
end
describe 'a multi-line %r regex without slashes' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = %r{
^^^ Use `//` around regular expression.
foo
bar
}x
RUBY
expect_correction(<<~RUBY)
foo = /
foo
bar
/x
RUBY
end
end
describe 'a multi-line %r regex with slashes' do
it 'is accepted' do
expect_no_offenses(<<~'RUBY')
foo = %r{
https?://
example\.com
}x
RUBY
end
describe 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = %r{
^^^ Use `//` around regular expression.
https?://
example\.com
}x
RUBY
expect_correction(<<~'RUBY')
foo = /
https?:\/\/
example\.com
/x
RUBY
end
end
end
end
context 'when EnforcedStyle is set to percent_r' do
let(:cop_config) { { 'EnforcedStyle' => 'percent_r' } }
describe 'a single-line `//` regex without slashes' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = /a/
^^^ Use `%r` around regular expression.
RUBY
expect_correction(<<~RUBY)
foo = %r{a}
RUBY
end
end
describe 'a single-line `//` regex with slashes' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = /home\//
^^^^^^^^ Use `%r` around regular expression.
RUBY
expect_correction(<<~RUBY)
foo = %r{home/}
RUBY
end
end
describe 'a multi-line `//` regex without slashes' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = /
^ Use `%r` around regular expression.
foo
bar
/x
RUBY
expect_correction(<<~RUBY)
foo = %r{
foo
bar
}x
RUBY
end
end
describe 'a multi-line `//` regex with slashes' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = /
^ Use `%r` around regular expression.
https?:\/\/
example\.com
/x
RUBY
expect_correction(<<~'RUBY')
foo = %r{
https?://
example\.com
}x
RUBY
end
end
describe 'a single-line %r regex without slashes' do
it 'is accepted' do
expect_no_offenses('foo = %r{a}')
end
end
describe 'a single-line %r regex with slashes' do
it 'is accepted' do
expect_no_offenses('foo = %r{home/}')
end
end
describe 'a multi-line %r regex without slashes' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = %r{
foo
bar
}x
RUBY
end
end
describe 'a multi-line %r regex with slashes' do
it 'is accepted' do
expect_no_offenses(<<~'RUBY')
foo = %r{
https?://
example\.com
}x
RUBY
end
end
end
context 'when EnforcedStyle is set to mixed' do
let(:cop_config) { { 'EnforcedStyle' => 'mixed' } }
describe 'a single-line `//` regex without slashes' do
it 'is accepted' do
expect_no_offenses('foo = /a/')
end
end
describe 'a single-line `//` regex with slashes' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = /home\//
^^^^^^^^ Use `%r` around regular expression.
RUBY
expect_correction(<<~RUBY)
foo = %r{home/}
RUBY
end
describe 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'is accepted' do
expect_no_offenses('foo = /home\\//')
end
end
end
describe 'a multi-line `//` regex without slashes' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = /
^ Use `%r` around regular expression.
foo
bar
/x
RUBY
expect_correction(<<~RUBY)
foo = %r{
foo
bar
}x
RUBY
end
end
describe 'a multi-line `//` regex with slashes' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
foo = /
^ Use `%r` around regular expression.
https?:\/\/
example\.com
/x
RUBY
expect_correction(<<~'RUBY')
foo = %r{
https?://
example\.com
}x
RUBY
end
end
describe 'a single-line %r regex without slashes' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = %r{a}
^^^^^ Use `//` around regular expression.
RUBY
expect_correction(<<~RUBY)
foo = /a/
RUBY
end
end
describe 'a single-line %r regex with slashes' do
it 'is accepted' do
expect_no_offenses('foo = %r{home/}')
end
describe 'when configured to allow inner slashes' do
before { cop_config['AllowInnerSlashes'] = true }
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = %r{home/}
^^^^^^^^^ Use `//` around regular expression.
RUBY
expect_correction(<<~'RUBY')
foo = /home\//
RUBY
end
end
end
describe 'a multi-line %r regex without slashes' do
it 'is accepted' do
expect_no_offenses(<<~RUBY)
foo = %r{
foo
bar
}x
RUBY
end
end
describe 'a multi-line %r regex with slashes' do
it 'is accepted' do
expect_no_offenses(<<~'RUBY')
foo = %r{
https?://
example\.com
}x
RUBY
end
end
end
context 'when `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` cop' do
let(:method_call_with_args_parentheses_config) { { 'EnforcedStyle' => 'require_parentheses' } }
context 'when using `%r` regexp with `EnforcedStyle: slashes`' do
let(:cop_config) { { 'EnforcedStyle' => 'slashes' } }
it 'registers an offense when used as a method argument' do
expect_offense(<<~RUBY)
do_something %r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
it 'registers an offense when used as a safe navigation method argument' do
expect_offense(<<~RUBY)
foo&.do_something %r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
it 'registers an offense when not used as a method argument' do
expect_offense(<<~RUBY)
%r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
it 'does not register an offense when using a regexp starts with a blank as a method argument' do
expect_no_offenses(<<~RUBY)
do_something %r/ regexp/
RUBY
end
it 'does not register an offense when using a regexp starts with a blank as a safe navigation method argument' do
expect_no_offenses(<<~RUBY)
foo&.do_something %r/ regexp/
RUBY
end
it 'registers an offense when using a regexp starts with a blank' do
expect_offense(<<~RUBY)
%r/ regexp/
^^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
it 'does not register an offense when using a regexp starts with equal as a method argument' do
expect_no_offenses(<<~RUBY)
do_something %r/=regexp/
RUBY
end
end
context 'when using `%r` regexp with `EnforcedStyle: mixed`' do
let(:cop_config) { { 'EnforcedStyle' => 'mixed' } }
it 'registers an offense when used as a method argument' do
expect_offense(<<~RUBY)
do_something %r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
it 'registers an offense when used as a safe navigation method argument' do
expect_offense(<<~RUBY)
foo&.do_something %r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
it 'registers an offense when not used as a method argument' do
expect_offense(<<~RUBY)
%r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
it 'does not register an offense when using a regexp starts with a blank as a method argument' do
expect_no_offenses(<<~RUBY)
do_something %r/ regexp/
RUBY
end
it 'does not register an offense when using a regexp starts with a blank as a safe navigation method argument' do
expect_no_offenses(<<~RUBY)
foo&.do_something %r/ regexp/
RUBY
end
it 'registers an offense when using a regexp starts with a blank' do
expect_offense(<<~RUBY)
%r/ regexp/
^^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
end
end
context 'when `EnforcedStyle: omit_parentheses` of `Style/MethodCallWithArgsParentheses` cop' do
let(:method_call_with_args_parentheses_config) { { 'EnforcedStyle' => 'omit_parentheses' } }
context 'when using `%r` regexp with `EnforcedStyle: slashes`' do
let(:cop_config) { { 'EnforcedStyle' => 'slashes' } }
it 'does not register an offense when used as a method argument' do
expect_no_offenses(<<~RUBY)
do_something %r/regexp/
RUBY
end
it 'does not register an offense when used as a safe navigation method argument' do
expect_no_offenses(<<~RUBY)
foo&.do_something %r/regexp/
RUBY
end
it 'registers an offense when not used as a method argument' do
expect_offense(<<~RUBY)
%r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
RUBY
end
end
context 'when using `%r` regexp with `EnforcedStyle: mixed`' do
let(:cop_config) { { 'EnforcedStyle' => 'mixed' } }
it 'does not register an offense when used as a method argument' do
expect_no_offenses(<<~RUBY)
do_something %r/regexp/
RUBY
end
it 'does not register an offense when used as a safe navigation method argument' do
expect_no_offenses(<<~RUBY)
foo&.do_something %r/regexp/
RUBY
end
it 'registers an offense when not used as a method argument' do
expect_offense(<<~RUBY)
%r/regexp/
^^^^^^^^^^ Use `//` around regular expression.
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/empty_literal_spec.rb | spec/rubocop/cop/style/empty_literal_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyLiteral, :config do
describe 'Empty Array' do
shared_examples 'registers_and_corrects' do |initializer:|
it "registers an offense for #{initializer}" do
expect_offense(<<~RUBY)
test = #{initializer}
#{'^' * initializer.length} Use array literal `[]` instead of `#{initializer}`.
RUBY
expect_correction(<<~RUBY)
test = []
RUBY
end
end
context 'initializer resulting in an empty array literal' do
it_behaves_like 'registers_and_corrects', initializer: 'Array.new()'
it_behaves_like 'registers_and_corrects', initializer: 'Array.new'
it_behaves_like 'registers_and_corrects', initializer: '::Array.new()'
it_behaves_like 'registers_and_corrects', initializer: 'Array.new([])'
it_behaves_like 'registers_and_corrects', initializer: 'Array[]'
it_behaves_like 'registers_and_corrects', initializer: 'Array([])'
end
it 'does not register an offense for Array.new(3)' do
expect_no_offenses('test = Array.new(3)')
end
it 'autocorrects Array.new in block in block' do
expect_offense(<<~RUBY)
puts { Array.new }
^^^^^^^^^ Use array literal `[]` instead of `Array.new`.
RUBY
expect_correction(<<~RUBY)
puts { [] }
RUBY
end
it 'does not register an offense Array.new with block' do
expect_no_offenses('test = Array.new { 1 }')
end
it 'does not register an offense for ::Array.new with block' do
expect_no_offenses('test = ::Array.new { 1 }')
end
it 'does not register Array.new with block in other block' do
expect_no_offenses('puts { Array.new { 1 } }')
end
it 'does not register an offense for Array[3]' do
expect_no_offenses('Array[3]')
end
it 'does not register an offense for Array [3]' do
expect_no_offenses('Array [3]')
end
end
describe 'Empty Hash' do
shared_examples 'registers_and_corrects' do |initializer:|
it "registers an offense for #{initializer}" do
expect_offense(<<~RUBY)
test = #{initializer}
#{'^' * initializer.length} Use hash literal `{}` instead of `#{initializer}`.
RUBY
expect_correction(<<~RUBY)
test = {}
RUBY
end
end
context 'initializer resulting in an empty hash literal' do
it_behaves_like 'registers_and_corrects', initializer: 'Hash.new()'
it_behaves_like 'registers_and_corrects', initializer: 'Hash.new'
it_behaves_like 'registers_and_corrects', initializer: '::Hash.new()'
it_behaves_like 'registers_and_corrects', initializer: 'Hash[]'
it_behaves_like 'registers_and_corrects', initializer: 'Hash([])'
end
it 'does not register an offense for Hash[3,4]' do
expect_no_offenses('Hash[3,4]')
end
it 'does not register an offense for Hash [3,4]' do
expect_no_offenses('Hash [3,4]')
end
it 'does not register an offense for Hash.new(3)' do
expect_no_offenses('test = Hash.new(3)')
end
it 'does not register an offense for ::Hash.new(3)' do
expect_no_offenses('test = ::Hash.new(3)')
end
it 'does not register an offense for Hash.new { block }' do
expect_no_offenses('test = Hash.new { block }')
end
it 'does not register an offense for ::Hash.new { block }' do
expect_no_offenses('test = ::Hash.new { block }')
end
it 'does not register an offense for Hash.new([])' do
expect_no_offenses('Hash.new([])')
end
context 'Ruby 2.7', :ruby27 do
it 'does not register an offense for Hash.new { _1[_2] = [] }' do
expect_no_offenses('test = Hash.new { _1[_2] = [] }')
end
it 'does not register an offense for ::Hash.new { _1[_2] = [] }' do
expect_no_offenses('test = ::Hash.new { _1[_2] = [] }')
end
end
it 'autocorrects Hash.new in block' do
expect_offense(<<~RUBY)
puts { Hash.new }
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
RUBY
expect_correction(<<~RUBY)
puts { {} }
RUBY
end
it 'autocorrects Hash.new to {} in various contexts' do
expect_offense(<<~RUBY)
test = Hash.new
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
Hash.new.merge("a" => 3)
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
yadayada.map { a }.reduce(Hash.new, :merge)
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
RUBY
expect_correction(<<~RUBY)
test = {}
{}.merge("a" => 3)
yadayada.map { a }.reduce({}, :merge)
RUBY
end
it 'autocorrects Hash.new to {} as the only parameter to a method' do
expect_offense(<<~RUBY)
yadayada.map { a }.reduce Hash.new
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
RUBY
expect_correction(<<~RUBY)
yadayada.map { a }.reduce({})
RUBY
end
it 'autocorrects Hash.new to {} as the first parameter to a method' do
expect_offense(<<~RUBY)
yadayada.map { a }.reduce Hash.new, :merge
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
RUBY
expect_correction(<<~RUBY)
yadayada.map { a }.reduce({}, :merge)
RUBY
end
it 'autocorrects Hash.new to {} and wraps it in parentheses ' \
'when it is the only argument to super' do
expect_offense(<<~RUBY)
def foo
super Hash.new
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
end
RUBY
expect_correction(<<~RUBY)
def foo
super({})
end
RUBY
end
it 'autocorrects Hash.new to {} and wraps all arguments in ' \
'parentheses when it is the first argument to super' do
expect_offense(<<~RUBY)
def foo
super Hash.new, something
^^^^^^^^ Use hash literal `{}` instead of `Hash.new`.
end
RUBY
expect_correction(<<~RUBY)
def foo
super({}, something)
end
RUBY
end
end
describe 'Empty String', :config do
let(:other_cops) { { 'Style/FrozenStringLiteralComment' => { 'Enabled' => false } } }
it 'registers an offense for String.new()' do
expect_offense(<<~RUBY)
test = String.new()
^^^^^^^^^^^^ Use string literal `''` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
test = ''
RUBY
end
it 'registers an offense for String.new' do
expect_offense(<<~RUBY)
test = String.new
^^^^^^^^^^ Use string literal `''` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
test = ''
RUBY
end
it 'registers an offense for ::String.new' do
expect_offense(<<~RUBY)
test = ::String.new
^^^^^^^^^^^^ Use string literal `''` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
test = ''
RUBY
end
it 'does not register an offense for String.new("top")' do
expect_no_offenses('test = String.new("top")')
end
it 'does not register an offense for ::String.new("top")' do
expect_no_offenses('test = ::String.new("top")')
end
context 'when double-quoted string literals are preferred' do
let(:other_cops) do
super().merge('Style/StringLiterals' => { 'EnforcedStyle' => 'double_quotes' })
end
it 'registers an offense for String.new' do
expect_offense(<<~RUBY)
test = String.new
^^^^^^^^^^ Use string literal `""` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
test = ""
RUBY
end
it 'registers an offense for ::String.new' do
expect_offense(<<~RUBY)
test = ::String.new
^^^^^^^^^^^^ Use string literal `""` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
test = ""
RUBY
end
end
context 'when frozen string literals is enabled', :ruby23 do
it 'does not register an offense for String.new' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
test = String.new
RUBY
end
end
context 'when Style/FrozenStringLiteralComment is enabled' do
let(:other_cops) { { 'Style/FrozenStringLiteralComment' => { 'Enabled' => true } } }
context 'and there is no magic comment' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
test = String.new
RUBY
end
end
context 'and there is a frozen_string_literal: false comment' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
# frozen_string_literal: false
test = String.new
^^^^^^^^^^ Use string literal `''` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: false
test = ''
RUBY
end
end
end
context 'when `AllCops/StringLiteralsFrozenByDefault: true`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'StringLiteralsFrozenByDefault' => true })
end
context 'when the frozen string literal comment is missing' do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
test = String.new
RUBY
end
end
context 'when the frozen string literal comment is true' do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
test = String.new
RUBY
end
end
context 'when the frozen string literal comment is false' do
it 'registers an offense' do
expect_offense(<<~RUBY)
# frozen_string_literal: false
test = String.new
^^^^^^^^^^ Use string literal `''` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: false
test = ''
RUBY
end
end
end
context 'when `AllCops/StringLiteralsFrozenByDefault: false`' do
let(:config) do
RuboCop::Config.new('AllCops' => { 'StringLiteralsFrozenByDefault' => false })
end
context 'when the frozen string literal comment is missing' do
it 'registers an offense' do
expect_offense(<<~RUBY)
test = String.new
^^^^^^^^^^ Use string literal `''` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
test = ''
RUBY
end
end
context 'when the frozen string literal comment is true' do
it 'registers no offense' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
test = String.new
RUBY
end
end
context 'when the frozen string literal comment is false' do
it 'registers an offense' do
expect_offense(<<~RUBY)
# frozen_string_literal: false
test = String.new
^^^^^^^^^^ Use string literal `''` instead of `String.new`.
RUBY
expect_correction(<<~RUBY)
# frozen_string_literal: false
test = ''
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/inverse_methods_spec.rb | spec/rubocop/cop/style/inverse_methods_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::InverseMethods, :config do
let(:config) do
RuboCop::Config.new(
'Style/InverseMethods' => {
'InverseMethods' => {
any?: :none?,
even?: :odd?,
present?: :blank?,
include?: :exclude?,
:== => :!=,
:=~ => :!~,
:< => :>=,
:> => :<=
},
'InverseBlocks' => {
select: :reject,
select!: :reject!
}
}
)
end
it 'registers an offense for calling !.none? with a symbol proc' do
expect_offense(<<~RUBY)
!foo.none?(&:even?)
^^^^^^^^^^^^^^^^^^^ Use `any?` instead of inverting `none?`.
RUBY
expect_correction(<<~RUBY)
foo.any?(&:even?)
RUBY
end
it 'does not register an offense for safe navigation calling !.none? with a symbol proc' do
expect_no_offenses(<<~RUBY)
!foo&.none?(&:even?)
RUBY
end
it 'registers an offense for calling !.none? with a block' do
expect_offense(<<~RUBY)
!foo.none? { |f| f.even? }
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead of inverting `none?`.
RUBY
expect_correction(<<~RUBY)
foo.any? { |f| f.even? }
RUBY
end
it 'does not register an offense for safe navigation calling !.none? with a block' do
expect_no_offenses(<<~RUBY)
!foo&.none? { |f| f.even? }
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for calling !.none? with a numblock' do
expect_offense(<<~RUBY)
!foo.none? { _1.even? }
^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead of inverting `none?`.
RUBY
expect_correction(<<~RUBY)
foo.any? { _1.even? }
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for calling !.none? with an itblock' do
expect_offense(<<~RUBY)
!foo.none? { it.even? }
^^^^^^^^^^^^^^^^^^^^^^^ Use `any?` instead of inverting `none?`.
RUBY
expect_correction(<<~RUBY)
foo.any? { it.even? }
RUBY
end
end
it 'registers an offense for calling !.any? inside parens' do
expect_offense(<<~RUBY)
!(foo.any? &:working?)
^^^^^^^^^^^^^^^^^^^^^^ Use `none?` instead of inverting `any?`.
RUBY
expect_correction(<<~RUBY)
foo.none? &:working?
RUBY
end
it 'does not register an offense for safe navigation calling !.any? inside parens' do
expect_no_offenses(<<~RUBY)
!(foo&.any? &:working?)
RUBY
end
it 'allows a method call without a not' do
expect_no_offenses('foo.none?')
end
it 'allows an inverse method when double negation is used' do
expect_no_offenses('!!(string =~ /^\w+$/)')
end
it 'allows an inverse method with a block when double negation is used' do
expect_no_offenses('!!foo.reject { |e| !e }')
end
it 'allows an inverse method in a block with next' do
expect_no_offenses(<<~RUBY)
class TestClass
def test_method
[1, 2, 3, 4].select do |number|
next if number == 4
number != 2
end
end
end
RUBY
end
shared_examples 'all variable types' do |variable|
it "registers an offense for calling !#{variable}.none?" do
expect_offense(<<~RUBY, variable: variable)
!%{variable}.none?
^^{variable}^^^^^^ Use `any?` instead of inverting `none?`.
RUBY
expect_correction(<<~RUBY)
#{variable}.any?
RUBY
end
it "registers an offense for calling not #{variable}.none?" do
expect_offense(<<~RUBY, variable: variable)
not %{variable}.none?
^^^^^{variable}^^^^^^ Use `any?` instead of inverting `none?`.
RUBY
expect_correction(<<~RUBY)
#{variable}.any?
RUBY
end
end
it_behaves_like 'all variable types', 'foo'
it_behaves_like 'all variable types', '$foo'
it_behaves_like 'all variable types', '@foo'
it_behaves_like 'all variable types', '@@foo'
it_behaves_like 'all variable types', 'FOO'
it_behaves_like 'all variable types', 'FOO::BAR'
it_behaves_like 'all variable types', 'foo["bar"]'
it_behaves_like 'all variable types', 'foo.bar'
{ any?: :none?,
even?: :odd?,
present?: :blank?,
include?: :exclude?,
none?: :any?,
odd?: :even?,
blank?: :present?,
exclude?: :include? }.each do |method, inverse|
it "registers an offense for !foo.#{method}" do
expect_offense(<<~RUBY, method: method)
!foo.%{method}
^^^^^^{method} Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo.#{inverse}
RUBY
end
end
{ :== => :!=,
:!= => :==,
:=~ => :!~,
:!~ => :=~,
:< => :>=,
:> => :<= }.each do |method, inverse|
it "registers an offense for !(foo #{method} bar)" do
expect_offense(<<~RUBY, method: method)
!(foo %{method} bar)
^^^^^^^{method}^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo #{inverse} bar
RUBY
end
it "registers an offense for not (foo #{method} bar)" do
expect_offense(<<~RUBY, method: method)
not (foo %{method} bar)
^^^^^^^^^^{method}^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo #{inverse} bar
RUBY
end
end
it 'allows using `any?` method with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.any?(&:odd)
RUBY
end
it 'allows using `none?` method with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.none?(&:odd)
RUBY
end
it 'allows comparing for relational comparison operator (`<`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.<(0)
RUBY
end
it 'allows comparing for relational comparison operator (`<=`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.<=(0)
RUBY
end
it 'allows comparing for relational comparison operator (`>`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.>(0)
RUBY
end
it 'allows comparing for relational comparison operator (`>=`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.>=(0)
RUBY
end
it 'allows comparing camel case constants on the right' do
expect_no_offenses(<<~RUBY)
klass = self.class
!(klass < BaseClass)
RUBY
end
it 'allows comparing camel case constants on the left' do
expect_no_offenses(<<~RUBY)
klass = self.class
!(BaseClass < klass)
RUBY
end
it 'registers an offense for comparing snake case constants on the right' do
expect_offense(<<~RUBY)
klass = self.class
!(klass < FOO_BAR)
^^^^^^^^^^^^^^^^^^ Use `>=` instead of inverting `<`.
RUBY
expect_correction(<<~RUBY)
klass = self.class
klass >= FOO_BAR
RUBY
end
it 'registers an offense for comparing snake case constants on the left' do
expect_offense(<<~RUBY)
klass = self.class
!(FOO_BAR < klass)
^^^^^^^^^^^^^^^^^^ Use `>=` instead of inverting `<`.
RUBY
expect_correction(<<~RUBY)
klass = self.class
FOO_BAR >= klass
RUBY
end
context 'inverse blocks' do
{ select: :reject,
reject: :select,
select!: :reject!,
reject!: :select! }.each do |method, inverse|
it "registers an offense for foo.#{method} { |e| !e }" do
expect_offense(<<~RUBY, method: method)
foo.%{method} { |e| !e }
^^^^^{method}^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} { |e| e }
RUBY
end
it "registers an offense for foo&.#{method} { |e| !e }" do
expect_offense(<<~RUBY, method: method)
foo&.%{method} { |e| !e }
^^^^^^{method}^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo&.#{inverse} { |e| e }
RUBY
end
it 'registers an offense for a multiline method call where the last method is inverted' do
expect_offense(<<~RUBY, method: method)
foo.%{method} do |e|
^^^^^{method}^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
something
!e.bar
end
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} do |e|
something
e.bar
end
RUBY
end
it 'registers an offense for a multiline safe navigation method call where the last method is inverted' do
expect_offense(<<~RUBY, method: method)
foo&.%{method} do |e|
^^^^^^{method}^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
something
e&.bar&.!
end
RUBY
expect_correction(<<~RUBY)
foo&.#{inverse} do |e|
something
e&.bar
end
RUBY
end
it 'registers an offense for an inverted equality block' do
expect_offense(<<~RUBY, method: method)
foo.%{method} { |e| e != 2 }
^^^^^{method}^^^^^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} { |e| e == 2 }
RUBY
end
it 'registers an offense for a multiline inverted equality block' do
expect_offense(<<~RUBY, method: method)
foo.%{method} do |e|
^^^^^{method}^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
something
something_else
e != 2
end
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} do |e|
something
something_else
e == 2
end
RUBY
end
it 'registers a single offense for nested inverse method calls' do
expect_offense(<<~RUBY, method: method)
y.%{method} { |key, _value| !(key =~ /c\\d/) }
^^^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
y.#{inverse} { |key, _value| (key =~ /c\\d/) }
RUBY
end
it 'corrects an inverted method call' do
expect_offense(<<~RUBY, method: method)
foo.%{method} { |e| !e.bar? }
^^^^^{method}^^^^^^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} { |e| e.bar? }
RUBY
end
it 'corrects an inverted method call when using `BasicObject#!`' do
expect_offense(<<~RUBY, method: method)
foo.%{method} { |e| e.bar?.! }
^^^^^{method}^^^^^^^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} { |e| e.bar? }
RUBY
end
it 'corrects an inverted safe navigation method call when using `BasicObject#!`' do
expect_offense(<<~RUBY, method: method)
foo&.%{method} { |e| e&.bar?&.! }
^^^^^^{method}^^^^^^^^^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo&.#{inverse} { |e| e&.bar? }
RUBY
end
it 'corrects an inverted method call when using `BasicObject#!` with spaces before the method call' do
expect_offense(<<~RUBY, method: method)
foo.%{method} { |e| e.bar?. ! }
^^^^^{method}^^^^^^^^^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} { |e| e.bar? }
RUBY
end
it 'corrects a complex inverted method call' do
expect_offense(<<~RUBY, method: method)
puts 1 if !foo.%{method} { |e| !e.bar? }
^^^^^{method}^^^^^^^^^^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
RUBY
expect_correction(<<~RUBY)
puts 1 if !foo.#{inverse} { |e| e.bar? }
RUBY
end
it 'corrects an inverted do end method call' do
expect_offense(<<~RUBY, method: method)
foo.%{method} do |e|
^^^^^{method}^^^^^^^ Use `#{inverse}` instead of inverting `#{method}`.
!e.bar
end
RUBY
expect_correction(<<~RUBY)
foo.#{inverse} do |e|
e.bar
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/class_vars_spec.rb | spec/rubocop/cop/style/class_vars_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ClassVars, :config do
it 'registers an offense for class variable declaration' do
expect_offense(<<~RUBY)
class TestClass; @@test = 10; end
^^^^^^ Replace class var @@test with a class instance var.
RUBY
end
it 'registers an offense for class variable set in class' do
expect_offense(<<~RUBY)
class TestClass
class_variable_set(:@@test, 2)
^^^^^^^ Replace class var :@@test with a class instance var.
end
RUBY
end
it 'registers an offense for class variable set on class receiver' do
expect_offense(<<~RUBY)
class TestClass; end
TestClass.class_variable_set(:@@test, 42)
^^^^^^^ Replace class var :@@test with a class instance var.
RUBY
end
it 'does not register an offense for class variable usage' do
expect_no_offenses('@@test.test(20)')
end
it 'registers no offense for class variable set without arguments' do
expect_no_offenses('class_variable_set')
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/array_intersect_with_single_element_spec.rb | spec/rubocop/cop/style/array_intersect_with_single_element_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ArrayIntersectWithSingleElement, :config do
context 'with `include?(element)`' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
array.include?(element)
RUBY
end
end
context 'with `intersect?([element])`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
array.intersect?([element])
^^^^^^^^^^^^^^^^^^^^^ Use `include?(element)` instead of `intersect?([element])`.
RUBY
expect_correction(<<~RUBY)
array.include?(element)
RUBY
end
end
context 'with `intersect?(%i[element])`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
array.intersect?(%i[element])
^^^^^^^^^^^^^^^^^^^^^^^ Use `include?(element)` instead of `intersect?([element])`.
RUBY
expect_correction(<<~RUBY)
array.include?(:element)
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trailing_body_on_module_spec.rb | spec/rubocop/cop/style/trailing_body_on_module_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::TrailingBodyOnModule, :config do
let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 2 }) }
it 'registers an offense when body trails after module definition' do
expect_offense(<<~RUBY)
module Foo body
^^^^ Place the first line of module body on its own line.
end
module Bar extend self
^^^^^^^^^^^ Place the first line of module body on its own line.
end
module Bar; def bar; end
^^^^^^^^^^^^ Place the first line of module body on its own line.
end
module Bar def bar; end
^^^^^^^^^^^^ Place the first line of module body on its own line.
end
RUBY
expect_correction(<<~RUBY)
module Foo#{trailing_whitespace}
body
end
module Bar#{trailing_whitespace}
extend self
end
module Bar#{trailing_whitespace}
def bar; end
end
module Bar#{trailing_whitespace}
def bar; end
end
RUBY
end
it 'registers an offense with multi-line module' do
expect_offense(<<~RUBY)
module Foo body
^^^^ Place the first line of module body on its own line.
def bar
qux
end
end
RUBY
expect_correction(<<~RUBY)
module Foo#{trailing_whitespace}
body
def bar
qux
end
end
RUBY
end
it 'registers an offense when module definition uses semicolon' do
expect_offense(<<~RUBY)
module Foo; do_stuff
^^^^^^^^ Place the first line of module body on its own line.
end
RUBY
expect_correction(<<~RUBY)
module Foo#{trailing_whitespace}
do_stuff
end
RUBY
end
it 'accepts regular module' do
expect_no_offenses(<<~RUBY)
module Foo
def no_op; end
end
RUBY
end
it 'autocorrects with comment after body' do
expect_offense(<<~RUBY)
module BarQux; foo # comment
^^^ Place the first line of module body on its own line.
end
RUBY
expect_correction(<<~RUBY)
# comment
module BarQux#{trailing_whitespace}
foo#{trailing_whitespace}
end
RUBY
end
it 'autocorrects when there are multiple semicolons' do
expect_offense(<<~RUBY)
module Bar; def bar; end
^^^^^^^^^^^^ Place the first line of module body on its own line.
end
RUBY
expect_correction(<<~RUBY)
module Bar#{trailing_whitespace}
def bar; end
end
RUBY
end
context 'when module is not on first line of processed_source' do
it 'autocorrects offense' do
expect_offense(<<~RUBY)
module Foo; body#{trailing_whitespace}
^^^^ Place the first line of module body on its own line.
end
RUBY
expect_correction(<<~RUBY)
module 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/struct_inheritance_spec.rb | spec/rubocop/cop/style/struct_inheritance_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::StructInheritance, :config do
it 'registers an offense when extending instance of Struct' do
expect_offense(<<~RUBY)
class Person < Struct.new(:first_name, :last_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
def foo; end
end
RUBY
expect_correction(<<~RUBY)
Person = Struct.new(:first_name, :last_name) do
def foo; end
end
RUBY
end
it 'registers an offense when extending instance of ::Struct' do
expect_offense(<<~RUBY)
class Person < ::Struct.new(:first_name, :last_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
def foo; end
end
RUBY
expect_correction(<<~RUBY)
Person = ::Struct.new(:first_name, :last_name) do
def foo; end
end
RUBY
end
it 'registers an offense when extending instance of Struct with do ... end' do
expect_offense(<<~RUBY)
class Person < Struct.new(:first_name, :last_name) do end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
end
RUBY
expect_correction(<<~RUBY)
Person = Struct.new(:first_name, :last_name) do
end
RUBY
end
it 'registers an offense when extending instance of Struct without `do` ... `end` and class body is empty' do
expect_offense(<<~RUBY)
class Person < Struct.new(:first_name, :last_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
end
RUBY
expect_correction(<<~RUBY)
Person = Struct.new(:first_name, :last_name)
RUBY
end
it 'registers an offense when extending instance of Struct without `do` ... `end` and class body is empty and single line definition' do
expect_offense(<<~RUBY)
class Person < Struct.new(:first_name, :last_name); end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
RUBY
expect_correction(<<~RUBY)
Person = Struct.new(:first_name, :last_name)
RUBY
end
it 'registers an offense when extending instance of ::Struct with do ... end' do
expect_offense(<<~RUBY)
class Person < ::Struct.new(:first_name, :last_name) do end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
end
RUBY
expect_correction(<<~RUBY)
Person = ::Struct.new(:first_name, :last_name) do
end
RUBY
end
it 'registers an offense when extending instance of `Struct` when there is a comment ' \
'before class declaration' do
expect_offense(<<~RUBY)
# comment
class Person < Struct.new(:first_name, :last_name) do end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't extend an instance initialized by `Struct.new`. Use a block to customize the struct.
end
RUBY
expect_correction(<<~RUBY)
# comment
Person = Struct.new(:first_name, :last_name) do
end
RUBY
end
it 'accepts plain class' do
expect_no_offenses(<<~RUBY)
class Person
end
RUBY
end
it 'accepts extending DelegateClass' do
expect_no_offenses(<<~RUBY)
class Person < DelegateClass(Animal)
end
RUBY
end
it 'accepts assignment to Struct.new' do
expect_no_offenses('Person = Struct.new(:first_name, :last_name)')
end
it 'accepts assignment to ::Struct.new' do
expect_no_offenses('Person = ::Struct.new(:first_name, :last_name)')
end
it 'accepts assignment to block form of Struct.new' do
expect_no_offenses(<<~RUBY)
Person = Struct.new(:first_name, :last_name) do
def age
42
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/rescue_standard_error_spec.rb | spec/rubocop/cop/style/rescue_standard_error_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RescueStandardError, :config do
context 'implicit' do
let(:cop_config) do
{ 'EnforcedStyle' => 'implicit',
'SupportedStyles' => %w[implicit explicit] }
end
context 'when rescuing in a begin block' do
it 'accepts rescuing no error class' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue
bar
end
RUBY
end
it 'accepts rescuing no error class, assigned to a variable' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue => e
bar
end
RUBY
end
it 'accepts rescuing a single error class other than StandardError' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue BarError
bar
end
RUBY
end
it 'accepts rescuing a single error class other than StandardError, assigned to a variable' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue BarError => e
bar
end
RUBY
end
context 'when rescuing StandardError by itself' do
it 'registers an offense' do
expect_offense(<<~RUBY)
begin
foo
rescue StandardError
^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself.
bar
end
RUBY
expect_correction(<<~RUBY)
begin
foo
rescue
bar
end
RUBY
end
context 'with ::StandardError' do
it 'registers an offense' do
expect_offense(<<~RUBY)
begin
foo
rescue ::StandardError
^^^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself.
bar
end
RUBY
expect_correction(<<~RUBY)
begin
foo
rescue
bar
end
RUBY
end
end
context 'when the error is assigned to a variable' do
it 'registers an offense' do
expect_offense(<<~RUBY)
begin
foo
rescue StandardError => e
^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself.
bar
end
RUBY
expect_correction(<<~RUBY)
begin
foo
rescue => e
bar
end
RUBY
end
context 'with ::StandardError' do
it 'registers an offense' do
expect_offense(<<~RUBY)
begin
foo
rescue ::StandardError => e
^^^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself.
bar
end
RUBY
end
end
end
end
it 'accepts rescuing StandardError with other errors' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue StandardError, BarError
bar
rescue BazError, StandardError
baz
end
RUBY
end
it 'accepts rescuing ::StandardError with other errors' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue ::StandardError, BarError
bar
rescue ::BazError, ::StandardError
baz
end
RUBY
end
it 'accepts rescuing StandardError with other errors, assigned to a variable' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue StandardError, BarError => e
bar
rescue BazError, StandardError => e
baz
end
RUBY
end
end
context 'when rescuing in a method definition' do
it 'accepts rescuing no error class' do
expect_no_offenses(<<~RUBY)
def baz
foo
rescue
bar
end
RUBY
end
it 'accepts rescuing no error class, assigned to a variable' do
expect_no_offenses(<<~RUBY)
def baz
foo
rescue => e
bar
end
RUBY
end
it 'accepts rescuing a single error other than StandardError' do
expect_no_offenses(<<~RUBY)
def baz
foo
rescue BarError
bar
end
RUBY
end
it 'accepts rescuing a single error other than StandardError, assigned to a variable' do
expect_no_offenses(<<~RUBY)
def baz
foo
rescue BarError => e
bar
end
RUBY
end
context 'when rescuing StandardError by itself' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def foobar
foo
rescue StandardError
^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself.
bar
end
RUBY
expect_correction(<<~RUBY)
def foobar
foo
rescue
bar
end
RUBY
end
context 'when the error is assigned to a variable' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def foobar
foo
rescue StandardError => e
^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself.
bar
end
RUBY
expect_correction(<<~RUBY)
def foobar
foo
rescue => e
bar
end
RUBY
end
end
end
it 'accepts rescuing StandardError with other errors' do
expect_no_offenses(<<~RUBY)
def foobar
foo
rescue StandardError, BarError
bar
rescue BazError, StandardError
baz
end
RUBY
end
it 'accepts rescuing StandardError with other errors, assigned to a variable' do
expect_no_offenses(<<~RUBY)
def foobar
foo
rescue StandardError, BarError => e
bar
rescue BazError, StandardError => e
baz
end
RUBY
end
end
it 'accepts rescue modifier' do
expect_no_offenses(<<~RUBY)
foo rescue 42
RUBY
end
end
context 'explicit' do
let(:cop_config) do
{ 'EnforcedStyle' => 'explicit',
'SupportedStyles' => %w[implicit explicit] }
end
context 'when rescuing in a begin block' do
context 'when calling rescue without an error class' do
it 'registers an offense' do
expect_offense(<<~RUBY)
begin
foo
rescue
^^^^^^ Avoid rescuing without specifying an error class.
bar
end
RUBY
expect_correction(<<~RUBY)
begin
foo
rescue StandardError
bar
end
RUBY
end
context 'when the error is assigned to a variable' do
it 'registers an offense' do
expect_offense(<<~RUBY)
begin
foo
rescue => e
^^^^^^ Avoid rescuing without specifying an error class.
bar
end
RUBY
expect_correction(<<~RUBY)
begin
foo
rescue StandardError => e
bar
end
RUBY
end
end
end
it 'accepts rescuing a single error other than StandardError' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue BarError
bar
end
RUBY
end
it 'accepts rescuing a single error other than StandardError assigned to a variable' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue BarError => e
bar
end
RUBY
end
it 'accepts rescuing StandardError by itself' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue StandardError
bar
end
RUBY
end
it 'accepts rescuing StandardError by itself, assigned to a variable' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue StandardError => e
bar
end
RUBY
end
it 'accepts rescuing StandardError with other errors' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue StandardError, BarError
bar
rescue BazError, StandardError
baz
end
RUBY
end
it 'accepts rescuing StandardError with other errors, assigned to a variable' do
expect_no_offenses(<<~RUBY)
begin
foo
rescue StandardError, BarError => e
bar
rescue BazError, StandardError => e
baz
end
RUBY
end
end
context 'when rescuing in a method definition' do
context 'when rescue is called without an error class' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def baz
foo
rescue
^^^^^^ Avoid rescuing without specifying an error class.
bar
end
RUBY
expect_correction(<<~RUBY)
def baz
foo
rescue StandardError
bar
end
RUBY
end
end
context 'when the error is assigned to a variable' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def baz
foo
rescue => e
^^^^^^ Avoid rescuing without specifying an error class.
bar
end
RUBY
expect_correction(<<~RUBY)
def baz
foo
rescue StandardError => e
bar
end
RUBY
end
end
it 'accepts rescuing a single error other than StandardError' do
expect_no_offenses(<<~RUBY)
def baz
foo
rescue BarError
bar
end
RUBY
end
it 'accepts rescuing a single error other than StandardError, assigned to a variable' do
expect_no_offenses(<<~RUBY)
def baz
foo
rescue BarError => e
bar
end
RUBY
end
it 'accepts rescuing StandardError by itself' do
expect_no_offenses(<<~RUBY)
def foobar
foo
rescue StandardError
bar
end
RUBY
end
it 'accepts rescuing StandardError by itself, assigned to a variable' do
expect_no_offenses(<<~RUBY)
def foobar
foo
rescue StandardError => e
bar
end
RUBY
end
it 'accepts rescuing StandardError with other errors' do
expect_no_offenses(<<~RUBY)
def foobar
foo
rescue StandardError, BarError
bar
rescue BazError, StandardError
baz
end
RUBY
end
it 'accepts rescuing StandardError with other errors, assigned to a variable' do
expect_no_offenses(<<~RUBY)
def foobar
foo
rescue StandardError, BarError => e
bar
rescue BazError, StandardError => e
baz
end
RUBY
end
end
it 'accepts rescue modifier' do
expect_no_offenses(<<~RUBY)
foo rescue 42
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_block_parameter_spec.rb | spec/rubocop/cop/style/empty_block_parameter_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EmptyBlockParameter, :config do
it 'registers an offense for an empty block parameter with do-end style' do
expect_offense(<<~RUBY)
a do ||
^^ Omit pipes for the empty block parameters.
end
RUBY
expect_correction(<<~RUBY)
a do
end
RUBY
end
it 'registers an offense for an empty block parameter with {} style' do
expect_offense(<<~RUBY)
a { || do_something }
^^ Omit pipes for the empty block parameters.
RUBY
expect_correction(<<~RUBY)
a { do_something }
RUBY
end
it 'registers an offense for an empty block parameter with super' do
expect_offense(<<~RUBY)
def foo
super { || do_something }
^^ Omit pipes for the empty block parameters.
end
RUBY
expect_correction(<<~RUBY)
def foo
super { do_something }
end
RUBY
end
it 'registers an offense for an empty block parameter with lambda' do
expect_offense(<<~RUBY)
lambda { || do_something }
^^ Omit pipes for the empty block parameters.
RUBY
expect_correction(<<~RUBY)
lambda { do_something }
RUBY
end
it 'accepts a block that is do-end style without parameter' do
expect_no_offenses(<<~RUBY)
a do
end
RUBY
end
it 'accepts a block that is {} style without parameter' do
expect_no_offenses(<<~RUBY)
a { }
RUBY
end
it 'accepts a non-empty block parameter with do-end style' do
expect_no_offenses(<<~RUBY)
a do |x|
end
RUBY
end
it 'accepts a non-empty block parameter with {} style' do
expect_no_offenses(<<~RUBY)
a { |x| }
RUBY
end
it 'accepts an empty block parameter with a lambda' do
expect_no_offenses(<<~RUBY)
-> () { do_something }
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/object_then_spec.rb | spec/rubocop/cop/style/object_then_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::ObjectThen, :config do
context 'EnforcedStyle: then' do
let(:cop_config) { { 'EnforcedStyle' => 'then' } }
it 'does not register an offense for method names other than `then`' do
expect_no_offenses(<<~RUBY)
obj.map { |x| x.foo }
RUBY
end
context 'Ruby 2.5', :ruby25, unsupported_on: :prism do
it 'accepts yield_self with block' do
expect_no_offenses(<<~RUBY)
obj.yield_self { |e| e.test }
RUBY
end
end
context 'Ruby 2.6', :ruby26 do
it 'registers an offense for yield_self with block' do
expect_offense(<<~RUBY)
obj.yield_self { |e| e.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj.then { |e| e.test }
RUBY
end
it 'registers an offense for yield_self with safe navigation and block' do
expect_offense(<<~RUBY)
obj&.yield_self { |e| e.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj&.then { |e| e.test }
RUBY
end
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for yield_self with numblock' do
expect_offense(<<~RUBY)
obj.yield_self { _1.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj.then { _1.test }
RUBY
end
it 'registers an offense for yield_self with safe navigation and numblock' do
expect_offense(<<~RUBY)
obj&.yield_self { _1.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj&.then { _1.test }
RUBY
end
it 'registers an offense for `yield_self` without receiver' do
expect_offense(<<~RUBY)
yield_self { |obj| obj.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
self.then { |obj| obj.test }
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for yield_self with itblock' do
expect_offense(<<~RUBY)
obj.yield_self { it.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj.then { it.test }
RUBY
end
it 'registers an offense for yield_self with safe navigation and itblock' do
expect_offense(<<~RUBY)
obj&.yield_self { it.test }
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj&.then { it.test }
RUBY
end
end
it 'registers an offense for yield_self with proc param' do
expect_offense(<<~RUBY)
obj.yield_self(&:test)
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj.then(&:test)
RUBY
end
it 'registers an offense for yield_self with safe navigation and proc param' do
expect_offense(<<~RUBY)
obj&.yield_self(&:test)
^^^^^^^^^^ Prefer `then` over `yield_self`.
RUBY
expect_correction(<<~RUBY)
obj&.then(&:test)
RUBY
end
it 'accepts yield_self with more than 1 param' do
expect_no_offenses(<<~RUBY)
obj.yield_self(other, &:test)
RUBY
end
it 'accepts yield_self with safe navigation and more than 1 param' do
expect_no_offenses(<<~RUBY)
obj&.yield_self(other, &:test)
RUBY
end
it 'accepts yield_self without a block' do
expect_no_offenses(<<~RUBY)
obj.yield_self
RUBY
end
it 'accepts yield_self with safe navigation without a block' do
expect_no_offenses(<<~RUBY)
obj&.yield_self
RUBY
end
end
context 'EnforcedStyle: yield_self' do
let(:cop_config) { { 'EnforcedStyle' => 'yield_self' } }
it 'registers an offense for then with block' do
expect_offense(<<~RUBY)
obj.then { |e| e.test }
^^^^ Prefer `yield_self` over `then`.
RUBY
expect_correction(<<~RUBY)
obj.yield_self { |e| e.test }
RUBY
end
it 'registers an offense for then with safe navigation with block' do
expect_offense(<<~RUBY)
obj&.then { |e| e.test }
^^^^ Prefer `yield_self` over `then`.
RUBY
expect_correction(<<~RUBY)
obj&.yield_self { |e| e.test }
RUBY
end
it 'registers an offense for then with proc param' do
expect_offense(<<~RUBY)
obj.then(&:test)
^^^^ Prefer `yield_self` over `then`.
RUBY
expect_correction(<<~RUBY)
obj.yield_self(&:test)
RUBY
end
it 'registers an offense for then with safe navigation and proc param' do
expect_offense(<<~RUBY)
obj&.then(&:test)
^^^^ Prefer `yield_self` over `then`.
RUBY
expect_correction(<<~RUBY)
obj&.yield_self(&:test)
RUBY
end
it 'accepts then with more than 1 param' do
expect_no_offenses(<<~RUBY)
obj.then(other, &:test)
RUBY
end
it 'accepts then with safe navigation and more than 1 param' do
expect_no_offenses(<<~RUBY)
obj&.then(other, &:test)
RUBY
end
it 'accepts then without a block' do
expect_no_offenses(<<~RUBY)
obj.then
RUBY
end
it 'accepts then with safe navigation without a block' do
expect_no_offenses(<<~RUBY)
obj&.then
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/metrics/collection_literal_length_spec.rb | spec/rubocop/cop/metrics/collection_literal_length_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::CollectionLiteralLength, :config do
let(:cop_config) do
{
'LengthThreshold' => length_threshold
}
end
let(:length_threshold) { 10 }
let(:message) do
'Avoid hard coding large quantities of data in code. ' \
'Prefer reading the data from an external source.'
end
let(:large_array) { (0...length_threshold).to_a }
let(:large_hash) { (0...length_threshold).to_h { |n| [n, n] } }
it 'registers an offense when using an `Array` literal with too many entries (on one line)' do
literal = large_array.to_s
expect_offense(<<~RUBY)
#{literal}
#{'^' * literal.length} #{message}
RUBY
end
it 'registers an offense when using an `Array` literal with too many entries (one per line)' do
expect_offense(<<~RUBY)
[
^ #{message}
#{large_array.join(",\n ")}
]
RUBY
end
it 'registers no offense when using an `Array` literal with fewer entries than the threshold (on one line)' do
literal = large_array.drop(1).to_s
expect_no_offenses(literal)
end
it 'registers no offense when using an `Array` literal with fewer entries than the threshold (one per line)' do
expect_no_offenses(<<~RUBY)
[
#{large_array.drop(1).join(",\n ")}
]
RUBY
end
it 'registers an offense when using an `Hash` literal with too many entries (on one line)' do
literal = large_hash.to_s
expect_offense(<<~RUBY)
#{literal}
#{'^' * literal.length} #{message}
RUBY
end
it 'registers an offense when using an `Hash` literal with too many entries (one per line)' do
expect_offense(<<~RUBY)
{
^ #{message}
#{large_hash.map { |k, v| "#{k} => #{v}" }.join(",\n ")}
}
RUBY
end
it 'registers no offense when using an `Hash` literal with fewer entries than the threshold (on one line)' do
literal = large_hash.drop(1).to_h.to_s
expect_no_offenses(literal)
end
it 'registers no offense when using an `Hash` literal with fewer entries than the threshold (one per line)' do
expect_no_offenses(<<~RUBY)
{
#{large_hash.drop(1).map { |k, v| "#{k} => #{v}" }.join(",\n ")}
}
RUBY
end
it 'registers an offense when using an `Set` "literal" with too many entries (on one line)' do
literal = "Set[#{large_array.join(', ')}]"
expect_offense(<<~RUBY)
#{literal}
#{'^' * literal.length} #{message}
RUBY
end
it 'registers an offense when using an `Set` "literal" with too many entries (one per line)' do
expect_offense(<<~RUBY)
Set[
^^^^ #{message}
#{large_array.join(",\n ")}
]
RUBY
end
it 'registers no offense when using an `Set` "literal" with fewer entries than the threshold (on one line)' do
literal = "Set[#{large_array.drop(1).join(', ')}]"
expect_no_offenses(literal)
end
it 'registers no offense when using an `Set` "literal" with fewer entries than the threshold (one per line)' do
expect_no_offenses(<<~RUBY)
Set[
#{large_array.drop(1).join(",\n ")}
]
RUBY
end
it 'does not register an offense when `[]` is called on something other than `Set`' do
expect_no_offenses(<<~RUBY)
foo[
#{large_array.join(",\n ")}
]
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/metrics/block_nesting_spec.rb | spec/rubocop/cop/metrics/block_nesting_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::BlockNesting, :config do
let(:cop_config) { { 'Max' => 2 } }
it 'accepts `Max` levels of nesting' do
expect_no_offenses(<<~RUBY)
if a
if b
puts b
end
end
RUBY
end
context '`Max + 1` levels of `if` nesting' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
if c
^^^^ Avoid more than 2 levels of block nesting.
puts c
end
end
end
RUBY
expect(cop.config_to_allow_offenses[:exclude_limit]).to eq('Max' => 3)
end
end
context '`Max + 2` levels of `if` nesting' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
if c
^^^^ Avoid more than 2 levels of block nesting.
if d
puts d
end
end
end
end
RUBY
expect(cop.config_to_allow_offenses[:exclude_limit]).to eq('Max' => 4)
end
end
context 'Multiple nested `ifs` at same level' do
it 'registers 2 offenses' do
expect_offense(<<~RUBY)
if a
if b
if c
^^^^ Avoid more than 2 levels of block nesting.
puts c
end
end
if d
if e
^^^^ Avoid more than 2 levels of block nesting.
puts e
end
end
end
RUBY
expect(cop.config_to_allow_offenses[:exclude_limit]).to eq('Max' => 3)
end
end
context 'nested `case`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
case c
^^^^^^ Avoid more than 2 levels of block nesting.
when C
puts C
end
end
end
RUBY
end
end
context 'nested `case` as a pattern matching', :ruby27 do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
case c
^^^^^^ Avoid more than 2 levels of block nesting.
in C
puts C
end
end
end
RUBY
end
end
context 'nested `while`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
while c
^^^^^^^ Avoid more than 2 levels of block nesting.
puts c
end
end
end
RUBY
end
end
context 'nested modifier `while`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
begin
^^^^^ Avoid more than 2 levels of block nesting.
puts c
end while c
end
end
RUBY
end
end
context 'nested `until`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
until c
^^^^^^^ Avoid more than 2 levels of block nesting.
puts c
end
end
end
RUBY
end
end
context 'nested modifier `until`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
begin
^^^^^ Avoid more than 2 levels of block nesting.
puts c
end until c
end
end
RUBY
end
end
context 'nested `for`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
for c in [1,2] do
^^^^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
puts c
end
end
end
RUBY
end
end
context 'nested `rescue`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
begin
puts c
rescue
^^^^^^ Avoid more than 2 levels of block nesting.
puts x
end
end
end
RUBY
end
end
it 'accepts if/elsif' do
expect_no_offenses(<<~RUBY)
if a
elsif b
elsif c
elsif d
end
RUBY
end
context 'when CountBlocks is false' do
let(:cop_config) { { 'Max' => 2, 'CountBlocks' => false } }
it 'accepts nested multiline blocks' do
expect_no_offenses(<<~RUBY)
if a
if b
[1, 2].each do |c|
puts c
end
end
end
RUBY
end
it 'accepts nested inline blocks' do
expect_no_offenses(<<~RUBY)
if a
if b
[1, 2].each { |c| puts c }
end
end
RUBY
end
context 'when numbered parameter', :ruby27 do
it 'accepts nested multiline blocks' do
expect_no_offenses(<<~RUBY)
if a
if b
[1, 2].each do
puts _1
end
end
end
RUBY
end
it 'accepts nested inline blocks' do
expect_no_offenses(<<~RUBY)
if a
if b
[1, 2].each { puts _1 }
end
end
RUBY
end
end
end
context 'when CountBlocks is true' do
let(:cop_config) { { 'Max' => 2, 'CountBlocks' => true } }
context 'nested multiline block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
[1, 2].each do |c|
^^^^^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
puts c
end
end
end
RUBY
end
end
context 'nested inline block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
[1, 2].each { |c| puts c }
^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
end
end
RUBY
end
end
context 'when numbered parameter', :ruby27 do
context 'nested multiline block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
[1, 2].each do
^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
puts _1
end
end
end
RUBY
end
end
context 'nested inline block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
[1, 2].each { puts _1 }
^^^^^^^^^^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
end
end
RUBY
end
end
end
context 'when `it` parameter', :ruby34 do
context 'nested multiline block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
[1, 2].each do
^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
puts it
end
end
end
RUBY
end
end
context 'nested inline block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
[1, 2].each { puts it }
^^^^^^^^^^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
end
end
RUBY
end
end
end
end
context 'when CountModifierForms is false' do
let(:cop_config) { { 'Max' => 2, 'CountModifierForms' => false } }
it 'accepts nested modifier forms' do
expect_no_offenses(<<~RUBY)
if a
if b
puts 'hello' if c
end
end
RUBY
end
it 'registers nested if expressions' do
expect_offense(<<~RUBY)
if a
if b
if c
^^^^ Avoid more than 2 levels of block nesting.
puts 'hello'
end
end
end
RUBY
end
end
context 'when CountModifierForms is true' do
let(:cop_config) { { 'Max' => 2, 'CountModifierForms' => true } }
context 'nested modifier forms' do
it 'registers an offense' do
expect_offense(<<~RUBY)
if a
if b
puts 'hello' if c
^^^^^^^^^^^^^^^^^ Avoid more than 2 levels of block nesting.
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/metrics/parameter_lists_spec.rb | spec/rubocop/cop/metrics/parameter_lists_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::ParameterLists, :config do
let(:cop_config) { { 'Max' => 4, 'CountKeywordArgs' => true, 'MaxOptionalParameters' => 3 } }
it 'registers an offense for a method def with 5 parameters' do
expect_offense(<<~RUBY)
def meth(a, b, c, d, e)
^^^^^^^^^^^^^^^ Avoid parameter lists longer than 4 parameters. [5/4]
end
RUBY
end
it 'accepts a method def with 4 parameters' do
expect_no_offenses(<<~RUBY)
def meth(a, b, c, d)
end
RUBY
end
it 'accepts a proc with more than 4 parameters' do
expect_no_offenses(<<~RUBY)
proc { |a, b, c, d, e| }
RUBY
end
it 'accepts a lambda with more than 4 parameters' do
expect_no_offenses(<<~RUBY)
->(a, b, c, d, e) { }
RUBY
end
context 'When CountKeywordArgs is true' do
it 'counts keyword arguments as well' do
expect_offense(<<~RUBY)
def meth(a, b, c, d: 1, e: 2)
^^^^^^^^^^^^^^^^^^^^^ Avoid parameter lists longer than 4 parameters. [5/4]
end
RUBY
end
end
context 'When CountKeywordArgs is false' do
before { cop_config['CountKeywordArgs'] = false }
it 'does not count keyword arguments' do
expect_no_offenses(<<~RUBY)
def meth(a, b, c, d: 1, e: 2)
end
RUBY
end
it 'does not count keyword arguments without default values' do
expect_no_offenses(<<~RUBY)
def meth(a, b, c, d:, e:)
end
RUBY
end
end
it 'registers an offense when optargs count exceeds the maximum' do
expect_offense(<<~RUBY)
def foo(a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid parameter lists longer than 4 parameters. [7/4]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method has too many optional parameters. [7/3]
end
def foo(a = 1, b = 2, c = 3, d = 4)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method has too many optional parameters. [4/3]
end
RUBY
expect(cop.config_to_allow_offenses[:exclude_limit]).to eq(
'Max' => 7,
'MaxOptionalParameters' => 7
)
end
it 'does not register an offense when method has allowed amount of optargs' do
expect_no_offenses(<<~RUBY)
def foo(a, b = 2, c = 3, d = 4)
end
RUBY
end
it 'does not register an offense when method has allowed amount of args with block arg' do
expect_no_offenses(<<~RUBY)
def foo(a, b, c, d, &block)
end
RUBY
end
it 'does not register an offense when method has no args' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
it 'registers an offense when defining `initialize` in the `class` definition' do
expect_offense(<<~RUBY)
class Foo
def initialize(one:, two:, three:, four:, five:)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid parameter lists longer than 4 parameters. [5/4]
end
end
RUBY
end
it 'does not register an offense when defining `initialize` in the block of `Struct.new`' do
expect_no_offenses(<<~RUBY)
Struct.new(:one, :two, :three, :four, :five) do
def initialize(one:, two:, three:, four:, five:)
end
end
RUBY
end
it 'does not register an offense when defining `initialize` in the block of `::Struct.new`' do
expect_no_offenses(<<~RUBY)
::Struct.new(:one, :two, :three, :four, :five) do
def initialize(one:, two:, three:, four:, five:)
end
end
RUBY
end
it 'does not register an offense when defining `initialize` in the block of `Data.define`' do
expect_no_offenses(<<~RUBY)
Data.define(:one, :two, :three, :four, :five) do
def initialize(one:, two:, three:, four:, five:)
end
end
RUBY
end
it 'does not register an offense when defining `initialize` in the block of `::Data.define`' do
expect_no_offenses(<<~RUBY)
::Data.define(:one, :two, :three, :four, :five) do
def initialize(one:, two:, three:, four:, five:)
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/metrics/class_length_spec.rb | spec/rubocop/cop/metrics/class_length_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::ClassLength, :config do
let(:cop_config) { { 'Max' => 5, 'CountComments' => false } }
it 'rejects a class with more than 5 lines' do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'registers an offense when a class with a singleton class definition has more than 5 lines' do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class has too many lines. [8/5]
class << self
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
end
RUBY
end
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(8)
end
it 'accepts a class with 5 lines' do
expect_no_offenses(<<~RUBY)
class Test
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
it 'accepts a class with less than 5 lines' do
expect_no_offenses(<<~RUBY)
class Test
a = 1
a = 2
a = 3
a = 4
end
RUBY
end
it 'does not count blank lines' do
expect_no_offenses(<<~RUBY)
class Test
a = 1
a = 2
a = 3
a = 4
a = 7
end
RUBY
end
it 'accepts empty classes' do
expect_no_offenses(<<~RUBY)
class Test
end
RUBY
end
context 'when a class has inner classes' do
it 'does not count lines of inner classes' do
expect_no_offenses(<<~RUBY)
class NamespaceClass
class TestOne
a = 1
a = 2
a = 3
a = 4
a = 5
end
class TestTwo
a = 1
a = 2
a = 3
a = 4
a = 5
end
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
it 'rejects a class with 6 lines that belong to the class directly' do
expect_offense(<<~RUBY)
class NamespaceClass
^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
class TestOne
a = 1
a = 2
a = 3
a = 4
a = 5
end
class TestTwo
a = 1
a = 2
a = 3
a = 4
a = 5
end
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'with `--lsp` option', :lsp do
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(1)
end
end
context 'when CountComments is disabled' do
it 'accepts classes that only contain comments' do
expect_no_offenses(<<~RUBY)
class Test
# comment
# comment
# comment
# comment
# comment
# comment
end
RUBY
end
end
context 'when CountComments is enabled' do
before { cop_config['CountComments'] = true }
it 'also counts commented lines' do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
#a = 2
a = 3
#a = 4
a = 5
a = 6
end
RUBY
end
it 'registers an offense for a class that only contains comments' do
expect_offense(<<~RUBY)
class Test
^^^^^^^^^^ Class has too many lines. [6/5]
# comment
# comment
# comment
# comment
# comment
# comment
end
RUBY
end
end
context 'when `CountAsOne` is not empty' do
before { cop_config['CountAsOne'] = ['array'] }
it 'folds array into one line' do
expect_no_offenses(<<~RUBY)
class Test
a = 1
a = [
2,
3,
4,
5
]
end
RUBY
end
end
context 'when overlapping constant assignments' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
X = Y = Z = do_something
RUBY
end
end
context 'when singleton class' do
it 'rejects a class with more than 5 lines' do
expect_offense(<<~RUBY)
class << self
^^^^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'accepts a class with 5 lines' do
expect_no_offenses(<<~RUBY)
class << self
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
end
context 'when inspecting a class defined with Class.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Class.new do
^^^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when inspecting a class defined with ::Class.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = ::Class.new do
^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when inspecting a class defined with Class.new with chained assignments' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Bar = Class.new do
^^^^^^^^^^^^ Class has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
end
context 'when inspecting a class defined with Class.new with chained assignments in class body' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Class.new do
^^^^^^^^^^^^ Class has too many lines. [6/5]
self.a = self::B = 1
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
end
context 'when inspecting a class defined with Struct.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'registers an offense when inspecting or equals (`||=`) for constant' do
expect_offense(<<~RUBY)
Foo ||= Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'registers an offense when multiple assignments to constants' do
# `Bar` is always nil, but syntax is valid.
expect_offense(<<~RUBY)
Foo, Bar = Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when using numbered parameter', :ruby27 do
context 'when inspecting a class defined with Class.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Class.new do
^^^^^^^^^^^^ Class has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
end
context 'when inspecting a class defined with ::Class.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = ::Class.new do
^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
end
context 'when inspecting a class defined with Struct.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
it 'registers an offense when inspecting or equals (`||=`) for constant' do
expect_offense(<<~RUBY)
Foo ||= Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
it 'registers an offense when multiple assignments to constants' do
# `Bar` is always nil, but syntax is valid.
expect_offense(<<~RUBY)
Foo, Bar = Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
end
end
context 'when using `it` parameter', :ruby34 do
context 'when inspecting a class defined with Class.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Class.new do
^^^^^^^^^^^^ Class has too many lines. [6/5]
a(it)
b(it)
c(it)
d(it)
e(it)
f(it)
end
RUBY
end
end
context 'when inspecting a class defined with ::Class.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = ::Class.new do
^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(it)
b(it)
c(it)
d(it)
e(it)
f(it)
end
RUBY
end
end
context 'when inspecting a class defined with Struct.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(it)
b(it)
c(it)
d(it)
e(it)
f(it)
end
RUBY
end
it 'registers an offense when inspecting or equals (`||=`) for constant' do
expect_offense(<<~RUBY)
Foo ||= Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(it)
b(it)
c(it)
d(it)
e(it)
f(it)
end
RUBY
end
it 'registers an offense when multiple assignments to constants' do
# `Bar` is always nil, but syntax is valid.
expect_offense(<<~RUBY)
Foo, Bar = Struct.new(:foo, :bar) do
^^^^^^^^^^^^^^^^^^^^^^^^^ Class has too many lines. [6/5]
a(it)
b(it)
c(it)
d(it)
e(it)
f(it)
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/metrics/module_length_spec.rb | spec/rubocop/cop/metrics/module_length_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::ModuleLength, :config do
let(:cop_config) { { 'Max' => 5, 'CountComments' => false } }
it 'rejects a module with more than 5 lines' do
expect_offense(<<~RUBY)
module Test
^^^^^^^^^^^ Module has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
module Test
^^^^^^^^^^^ Module has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(8)
end
it 'accepts a module with 5 lines' do
expect_no_offenses(<<~RUBY)
module Test
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
it 'accepts a module with less than 5 lines' do
expect_no_offenses(<<~RUBY)
module Test
a = 1
a = 2
a = 3
a = 4
end
RUBY
end
it 'does not count blank lines' do
expect_no_offenses(<<~RUBY)
module Test
a = 1
a = 2
a = 3
a = 4
a = 7
end
RUBY
end
it 'accepts empty modules' do
expect_no_offenses(<<~RUBY)
module Test
end
RUBY
end
context 'when a module has inner modules' do
it 'does not count lines of inner modules' do
expect_no_offenses(<<~RUBY)
module NamespaceModule
module TestOne
a = 1
a = 2
a = 3
a = 4
a = 5
end
module TestTwo
a = 1
a = 2
a = 3
a = 4
a = 5
end
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
it 'rejects a module with 6 lines that belong to the module directly' do
expect_offense(<<~RUBY)
module NamespaceModule
^^^^^^^^^^^^^^^^^^^^^^ Module has too many lines. [6/5]
module TestOne
a = 1
a = 2
a = 3
a = 4
a = 5
end
module TestTwo
a = 1
a = 2
a = 3
a = 4
a = 5
end
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when a module has inner classes' do
it 'does not count lines of inner classes' do
expect_no_offenses(<<~RUBY)
module NamespaceModule
class TestOne
a = 1
a = 2
a = 3
a = 4
a = 5
end
class TestTwo
a = 1
a = 2
a = 3
a = 4
a = 5
end
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
it 'rejects a module with more than 5 lines including its singleton class' do
expect_offense(<<~RUBY)
module Test
^^^^^^^^^^^ Module has too many lines. [8/5]
class << self
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
end
RUBY
end
it 'rejects a module with more than 5 lines that belong to the module directly and including its singleton class' do
expect_offense(<<~RUBY)
module NamespaceModule
^^^^^^^^^^^^^^^^^^^^^^ Module has too many lines. [13/5]
class << self
a = 1
a = 2
a = 3
a = 4
a = 5
end
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'rejects a module with 6 lines that belong to the module directly' do
expect_offense(<<~RUBY)
module NamespaceModule
^^^^^^^^^^^^^^^^^^^^^^ Module has too many lines. [6/5]
class TestOne
a = 1
a = 2
a = 3
a = 4
a = 5
end
class TestTwo
a = 1
a = 2
a = 3
a = 4
a = 5
end
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'with `--lsp` option', :lsp do
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
module Test
^^^^^^^^^^^ Module has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(1)
end
end
context 'when CountComments is enabled' do
before { cop_config['CountComments'] = true }
it 'also counts commented lines' do
expect_offense(<<~RUBY)
module Test
^^^^^^^^^^^ Module has too many lines. [6/5]
a = 1
#a = 2
a = 3
#a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when `CountAsOne` is not empty' do
before { cop_config['CountAsOne'] = ['array'] }
it 'folds array into one line' do
expect_no_offenses(<<~RUBY)
module Test
a = 1
a = [
2,
3,
4,
5
]
end
RUBY
end
end
context 'when inspecting a class defined with Module.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Module.new do
^^^ Module has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when inspecting a class defined with ::Module.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = ::Module.new do
^^^ Module has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when using numbered parameter', :ruby27 do
context 'when inspecting a class defined with Module.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Module.new do
^^^ Module has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
end
context 'when inspecting a class defined with ::Module.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = ::Module.new do
^^^ Module has too many lines. [6/5]
a(_1)
b(_1)
c(_1)
d(_1)
e(_1)
f(_1)
end
RUBY
end
end
end
context 'when using `it` parameter', :ruby34 do
context 'when inspecting a class defined with Module.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = Module.new do
^^^ Module has too many lines. [6/5]
a(it)
b(it)
c(it)
d(it)
e(it)
f(it)
end
RUBY
end
end
context 'when inspecting a class defined with ::Module.new' do
it 'registers an offense' do
expect_offense(<<~RUBY)
Foo = ::Module.new do
^^^ Module has too many lines. [6/5]
a(it)
b(it)
c(it)
d(it)
e(it)
f(it)
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/metrics/block_length_spec.rb | spec/rubocop/cop/metrics/block_length_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::BlockLength, :config do
let(:cop_config) { { 'Max' => 2, 'CountComments' => false } }
shared_examples 'allow an offense on an allowed method' do |allowed, config_key|
before { cop_config[config_key] = [allowed] }
it 'still rejects other methods with long blocks' do
expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
end
RUBY
end
it 'accepts the foo method with a long block' do
expect_no_offenses(<<~RUBY)
#{allowed} do
a = 1
a = 2
a = 3
end
RUBY
end
end
it 'rejects a block with more than 5 lines' do
expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
end
RUBY
end
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(5)
end
it 'accepts a block with less than 3 lines' do
expect_no_offenses(<<~RUBY)
something do
a = 1
a = 2
end
RUBY
end
it 'does not count blank lines' do
expect_no_offenses(<<~RUBY)
something do
a = 1
a = 4
end
RUBY
end
context 'when the `CountAsOne` config is invalid' do
before do
cop_config['CountAsOne'] = 'config'
end
let(:source) { <<~RUBY }
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
end
RUBY
it 'raises `RuboCop::Warning`' do
expect { expect_offense(source) }.to raise_error(RuboCop::Warning)
end
end
context 'when using numbered parameter', :ruby27 do
it 'rejects a block with more than 5 lines' do
expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = _1
a = _2
a = _3
end
RUBY
end
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = _1
a = _2
a = _3
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(5)
end
it 'accepts a block with less than 3 lines' do
expect_no_offenses(<<~RUBY)
something do
a = _1
a = _2
end
RUBY
end
it 'does not count blank lines' do
expect_no_offenses(<<~RUBY)
something do
a = _1
a = _2
end
RUBY
end
end
context 'when using `it` parameter', :ruby34 do
it 'rejects a block with more than 5 lines' do
expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = it
a = it
a = it
end
RUBY
end
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = it
a = it
a = it
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(5)
end
it 'accepts a block with less than 3 lines' do
expect_no_offenses(<<~RUBY)
something do
a = it
a = it
end
RUBY
end
it 'does not count blank lines' do
expect_no_offenses(<<~RUBY)
something do
a = it
a = it
end
RUBY
end
end
it 'accepts a block with multiline receiver and less than 3 lines of body' do
expect_no_offenses(<<~RUBY)
[
:a,
:b,
:c,
].each do
a = 1
a = 2
end
RUBY
end
it 'accepts empty blocks' do
expect_no_offenses(<<~RUBY)
something do
end
RUBY
end
it 'rejects brace blocks too' do
expect_offense(<<~RUBY)
something {
^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
}
RUBY
end
it 'properly counts nested blocks' do
expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [6/2]
something do
^^^^^^^^^^^^ Block has too many lines. [4/2]
a = 2
a = 3
a = 4
a = 5
end
end
RUBY
end
it 'does not count commented lines by default' do
expect_no_offenses(<<~RUBY)
something do
a = 1
#a = 2
#a = 3
a = 4
end
RUBY
end
context 'when defining a class' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
Class.new do
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when defining a module' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
Module.new do
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when defining a Struct' do
it 'does not register an offense' do
expect_no_offenses(<<~'RUBY')
Person = Struct.new(:first_name, :last_name) do
def full_name
"#{first_name} #{last_name}"
end
def foo
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
end
RUBY
end
end
context 'with `--lsp` option', :lsp do
it 'reports the correct beginning and end lines' do
offenses = expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = _1
a = _2
a = _3
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(1)
end
end
context 'when CountComments is enabled' do
before { cop_config['CountComments'] = true }
it 'also counts commented lines' do
expect_offense(<<~RUBY)
something do
^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
#a = 2
a = 3
end
RUBY
end
end
context 'when `CountAsOne` is not empty' do
before { cop_config['CountAsOne'] = ['array'] }
it 'folds array into one line' do
expect_no_offenses(<<~RUBY)
something do
a = 1
a = [
2,
3
]
end
RUBY
end
end
context 'when methods to allow are defined' do
context 'when AllowedMethods is enabled' do
it_behaves_like('allow an offense on an allowed method', 'foo', 'AllowedMethods')
it_behaves_like('allow an offense on an allowed method', 'Gem::Specification.new',
'AllowedMethods')
context 'when receiver contains whitespaces' do
before { cop_config['AllowedMethods'] = ['Foo::Bar.baz'] }
it 'allows whitespaces' do
expect_no_offenses(<<~RUBY)
Foo::
Bar.baz do
a = 1
a = 2
a = 3
end
RUBY
end
end
context 'when a method is allowed, but receiver is a module' do
before { cop_config['AllowedMethods'] = ['baz'] }
it 'does not report an offense' do
expect_no_offenses(<<~RUBY)
Foo::Bar.baz do
a = 1
a = 2
a = 3
end
RUBY
end
end
end
context 'when AllowedPatterns is enabled' do
before { cop_config['AllowedPatterns'] = [/baz/] }
it 'does not report an offense' do
expect_no_offenses(<<~RUBY)
Foo::Bar.baz do
a = 1
a = 2
a = 3
end
RUBY
end
context 'that does not match' do
it 'reports an offense' do
expect_offense(<<~RUBY)
Foo::Bar.bar do
^^^^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
end
RUBY
end
end
end
context 'when IgnoredMethods is enabled' do
context 'when string' do
before { cop_config['IgnoredMethods'] = ['Foo::Bar.baz'] }
it 'does not report an offense' do
expect_no_offenses(<<~RUBY)
Foo::Bar.baz do
a = 1
a = 2
a = 3
end
RUBY
end
context 'that does not match' do
it 'reports an offense' do
expect_offense(<<~RUBY)
Foo::Bar.bar do
^^^^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
end
RUBY
end
end
end
context 'when regex' do
before { cop_config['IgnoredMethods'] = [/baz/] }
it 'does not report an offense' do
expect_no_offenses(<<~RUBY)
Foo::Bar.baz do
a = 1
a = 2
a = 3
end
RUBY
end
context 'that does not match' do
it 'reports an offense' do
expect_offense(<<~RUBY)
Foo::Bar.bar do
^^^^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
end
RUBY
end
end
end
end
context 'when ExcludedMethods is enabled' do
before { cop_config['ExcludedMethods'] = ['Foo::Bar.baz'] }
it 'does not report an offense' do
expect_no_offenses(<<~RUBY)
Foo::Bar.baz do
a = 1
a = 2
a = 3
end
RUBY
end
context 'that does not match' do
it 'reports an offense' do
expect_offense(<<~RUBY)
Foo::Bar.bar do
^^^^^^^^^^^^^^^ Block has too many lines. [3/2]
a = 1
a = 2
a = 3
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/metrics/method_length_spec.rb | spec/rubocop/cop/metrics/method_length_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::MethodLength, :config do
let(:cop_config) { { 'Max' => 5, 'CountComments' => false } }
context 'when method is an instance method' do
it 'does not register an offense when there are exactly `Max` lines' do
expect_no_offenses(<<~RUBY)
def m
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
it 'registers an offense' do
expect_offense(<<~RUBY)
def m
^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when method is defined with `define_method`' do
it 'does not register an offense when there are exactly `Max` lines' do
expect_no_offenses(<<~RUBY)
define_method(:m) do
a = 1
a = 2
a = 3
a = 4
a = 5
end
RUBY
end
it 'registers an offense when there are more than `Max` lines' do
expect_offense(<<~RUBY)
define_method(:m) do
^^^^^^^^^^^^^^^^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'registers an offense for an over-long dynamically defined method with a dynamic symbol name' do
expect_offense(<<~'RUBY')
define_method(:"#{method_name}=") do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'registers an offense for an over-long dynamically defined method with a dynamic string name' do
expect_offense(<<~'RUBY')
define_method("#{method_name}=") do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when using numbered parameter', :ruby27 do
context 'when method is defined with `define_method`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
define_method(:m) do
^^^^^^^^^^^^^^^^^^^^ Method has too many lines. [6/5]
a = _1
a = _2
a = _3
a = _4
a = _5
a = _6
end
RUBY
end
end
end
context 'when using `it` parameter', :ruby34 do
context 'when method is defined with `define_method`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
define_method(:m) do
^^^^^^^^^^^^^^^^^^^^ Method has too many lines. [6/5]
a = it
a = it
a = it
a = it
a = it
a = it
end
RUBY
end
end
end
context 'when method is a class method' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.m
^^^^^^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when method is defined on a singleton class' do
it 'registers an offense' do
expect_offense(<<~RUBY)
class K
class << self
def m
^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
end
end
RUBY
end
end
it 'accepts a method with less than 5 lines' do
expect_no_offenses(<<~RUBY)
def m
a = 1
a = 2
a = 3
a = 4
end
RUBY
end
it 'accepts a method with multiline arguments and less than 5 lines of body' do
expect_no_offenses(<<~RUBY)
def m(x,
y,
z)
a = 1
a = 2
a = 3
a = 4
end
RUBY
end
it 'does not count blank lines' do
expect_no_offenses(<<~RUBY)
def m()
a = 1
a = 2
a = 3
a = 4
a = 7
end
RUBY
end
it 'accepts empty methods' do
expect_no_offenses(<<~RUBY)
def m()
end
RUBY
end
it 'is not fooled by one-liner methods, syntax #1' do
expect_no_offenses(<<~RUBY)
def one_line; 10 end
def self.m()
a = 1
a = 2
a = 4
a = 5
a = 6
end
RUBY
end
it 'is not fooled by one-liner methods, syntax #2' do
expect_no_offenses(<<~RUBY)
def one_line(test) 10 end
def self.m()
a = 1
a = 2
a = 4
a = 5
a = 6
end
RUBY
end
it 'properly counts lines when method ends with block' do
expect_offense(<<~RUBY)
def m
^^^^^ Method has too many lines. [6/5]
something do
a = 2
a = 3
a = 4
a = 5
end
end
RUBY
end
it 'does not count commented lines by default' do
expect_no_offenses(<<~RUBY)
def m()
a = 1
#a = 2
a = 3
#a = 4
a = 5
a = 6
end
RUBY
end
it 'does not crash when using a heredoc in a block without block arguments' do
expect_no_offenses(<<~RUBY)
def foo
do_something do
<<~HEREDOC
text
HEREDOC
end
end
RUBY
end
context 'when CountComments is enabled' do
before { cop_config['CountComments'] = true }
it 'also counts commented lines' do
expect_offense(<<~RUBY)
def m
^^^^^ Method has too many lines. [6/5]
a = 1
#a = 2
a = 3
#a = 4
a = 5
a = 6
end
RUBY
end
end
context 'when methods to allow are defined' do
context 'AllowedMethods is enabled' do
before { cop_config['AllowedMethods'] = ['foo'] }
it 'still rejects other methods with more than 5 lines' do
expect_offense(<<~RUBY)
def m
^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'accepts the foo method with more than 5 lines' do
expect_no_offenses(<<~RUBY)
def foo
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'accepts dynamically defined matching method name with more than 5 lines' do
expect_no_offenses(<<~RUBY)
define_method(:foo) do
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'accepts dynamically defined matching method name with a numblock' do
expect_no_offenses(<<~RUBY)
define_method(:foo) do
a = _1
a = _2
a = _3
a = _4
a = _5
a = _6
end
RUBY
end
it 'accepts dynamically defined matching method name with an itblock', :ruby34 do
expect_no_offenses(<<~RUBY)
define_method(:foo) do
a = it
a = it
a = it
a = it
a = it
a = it
end
RUBY
end
end
context 'AllowedPatterns is enabled' do
before { cop_config['AllowedPatterns'] = [/_name/] }
it 'accepts the user_name method' do
expect_no_offenses(<<~RUBY)
def user_name
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'accepts dynamically defined matching method name with more than 5 lines' do
expect_no_offenses(<<~RUBY)
define_method(:user_name) do
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
it 'accepts dynamically defined matching method name with a numblock' do
expect_no_offenses(<<~RUBY)
define_method(:user_name) do
a = _1
a = _2
a = _3
a = _4
a = _5
a = _6
end
RUBY
end
it 'accepts dynamically defined matching method name with an itblock', :ruby34 do
expect_no_offenses(<<~RUBY)
define_method(:user_name) do
a = it
a = it
a = it
a = it
a = it
a = it
end
RUBY
end
it 'raises offense for firstname' do
expect_offense(<<~RUBY)
def firstname
^^^^^^^^^^^^^ Method has too many lines. [6/5]
a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
end
RUBY
end
end
end
context 'when `CountAsOne` is not empty' do
before { cop_config['CountAsOne'] = ['array'] }
it 'folds array into one line' do
expect_no_offenses(<<~RUBY)
def m
a = 1
a = [
2,
3,
4,
5
]
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/metrics/cyclomatic_complexity_spec.rb | spec/rubocop/cop/metrics/cyclomatic_complexity_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::CyclomaticComplexity, :config do
context 'when Max is 1' do
let(:cop_config) { { 'Max' => 1 } }
it 'accepts a method with no decision points' do
expect_no_offenses(<<~RUBY)
def method_name
call_foo
end
RUBY
end
it 'accepts an empty method' do
expect_no_offenses(<<~RUBY)
def method_name
end
RUBY
end
it 'accepts an empty `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :method_name do
end
RUBY
end
it 'accepts complex code outside of methods' do
expect_no_offenses(<<~RUBY)
def method_name
call_foo
end
if first_condition then
call_foo if second_condition && third_condition
call_bar if fourth_condition || fifth_condition
end
RUBY
end
it 'registers an offense for an if modifier' do
expect_offense(<<~RUBY)
def self.method_name
^^^^^^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo if some_condition
end
RUBY
end
it 'registers an offense for an unless modifier' do
offenses = expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo unless some_condition
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(3)
end
it 'registers an offense for an elsif block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [3/1]
if first_condition then
call_foo
elsif second_condition then
call_bar
else
call_bam
end
end
RUBY
end
it 'registers an offense for a ternary operator' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
value = some_condition ? 1 : 2
end
RUBY
end
it 'registers an offense for a while block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
while some_condition do
call_foo
end
end
RUBY
end
it 'registers an offense for an until block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
until some_condition do
call_foo
end
end
RUBY
end
it 'registers an offense for a for block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
for i in 1..2 do
call_method
end
end
RUBY
end
it 'registers an offense for a rescue block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
begin
call_foo
rescue Exception
call_bar
end
end
RUBY
end
it 'registers an offense for a case/when block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [3/1]
case value
when 1
call_foo
when 2
call_bar
end
end
RUBY
end
it 'registers an offense for a case/in block', :ruby27 do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [3/1]
case value
in 1
call_foo
in 2
call_bar
end
end
RUBY
end
it 'registers an offense for &&' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo && call_bar
end
RUBY
end
it 'registers an offense for &&=' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
foo = nil
foo &&= 42
end
RUBY
end
it 'registers an offense for and' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo and call_bar
end
RUBY
end
it 'registers an offense for ||' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo || call_bar
end
RUBY
end
it 'registers an offense for ||=' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
foo = nil
foo ||= 42
end
RUBY
end
it 'registers an offense for or' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo or call_bar
end
RUBY
end
it 'deals with nested if blocks containing && and ||' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [6/1]
if first_condition then
call_foo if second_condition && third_condition
call_bar if fourth_condition || fifth_condition
end
end
RUBY
end
it 'registers an offense for &.' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [3/1]
foo&.bar
foo&.bar
end
RUBY
end
it 'counts repeated &. on same untouched local variable as 1' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [3/1]
var = 1
var&.foo
var&.dont_count_me
var = 2
var&.bar
var&.dont_count_me_either
end
RUBY
end
it 'counts only a single method' do
expect_offense(<<~RUBY)
def method_name_1
^^^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name_1` is too high. [2/1]
call_foo if some_condition
end
def method_name_2
^^^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name_2` is too high. [2/1]
call_foo if some_condition
end
RUBY
end
it 'registers an offense for a `define_method`' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo if some_condition
end
RUBY
end
it 'counts enumerating methods with blocks as +1' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [3/1]
(1..4).map do |i| # map: +1
i * 2
end.each.with_index { |val, i| puts val, i } # each: +0, with_index: +1
return treasure.map
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'counts enumerating methods with numblocks as +1' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [3/1]
(_1.._2).map do |i| # map: +1
i * 2
end.each.with_index { |val, i| puts val, i } # each: +0, with_index: +1
return treasure.map
end
RUBY
end
end
it 'counts enumerating methods with block-pass as +1' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
[].map(&:to_s)
end
RUBY
end
it 'does not count blocks in general' do
expect_no_offenses(<<~RUBY)
define_method :method_name do
Struct.new(:foo, :bar) do
String.class_eval do
[42].tap do |answer|
foo { bar }
end
end
end
end
RUBY
end
context 'with `--lsp` option', :lsp do
it 'registers an offense for an unless modifier' do
offenses = expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [2/1]
call_foo unless some_condition
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(1)
end
end
end
context 'when AllowedMethods is enabled' do
let(:cop_config) { { 'Max' => 0, 'AllowedMethods' => ['foo'] } }
it 'does not register an offense when defining an instance method' do
expect_no_offenses(<<~RUBY)
def foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when defining a class method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when using `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :foo do
bar.baz(:qux)
end
RUBY
end
end
context 'when AllowedPatterns is enabled' do
let(:cop_config) { { 'Max' => 0, 'AllowedPatterns' => [/foo/] } }
it 'does not register an offense when defining an instance method' do
expect_no_offenses(<<~RUBY)
def foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when defining a class method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when using `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :foo do
bar.baz(:qux)
end
RUBY
end
end
context 'when Max is 2' do
let(:cop_config) { { 'Max' => 2 } }
it 'counts stupid nested if and else blocks' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Cyclomatic complexity for `method_name` is too high. [5/2]
if first_condition then
call_foo
else
if second_condition then
call_bar
else
call_bam if third_condition
end
call_baz if fourth_condition
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/metrics/abc_size_spec.rb | spec/rubocop/cop/metrics/abc_size_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::AbcSize, :config do
context 'when Max is 0' do
let(:cop_config) { { 'Max' => 0 } }
it 'accepts an empty method' do
expect_no_offenses(<<~RUBY)
def method_name
end
RUBY
end
it 'accepts an empty `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :method_name do
end
RUBY
end
it 'registers an offense for an if modifier' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<0, 2, 1> 2.24/0]
call_foo if some_condition # 0 + 2*2 + 1*1
end
RUBY
end
it 'registers an offense for an assignment of a local variable' do
offenses = expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<1, 0, 0> 1/0]
x = 1
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(3)
end
it 'registers an offense for an assignment of an element' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<1, 2, 0> 2.24/0]
x[0] = 1
end
RUBY
end
it 'registers an offense for complex content including A, B, and C scores' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<3, 4, 5> 7.07/0]
my_options = Hash.new if 1 == 1 || 2 == 2 # 1, 1, 4
my_options.each do |key, value| # 2, 1, 1
p key # 0, 1, 0
p value # 0, 1, 0
end
end
RUBY
end
it 'registers an offense for a `define_method`' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<1, 0, 0> 1/0]
x = 1
end
RUBY
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense for a `define_method` with numblock' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<1, 0, 0> 1/0]
x = _1
end
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense for a `define_method` with itblock' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<1, 0, 0> 1/0]
x = it
end
RUBY
end
end
it 'treats safe navigation method calls like regular method calls + a condition' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<0, 2, 1> 2.24/0]
object&.do_something
end
RUBY
end
context 'with `--lsp` option', :lsp do
it 'registers an offense for an assignment of a local variable' do
offenses = expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [<1, 0, 0> 1/0]
x = 1
end
RUBY
offense = offenses.first
expect(offense.location.last_line).to eq(1)
end
end
context 'when method is in list of allowed methods' do
context 'when AllowedMethods is enabled' do
let(:cop_config) { { 'Max' => 0, 'AllowedMethods' => ['foo'] } }
it 'does not register an offense when defining an instance method' do
expect_no_offenses(<<~RUBY)
def foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when defining a class method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when using `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :foo do
bar.baz(:qux)
end
RUBY
end
end
context 'when AllowedPatterns is enabled' do
let(:cop_config) { { 'Max' => 0, 'AllowedPatterns' => [/foo/] } }
it 'does not register an offense when defining an instance method' do
expect_no_offenses(<<~RUBY)
def foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when defining a class method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when using `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :foo do
bar.baz(:qux)
end
RUBY
end
end
end
context 'when CountRepeatedAttributes is `false`' do
let(:cop_config) { { 'Max' => 0, 'CountRepeatedAttributes' => false } }
it 'does not count repeated attributes' do
expect_offense(<<~RUBY)
def foo
^^^^^^^ Assignment Branch Condition size for `foo` is too high. [<0, 1, 0> 1/0]
bar
self.bar
bar
end
RUBY
end
end
context 'when CountRepeatedAttributes is `true`' do
let(:cop_config) { { 'Max' => 0, 'CountRepeatedAttributes' => true } }
it 'counts repeated attributes' do
expect_offense(<<~RUBY)
def foo
^^^^^^^ Assignment Branch Condition size for `foo` is too high. [<0, 3, 0> 3/0]
bar
self.bar
bar
end
RUBY
end
end
end
context 'when Max is 2' do
let(:cop_config) { { 'Max' => 2 } }
it 'accepts two assignments' do
expect_no_offenses(<<~RUBY)
def method_name
x = 1
y = 2
end
RUBY
end
end
context 'when Max is 2.3' do
let(:cop_config) { { 'Max' => 2.3 } }
it 'accepts a total score of 2.24' do
expect_no_offenses(<<~RUBY)
def method_name
y = 1 if y == 1
end
RUBY
end
end
{
1.3 => '<1, 1, 4> 4.24/1.3', # no more than 2 decimals reported
10.3 => '<10, 10, 40> 42.43/10.3',
100.321 => '<100, 100, 400> 424.3/100.3', # 4 significant digits,
# so only 1 decimal here
1000.3 => '<1000, 1000, 4000> 4243/1000'
}.each do |max, presentation|
context "when Max is #{max}" do
let(:cop_config) { { 'Max' => max } }
it "reports size and max as #{presentation}" do
# Build an amount of code large enough to register an offense.
code = [' x = Hash.new if 1 == 1 || 2 == 2'] * max
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Assignment Branch Condition size for `method_name` is too high. [#{presentation}]
#{code.join("\n ")}
end
RUBY
expect_no_corrections
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/metrics/perceived_complexity_spec.rb | spec/rubocop/cop/metrics/perceived_complexity_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::PerceivedComplexity, :config do
context 'when Max is 1' do
let(:cop_config) { { 'Max' => 1 } }
it 'accepts a method with no decision points' do
expect_no_offenses(<<~RUBY)
def method_name
call_foo
end
RUBY
end
it 'accepts an empty method' do
expect_no_offenses(<<~RUBY)
def method_name
end
RUBY
end
it 'accepts an empty `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :method_name do
end
RUBY
end
it 'accepts complex code outside of methods' do
expect_no_offenses(<<~RUBY)
def method_name
call_foo
end
if first_condition then
call_foo if second_condition && third_condition
call_bar if fourth_condition || fifth_condition
end
RUBY
end
it 'registers an offense for an if modifier' do
expect_offense(<<~RUBY)
def self.method_name
^^^^^^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
call_foo if some_condition
end
RUBY
end
it 'registers an offense for an unless modifier' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
call_foo unless some_condition
end
RUBY
end
it 'registers an offense for elsif and else blocks' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [4/1]
if first_condition then
call_foo
elsif second_condition then
call_bar
else
call_bam
end
end
RUBY
end
it 'registers an offense for a ternary operator' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
value = some_condition ? 1 : 2
end
RUBY
end
it 'registers an offense for a while block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
while some_condition do
call_foo
end
end
RUBY
end
it 'registers an offense for an until block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
until some_condition do
call_foo
end
end
RUBY
end
it 'registers an offense for a for block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
for i in 1..2 do
call_method
end
end
RUBY
end
it 'registers an offense for a rescue block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
begin
call_foo
rescue Exception
call_bar
end
end
RUBY
end
it 'registers an offense for a case/when block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [3/1]
case value
when 1 then call_foo_1
when 2 then call_foo_2
when 3 then call_foo_3
when 4 then call_foo_4
end
end
RUBY
end
it 'registers an offense for a case/when block without an expression after case' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [3/1]
case
when value == 1
call_foo
when value == 2
call_bar
end
end
RUBY
end
it 'counts else in a case with no argument' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [4/1]
case
when value == 1
call_foo
when value == 2
call_bar
else
call_baz
end
end
RUBY
end
it 'registers an offense for &&' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
call_foo && call_bar
end
RUBY
end
it 'registers an offense for and' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
call_foo and call_bar
end
RUBY
end
it 'registers an offense for ||' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
call_foo || call_bar
end
RUBY
end
it 'registers an offense for or' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
call_foo or call_bar
end
RUBY
end
it 'deals with nested if blocks containing && and ||' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [6/1]
if first_condition then
call_foo if second_condition && third_condition
call_bar if fourth_condition || fifth_condition
end
end
RUBY
end
it 'counts only a single method' do
expect_offense(<<~RUBY)
def method_name_1
^^^^^^^^^^^^^^^^^ Perceived complexity for `method_name_1` is too high. [2/1]
call_foo if some_condition
end
def method_name_2
^^^^^^^^^^^^^^^^^ Perceived complexity for `method_name_2` is too high. [2/1]
call_foo if some_condition
end
RUBY
end
it 'registers an offense for a `define_method`' do
expect_offense(<<~RUBY)
define_method :method_name do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
call_foo if some_condition
end
RUBY
end
it 'does not count unknown block calls' do
expect_no_offenses(<<~RUBY)
def method_name
bar.baz(:qux) do |x|
raise x
end
end
RUBY
end
it 'counts known iterating block' do
expect_offense(<<~RUBY)
def method_name
^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [2/1]
ary.each do |x|
foo(x)
end
end
RUBY
end
end
context 'when AllowedMethods is enabled' do
let(:cop_config) { { 'Max' => 0, 'AllowedMethods' => ['foo'] } }
it 'does not register an offense when defining an instance method' do
expect_no_offenses(<<~RUBY)
def foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when defining a class method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when using `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :foo do
bar.baz(:qux)
end
RUBY
end
end
context 'when AllowedPatterns is enabled' do
let(:cop_config) { { 'Max' => 0, 'AllowedPatterns' => [/foo/] } }
it 'does not register an offense when defining an instance method' do
expect_no_offenses(<<~RUBY)
def foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when defining a class method' do
expect_no_offenses(<<~RUBY)
def self.foo
bar.baz(:qux)
end
RUBY
end
it 'does not register an offense when using `define_method`' do
expect_no_offenses(<<~RUBY)
define_method :foo do
bar.baz(:qux)
end
RUBY
end
end
context 'when Max is 2' do
let(:cop_config) { { 'Max' => 2 } }
it 'counts stupid nested if and else blocks' do
expect_offense(<<~RUBY)
def method_name # 1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Perceived complexity for `method_name` is too high. [7/2]
if first_condition then # 2
call_foo
else # 3
if second_condition then # 4
call_bar
else # 5
call_bam if third_condition # 6
end
call_baz if fourth_condition # 7
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/metrics/utils/code_length_calculator_spec.rb | spec/rubocop/cop/metrics/utils/code_length_calculator_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::Utils::CodeLengthCalculator do
describe '#calculate' do
context 'when method' do
it 'calculates method length' do
source = parse_source(<<~RUBY)
def test
a = 1
# a = 2
a = [
3,
4
]
end
RUBY
length = described_class.new(source.ast, source).calculate
expect(length).to eq(5)
end
it 'does not count blank lines' do
source = parse_source(<<~RUBY)
def test
a = 1
a = [
3,
4
]
end
RUBY
length = described_class.new(source.ast, source).calculate
expect(length).to eq(5)
end
it 'counts comments if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
# a = 2
a = [
3,
4
]
end
RUBY
length = described_class.new(source.ast, source, count_comments: true).calculate
expect(length).to eq(6)
end
it 'folds arrays if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
a = [
2,
3
]
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[array]).calculate
expect(length).to eq(2)
end
it 'folds hashes if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
a = {
foo: :bar,
baz: :quux
}
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(2)
end
it 'folds hashes as method args if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
foo({
foo: :bar,
baz: :quux
})
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(2)
end
it 'folds multiline hashes without braces as method args if asked' do
source = parse_source(<<~RUBY)
def test
foo(foo: :bar,
baz: :quux)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'folds multiline hashes with line break after it as method args if asked' do
source = parse_source(<<~RUBY)
def test
foo(foo: :bar,
baz: :quux
)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'folds multiline hashes with line break before it as method args if asked' do
source = parse_source(<<~RUBY)
def test
foo(
foo: :bar,
baz: :quux)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'folds hashes without braces as the one of method args if asked' do
source = parse_source(<<~RUBY)
def test
foo(foo, foo: :bar,
baz: :quux)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'counts single line correctly if asked folding' do
source = parse_source(<<~RUBY)
def test
foo(foo: :bar, baz: :quux)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'counts single line without parentheses correctly if asked folding' do
source = parse_source(<<~RUBY)
def test
foo foo: :bar, baz: :quux
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'counts single line hash with line breaks correctly if asked folding' do
source = parse_source(<<~RUBY)
def test
foo(
foo: :bar, baz: :quux
)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'folds hashes with comment if asked' do
source = parse_source(<<~RUBY)
def test
foo(
# foo: :bar,
baz: :quux
)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(1)
end
it 'counts single line hash as the one of method args if asked folding' do
source = parse_source(<<~RUBY)
def test
foo(
bar,
baz: :quux
)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(4)
end
it 'counts single line hash as the one of method args with safe navigation operator if asked folding' do
source = parse_source(<<~RUBY)
def test
foo&.bar(
baz,
qux: :quux
)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(4)
end
it 'counts single line hash with other args correctly if asked folding' do
source = parse_source(<<~RUBY)
def test
foo(
{ foo: :bar },
bar, baz
)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(4)
end
it 'folds hashes as method kwargs if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
foo(
foo: :bar,
baz: :quux
)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(2)
end
it 'folds heredocs if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
a = <<~HERE
Lorem
ipsum
dolor
HERE
a = 3
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[heredoc]).calculate
expect(length).to eq(3)
end
it 'folds method calls if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
foo(
1,
2,
3
)
obj&.foo(
1,
2
)
foo(1)
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[method_call]).calculate
expect(length).to eq(4)
end
it 'folds method calls with heredocs if asked' do
source = parse_source(<<~RUBY)
def test
a = 1
foo <<~HERE, <<~THERE
2
3
4
HERE
5
6
7
THERE
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[method_call]).calculate
expect(length).to eq(2)
end
end
context 'when class' do
it 'calculates class length' do
source = parse_source(<<~RUBY)
class Test
a = 1
# a = 2
a = 3
end
RUBY
length = described_class.new(source.ast, source).calculate
expect(length).to eq(2)
end
it 'calculates singleton class length' do
source = parse_source(<<~RUBY)
class << self
a = 1
# a = 2
a = 3
end
RUBY
length = described_class.new(source.ast, source).calculate
expect(length).to eq(2)
end
it 'does not count blank lines' do
source = parse_source(<<~RUBY)
class Test
a = 1
a = 3
end
RUBY
length = described_class.new(source.ast, source).calculate
expect(length).to eq(2)
end
it 'counts comments if asked' do
source = parse_source(<<~RUBY)
class Test
a = 1
# a = 2
a = 3
end
RUBY
length = described_class.new(source.ast, source, count_comments: true).calculate
expect(length).to eq(3)
end
it 'folds arrays if asked' do
source = parse_source(<<~RUBY)
class Test
a = 1
a = [
2,
3
]
def test
a = 1
a = [
2
]
end
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[array]).calculate
expect(length).to eq(6)
end
it 'folds hashes if asked' do
source = parse_source(<<~RUBY)
class Test
a = 1
a = {
foo: :bar,
baz: :quux
}
def test
a = 1
a = {
foo: :bar
}
end
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[hash]).calculate
expect(length).to eq(6)
end
it 'folds heredocs if asked' do
source = parse_source(<<~RUBY)
class Test
a = 1
a = <<~HERE
Lorem
ipsum
dolor
HERE
def test
a = 1
a = <<~HERE
Lorem
ipsum
HERE
a = 3
end
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[heredoc]).calculate
expect(length).to eq(7)
end
it 'does not count lines of inner classes' do
source = parse_source(<<~RUBY)
class Test
a = 1
a = 2
a = [
3
]
class Inner
a = 1
# a = 2
a = [
3,
4
]
end
end
RUBY
length = described_class.new(source.ast, source, foldable_types: %i[array]).calculate
expect(length).to eq(3)
end
end
it 'raises when unknown foldable type is passed' do
source = parse_source(<<~RUBY)
def test
a = 1
end
RUBY
warning = 'Unknown foldable type: :send. ' \
'Valid foldable types are: array, hash, heredoc, method_call.'
expect do
described_class.new(source.ast, source, foldable_types: %i[send]).calculate
end.to raise_error(RuboCop::Warning, warning)
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/metrics/utils/abc_size_calculator_spec.rb | spec/rubocop/cop/metrics/utils/abc_size_calculator_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Metrics::Utils::AbcSizeCalculator do
describe '#calculate' do
subject(:vector) do
described_class.calculate(node,
discount_repeated_attributes: discount_repeated_attributes).last
end
let(:discount_repeated_attributes) { false }
let(:node) { parse_source(source).ast }
context 'multiple calls with return' do
let(:source) { <<~RUBY }
def method_name
return x, y, z
end
RUBY
it { is_expected.to eq '<0, 3, 0>' }
end
context 'with +=' do
let(:source) { <<~RUBY }
def method_name
x = nil
x += 1
end
RUBY
it { is_expected.to eq '<2, 0, 0>' }
end
context 'with += for setters' do
let(:source) { <<~RUBY }
def method_name
foo.bar += 1
end
RUBY
it { is_expected.to eq '<1, 2, 0>' }
end
context 'with ||=' do
let(:source) { <<~RUBY }
def method_name
x = nil
x ||= 1
end
RUBY
it { is_expected.to eq '<2, 0, 1>' }
end
context 'with ||= on a constant' do
let(:source) { <<~RUBY }
def method_name
self::FooModule ||= Mod
end
RUBY
it { is_expected.to eq '<1, 0, 1>' }
end
context 'with &&=' do
let(:source) { <<~RUBY }
def method_name
x = nil
x &&= 1
end
RUBY
it { is_expected.to eq '<2, 0, 1>' }
end
context 'assignment with ternary operator' do
let(:source) { <<~RUBY }
def method_name
a = b ? c : d
e = f ? g : h
end
RUBY
it { is_expected.to eq '<2, 6, 2>' }
end
context 'with a block' do
let(:source) { <<~RUBY }
def method_name
x = foo # <1, 1, 0>
bar do # <1, 2, 0> (+1 for bar, 0 for non-empty block)
y = baz # <2, 3, 0>
end
end
RUBY
it { is_expected.to eq '<2, 3, 0>' }
end
context 'same but with 7 arguments' do
let(:source) { <<~RUBY }
def method_name
x = foo
bar do |a, (b, c), d = 42, *e, f: 42, **g|
y = baz
end
end
RUBY
it { is_expected.to eq '<9, 3, 0>' }
end
context 'with unused assignments' do
let(:source) { <<~RUBY }
def method_name
_, _ignored, foo, = [1, 2, 3] # <1, 0, 0>
bar do |_, (only_real_assignment, _unused), *, **| # <+1, 1, 0>
only_real_assignment
end
end
RUBY
it { is_expected.to eq '<2, 1, 0>' }
end
context 'with a known iterating block' do
let(:source) { <<~RUBY }
def method_name
x = foo # <1, 1, 0>
x.each do # <1, 2, 1> (+1 B for each, +1 C iterating block)
y = baz # <2, 3, 1>
end
x.map(&:to_s) # <2, 4, 2> (+1 B for map, +1 C iterating block)
end
RUBY
it { is_expected.to eq '<2, 4, 2>' }
end
context 'method with arguments' do
let(:source) { <<~RUBY }
def method_name(a = 0, *b, c: 42, **d)
end
RUBY
it { is_expected.to eq '<4, 0, 0>' }
end
context 'with .foo =' do
let(:source) { <<~RUBY }
def method_name
foo.bar = 42
end
RUBY
it { is_expected.to eq '<1, 2, 0>' }
end
context 'with []=' do
let(:source) { <<~RUBY }
def method_name
x = {}
x[:hello] = 'world'
end
RUBY
it { is_expected.to eq '<2, 1, 0>' }
end
context 'multiple assignment' do
let(:source) { <<~RUBY }
def method_name
a, b, c = d
end
RUBY
it { is_expected.to eq '<3, 1, 0>' }
end
context 'multiple assignment with method setters' do
let(:source) { <<~RUBY }
def method_name
self.a, foo.b, bar[42] = nil
end
RUBY
it { is_expected.to eq '<3, 5, 0>' }
end
context 'equivalent to multiple assignment with method setters' do
let(:source) { <<~RUBY }
def method_name
self.a = nil # 1, 1, 0
foo.b = nil # 1, +2, 0
bar[42] = nil # 1, +2, 0
end
RUBY
it { is_expected.to eq '<3, 5, 0>' }
end
context 'if and arithmetic operations' do
let(:source) { <<~RUBY }
def method_name
a = b ? c : d
if a
a
else
e = f ? g : h
# The * and - are counted as branches because they are parsed as
# `send` nodes. YARV might optimize them, but to `parser` they
# are methods.
e * 2.4 - 781.0
end
end
RUBY
it { is_expected.to eq '<2, 8, 4>' }
end
context 'same with extra condition' do
let(:source) { <<~RUBY }
def method_name
a = b ? c : d
if a < b
a
else
e = f ? g : h
# The * and - are counted as branches because they are parsed as
# `send` nodes. YARV might optimize them, but to `parser` they
# are methods.
e * 2.4 - 781.0
end
end
RUBY
it { is_expected.to eq '<2, 9, 5>' }
end
context 'with &.foo' do
let(:source) { <<~RUBY }
def method_name
method&.foo
method&.foo
end
RUBY
it { is_expected.to eq '<0, 4, 2>' }
context 'with repeated lvar receivers' do
let(:source) { <<~RUBY }
def foo
var = other = 1 # 2, 0, 0
var&.do_something # +1, +1
var&.dont_count_this_as_condition # +1, +0
var = 2 # +1
var&.start_counting_again # +1, +1
var&.dont_count_this_as_condition_either # +1, +0
other&.do_something # +1, +1
end
RUBY
it { is_expected.to eq '<3, 5, 3>' }
end
end
context 'elsif vs else if' do
context 'elsif' do
let(:source) { <<~RUBY }
def method_name
if foo # 0, 1, 1
bar # 0, 2, 1
elsif baz # 0, 3, 2
qux # 0, 4, 2
else # 0, 4, 3
foobar # 0, 5, 3
end
end
RUBY
it { is_expected.to eq '<0, 5, 3>' }
end
context 'else if' do
let(:source) { <<~RUBY }
def method_name
if foo # 0, 1, 1
bar # 0, 2, 1
else # 0, 2, 2
if baz # 0, 3, 3
qux # 0, 4, 3
else # 0, 4, 4
foobar # 0, 5, 4
end
end
end
RUBY
it { is_expected.to eq '<0, 5, 4>' }
end
end
context 'with a for' do
let(:source) { <<~RUBY }
def method_name
for x in 0..5 # 2, 0, 1
puts x # +1
end
end
RUBY
it { is_expected.to eq '<2, 1, 1>' }
end
context 'with a yield' do
let(:source) { <<~RUBY }
def method_name
yield 42
end
RUBY
it { is_expected.to eq '<0, 1, 0>' }
end
context 'when counting repeated calls' do
let(:discount_repeated_attributes) { false }
let(:source) { <<~RUBY }
def method_name(var)
var.foo
var.foo
bar
bar
end
RUBY
it { is_expected.to eq '<1, 4, 0>' }
end
context 'when discounting repeated calls' do
let(:discount_repeated_attributes) { true }
context 'when root receiver is a var' do
let(:source) { <<~RUBY }
def method_name(var) # 1, 0, 0
var.foo.bar.baz # +3
var.foo.bar.qux # +1
var.foo.bar = 42 # +1 +1 (partial invalidation)
var.foo # +0
var.foo.bar # +1
var.foo.bar.baz # +1
var = 42 # +1 (complete invalidation)
var.foo.bar # +2
end
RUBY
it { is_expected.to eq '<3, 9, 0>' }
end
context 'when root receiver is self/nil' do
let(:source) { <<~RUBY }
def method_name # 0, 0, 0
self.foo.bar.baz # +3
foo.bar.qux # +1
foo.bar = 42 # +1 +1 (partial invalidation)
foo # +0
self.foo.bar # +1
foo&.bar.baz # +1 (C += 0 since `csend` treated as `send`)
self.foo ||= 42 # +1 +1 +1 (complete invalidation)
self.foo.bar # +2
end
RUBY
it { is_expected.to eq '<2, 9, 1>' }
end
context 'when some calls have arguments' do
let(:source) { <<~RUBY }
def method_name(var) # 1, 0, 0
var.foo(42).bar # +2
var.foo(42).bar # +2
var.foo.bar # +2
var.foo.bar # +0
var.foo.bar(42) # +1
end
RUBY
it { is_expected.to eq '<1, 7, 0>' }
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/internal_affairs/redundant_described_class_as_subject_spec.rb | spec/rubocop/cop/internal_affairs/redundant_described_class_as_subject_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::RedundantDescribedClassAsSubject, :config do
it 'registers an offense when using `subject(:cop)` and `:config` is not specified in `describe`' do
expect_offense(<<~RUBY)
RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition do
subject(:cop) { described_class.new(config) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `subject` and specify `:config` in `describe`.
let(:config) { RuboCop::Config.new }
end
RUBY
expect_correction(<<~RUBY)
RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition, :config do
let(:config) { RuboCop::Config.new }
end
RUBY
end
it 'registers an offense when using `subject(:cop)` and `:config` is already specified in `describe`' do
expect_offense(<<~RUBY)
RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition, :config do
subject(:cop) { described_class.new(config) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `subject`.
let(:config) { RuboCop::Config.new }
end
RUBY
expect_correction(<<~RUBY)
RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition, :config do
let(:config) { RuboCop::Config.new }
end
RUBY
end
it 'registers an offense when using `subject(:cop)` with no argument `described_class.new` and `:config` is specified' do
expect_offense(<<~RUBY)
RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition, :config do
subject(:cop) { described_class.new }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `subject`.
let(:config) { RuboCop::Config.new }
end
RUBY
expect_correction(<<~RUBY)
RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition, :config do
let(:config) { RuboCop::Config.new }
end
RUBY
end
it 'does not register an offense when using `subject(:cop)` with multiple arguments to `described_class.new`' do
expect_no_offenses(<<~RUBY)
RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition do
subject(:cop) { described_class.new(config, options) }
end
RUBY
end
it 'registers an offense without `describe` DSL' do
expect_offense(<<~RUBY)
shared_context "shared cop context" do
subject(:cop) { described_class.new }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the redundant `subject`.
let(:config) { RuboCop::Config.new }
end
RUBY
expect_correction(<<~RUBY)
shared_context "shared cop context" do
let(:config) { RuboCop::Config.new }
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/internal_affairs/redundant_let_rubocop_config_new_spec.rb | spec/rubocop/cop/internal_affairs/redundant_let_rubocop_config_new_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::RedundantLetRuboCopConfigNew, :config do
it 'registers an offense when using `let(:config)` and `:config` is not specified in `describe`' do
expect_offense(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma do
subject(:cop) { described_class.new(config) }
let(:config) { RuboCop::Config.new }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove `let` that is `RuboCop::Config.new` with no arguments and specify `:config` in `describe`.
end
RUBY
expect_correction(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma, :config do
subject(:cop) { described_class.new(config) }
end
RUBY
end
it 'registers an offense when using `let(:config)` and `:config` is already specified in `describe`' do
expect_offense(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma, :config do
subject(:cop) { described_class.new(config) }
let(:config) { RuboCop::Config.new }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove `let` that is `RuboCop::Config.new` with no arguments.
end
RUBY
expect_correction(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma, :config do
subject(:cop) { described_class.new(config) }
end
RUBY
end
it 'registers an offense when using `let(:config)` with no argument `RuboCop::Config.new` and `:config` is specified' do
expect_offense(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma, :config do
subject(:cop) { described_class.new }
let(:config) { RuboCop::Config.new }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove `let` that is `RuboCop::Config.new` with no arguments.
end
RUBY
expect_correction(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma, :config do
subject(:cop) { described_class.new }
end
RUBY
end
it 'registers an offense when using `let(:config) { RuboCop::Config.new(described_class.badge.to_s => cop_config) }` ' \
'and `:config` is specified' do
expect_offense(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma, :config do
subject(:cop) { described_class.new(config) }
let(:config) { RuboCop::Config.new(described_class.badge.to_s => cop_config) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove `let` that is `RuboCop::Config.new` with no arguments.
let(:cop_config) { { 'Parameter' => 'Value' } }
end
RUBY
expect_correction(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma, :config do
subject(:cop) { described_class.new(config) }
let(:cop_config) { { 'Parameter' => 'Value' } }
end
RUBY
end
it 'does not register an offense when using `let(:config)` with arguments to `RuboCop::Config.new`' do
expect_no_offenses(<<~RUBY)
RSpec.describe RuboCop::Cop::Layout::SpaceAfterComma do
let(:config) { RuboCop::Config.new('Layout/SpaceInsideHashLiteralBraces' => brace_config) }
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/internal_affairs/style_detected_api_use_spec.rb | spec/rubocop/cop/internal_affairs/style_detected_api_use_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::StyleDetectedApiUse, :config do
it 'registers an offense when correct_style_detected is used without a negative *_style_detected follow up' do
expect_offense(<<~RUBY)
def on_send(node)
^{} `correct_style_detected` method called without calling a negative `*_style_detected` method.
if offense?
add_offense(node)
else
correct_style_detected
end
end
RUBY
end
it 'registers an offense when correct_style_detected is used in a conditional expression' do
expect_offense(<<~RUBY)
def on_send(node)
return if correct_style_detected
^^^^^^^^^^^^^^^^^^^^^^ `*_style_detected` method called in conditional.
add_offense(node)
opposite_style_detected
end
RUBY
end
%i[opposite_style_detected unexpected_style_detected
ambiguous_style_detected conflicting_styles_detected
unrecognized_style_detected
no_acceptable_style!].each do |negative_style_detected_method|
it "registers an offense when #{negative_style_detected_method} is used in a conditional expression" do
expect_offense(<<~RUBY)
def on_send(node)
return add_offense(node) if #{negative_style_detected_method}
#{'^' * negative_style_detected_method.to_s.length} `*_style_detected` method called in conditional.
correct_style_detected
end
RUBY
end
it "registers an offense when #{negative_style_detected_method} is used without a correct_style_detected follow up" do
expect_offense(<<~RUBY)
def on_send(node)
^{} negative `*_style_detected` methods called without calling `correct_style_detected` method.
return unless offense?
add_offense(node)
#{negative_style_detected_method}
end
RUBY
end
it "does not register an offense when correct_style_detected and #{negative_style_detected_method} are both used" do
expect_no_offenses(<<~RUBY)
def on_send(node)
if offense?
add_offense(node)
#{negative_style_detected_method}
else
correct_style_detected
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/internal_affairs/numblock_handler_spec.rb | spec/rubocop/cop/internal_affairs/numblock_handler_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::NumblockHandler, :config do
it 'registers an offense for cops with forgotten numblock handlers' do
expect_offense <<~RUBY
class Cop < Base
def on_block(node)
^^^^^^^^^^^^^^^^^^ Define on_numblock to handle blocks with numbered arguments.
end
end
RUBY
end
it 'does not register an offense for cops with on_numblock alias' do
expect_no_offenses <<~RUBY
class Cop < Base
def on_block(node)
end
alias on_numblock on_block
end
RUBY
end
it 'does not register an offense for cops with on_numblock alias_method' do
expect_no_offenses <<~RUBY
class Cop < Base
def on_block(node)
end
alias_method :on_numblock, :on_block
end
RUBY
end
it 'does not register an offense for cops with on_numblock method' do
expect_no_offenses <<~RUBY
class Cop < Base
def on_block(node)
end
def on_numblock(node)
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/internal_affairs/offense_location_keyword_spec.rb | spec/rubocop/cop/internal_affairs/offense_location_keyword_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::OffenseLocationKeyword, :config do
context 'when `node.loc.selector` is passed' do
it 'registers an offense' do
expect_offense(<<~RUBY)
add_offense(node, location: node.loc.selector)
^^^^^^^^^^^^^^^^^ Use `:selector` as the location argument to `#add_offense`.
RUBY
expect_correction(<<~RUBY)
add_offense(node, location: :selector)
RUBY
end
it 'registers an offense if message argument is passed' do
expect_offense(<<~RUBY)
add_offense(
node,
message: 'message',
location: node.loc.selector
^^^^^^^^^^^^^^^^^ Use `:selector` as the location argument to `#add_offense`.
)
RUBY
expect_correction(<<~RUBY)
add_offense(
node,
message: 'message',
location: :selector
)
RUBY
end
end
it 'does not register an offense when the `loc` is on a child node' do
expect_no_offenses(<<~RUBY, 'example_cop.rb')
add_offense(node, location: node.arguments.loc.selector)
RUBY
end
it 'does not register an offense when the `loc` is on a different node' do
expect_no_offenses(<<~RUBY, 'example_cop.rb')
add_offense(node, location: other_node.loc.selector)
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/internal_affairs/empty_line_between_expect_offense_and_correction_spec.rb | spec/rubocop/cop/internal_affairs/empty_line_between_expect_offense_and_correction_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::EmptyLineBetweenExpectOffenseAndCorrection, :config do
it 'registers and corrects an offense when using no empty line between `expect_offense` and `expect_correction` ' \
'with heredoc argument' do
expect_offense(<<~RUBY)
expect_offense(<<~CODE)
bad_method
CODE
^^^^ Add empty line between `expect_offense` and `expect_correction`.
expect_correction(<<~CODE)
good_good
CODE
RUBY
expect_correction(<<~RUBY)
expect_offense(<<~CODE)
bad_method
CODE
expect_correction(<<~CODE)
good_good
CODE
RUBY
end
it 'registers and corrects an offense when using no empty line between `expect_offense` and `expect_correction`' \
'with variable argument' do
expect_offense(<<~RUBY)
expect_offense(code)
^^^^^^^^^^^^^^^^^^^^ Add empty line between `expect_offense` and `expect_correction`.
expect_correction(code)
RUBY
expect_correction(<<~RUBY)
expect_offense(code)
expect_correction(code)
RUBY
end
it 'registers and corrects an offense when using no empty line between `expect_offense` and `expect_no_corrections`' do
expect_offense(<<~RUBY)
expect_offense('bad_method')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line between `expect_offense` and `expect_no_corrections`.
expect_no_corrections
RUBY
expect_correction(<<~RUBY)
expect_offense('bad_method')
expect_no_corrections
RUBY
end
it 'does not register an offense when using only `expect_offense`' do
expect_no_offenses(<<~RUBY)
expect_offense(<<~CODE)
bad_method
CODE
RUBY
end
it 'does not register an offense when using empty line between `expect_offense` and `expect_correction` ' \
'with heredoc argument' do
expect_no_offenses(<<~RUBY)
expect_offense(<<~CODE)
bad_method
CODE
expect_correction(<<~CODE)
good_method
CODE
RUBY
end
it 'does not register an offense when using empty line between `expect_offense` and `expect_correction`' \
'with variable argument' do
expect_no_offenses(<<~RUBY)
expect_offense(bad_method)
expect_correction(good_method)
RUBY
end
it 'does not register an offense when using empty line between `expect_offense` and `expect_no_corrections`' do
expect_no_offenses(<<~RUBY)
expect_offense('bad_method')
expect_no_corrections
RUBY
end
it 'does not register an offense for `expect_offense` with unexpected syntax' do
expect_no_offenses(<<~RUBY)
expect_offense << 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/internal_affairs/useless_message_assertion_spec.rb | spec/rubocop/cop/internal_affairs/useless_message_assertion_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::UselessMessageAssertion, :config do
it 'registers an offense for specs that assert using the MSG' do
expect_offense(<<~RUBY, 'example_spec.rb')
it 'uses described_class::MSG to specify the expected message' do
inspect_source(cop, 'foo')
expect(cop.messages).to eq([described_class::MSG])
^^^^^^^^^^^^^^^^^^^^ Do not specify cop behavior using `described_class::MSG`.
end
RUBY
end
it 'registers an offense for specs that expect offense using the MSG' do
expect_offense(<<~'RUBY', 'example_spec.rb')
it 'uses described_class::MSG to expect offense' do
expect_offense(<<-SOURCE.strip_indent('|'))
| foo
| ^^^ #{described_class::MSG}
^^^^^^^^^^^^^^^^^^^^ Do not specify cop behavior using `described_class::MSG`.
SOURCE
end
RUBY
end
it 'registers an offense for described_class::MSG in let' do
expect_offense(<<~RUBY, 'example_spec.rb')
let(:msg) { described_class::MSG }
^^^^^^^^^^^^^^^^^^^^ Do not specify cop behavior using `described_class::MSG`.
RUBY
end
it 'does not register an offense for an assertion about the message' do
expect_no_offenses(<<~RUBY, 'example_spec.rb')
it 'has a good message' do
expect(described_class::MSG).to eq('Good message.')
end
RUBY
end
it 'does not register an offense and no error when empty file' do
expect_no_offenses('', 'example_spec.rb')
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/internal_affairs/node_destructuring_spec.rb | spec/rubocop/cop/internal_affairs/node_destructuring_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::NodeDestructuring, :config do
context 'when destructuring using `node.children`' do
it 'registers an offense when receiver is named `node`' do
expect_offense(<<~RUBY, 'example_cop.rb')
lhs, rhs = node.children
^^^^^^^^^^^^^^^^^^^^^^^^ Use the methods provided with the node extensions instead of manually destructuring nodes.
RUBY
end
it 'registers an offense when receiver is named `send_node`' do
expect_offense(<<~RUBY, 'example_cop.rb')
lhs, rhs = send_node.children
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the methods provided with the node extensions instead of manually destructuring nodes.
RUBY
end
end
it 'registers an offense when destructuring using a splat' do
expect_offense(<<~RUBY, 'example_spec.rb')
lhs, rhs = *node
^^^^^^^^^^^^^^^^ Use the methods provided with the node extensions instead of manually destructuring nodes.
RUBY
end
it 'does not register an offense when receiver is named `array`' do
expect_no_offenses(<<~RUBY, 'example_spec.rb')
lhs, rhs = array.children
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/internal_affairs/redundant_location_argument_spec.rb | spec/rubocop/cop/internal_affairs/redundant_location_argument_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::RedundantLocationArgument, :config do
context 'when location argument is passed' do
context 'when location argument is :expression' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'example_cop.rb')
add_offense(node, location: :expression)
^^^^^^^^^^^^^^^^^^^^^ Redundant location argument to `#add_offense`.
RUBY
expect_correction(<<~RUBY)
add_offense(node)
RUBY
end
context 'when there is a message argument' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'example_cop.rb')
add_offense(node, location: :expression, message: 'message')
^^^^^^^^^^^^^^^^^^^^^ Redundant location argument to `#add_offense`.
RUBY
expect_correction(<<~RUBY)
add_offense(node, message: 'message')
RUBY
end
end
it 'removes default `location` when preceded by another keyword' do
expect_offense(<<~RUBY)
add_offense(node, message: 'foo', location: :expression)
^^^^^^^^^^^^^^^^^^^^^ Redundant location argument to `#add_offense`.
RUBY
expect_correction(<<~RUBY)
add_offense(node, message: 'foo')
RUBY
end
it 'removes default `location` surrounded by other keywords' do
expect_offense(<<~RUBY)
add_offense(
node,
severity: :error,
location: :expression,
^^^^^^^^^^^^^^^^^^^^^ Redundant location argument to `#add_offense`.
message: 'message'
)
RUBY
expect_correction(<<~RUBY)
add_offense(
node,
severity: :error,
message: 'message'
)
RUBY
end
end
context 'when location argument does not equal to :expression' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'example_cop.rb')
add_offense(node, location: :selector)
RUBY
end
end
end
context 'when location argument is not passed' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'example_cop.rb')
add_offense(node)
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/internal_affairs/cop_description_spec.rb | spec/rubocop/cop/internal_affairs/cop_description_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::CopDescription, :config do
context 'The description starts with `This cop ...`' do
it 'registers an offense and corrects if using just a verb' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Lint
# This cop checks some offenses...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Description should be started with `Checks` instead of `This cop ...`.
#
# ...
class Foo < Base
end
end
end
end
RUBY
expect_correction(<<~RUBY)
module RuboCop
module Cop
module Lint
# Checks some offenses...
#
# ...
class Foo < Base
end
end
end
end
RUBY
end
it 'registers an offense if using an auxiliary verb' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Lint
# This cop can check some offenses...
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Description should be started with a word such as verb instead of `This cop ...`.
#
# ...
class Foo < Base
end
end
end
end
RUBY
end
it 'registers an offense if the description like `This cop is ...`' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Lint
# This cop is used to...
^^^^^^^^^^^^^^^^^^^^^^ Description should be started with a word such as verb instead of `This cop ...`.
#
# ...
class Foo < Base
end
end
end
end
RUBY
end
end
context 'The description starts with a word such as verb' do
it 'does not register if the description like `Checks`' do
expect_no_offenses(<<~RUBY)
module RuboCop
module Cop
module Lint
# Checks some problem
#
# ...
class Foo < Base
end
end
end
end
RUBY
end
it 'does not register if the description starts with non-verb word' do
expect_no_offenses(<<~RUBY)
module RuboCop
module Cop
module Lint
# Either foo or bar ...
#
# ...
class Foo < Base
end
end
end
end
RUBY
end
end
it 'registers an offense if the description starts with an empty comment line' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Lint
#
^^^^^^^ Description should not start with an empty comment line.
# Checks some problem
#
# ...
class Foo < Base
end
end
end
end
RUBY
expect_correction(<<~RUBY)
module RuboCop
module Cop
module Lint
# Checks some problem
#
# ...
class Foo < Base
end
end
end
end
RUBY
end
context 'There is no description comment' do
it 'does not register offense' do
expect_no_offenses(<<~RUBY)
module RuboCop
module Cop
module Lint
class Foo < Base
end
end
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/internal_affairs/cop_enabled_spec.rb | spec/rubocop/cop/internal_affairs/cop_enabled_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::CopEnabled, :config do
context 'with .for_cop' do
it "registers an offense when using `config.for_cop(...)['Enabled']" do
expect_offense(<<~RUBY)
config.for_cop('Foo/Bar')['Enabled']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `config.cop_enabled?('Foo/Bar')` instead [...]
RUBY
expect_correction(<<~RUBY)
config.cop_enabled?('Foo/Bar')
RUBY
end
it "registers an offense when using `@config.for_cop(...)['Enabled']" do
expect_offense(<<~RUBY)
@config.for_cop('Foo/Bar')['Enabled']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `@config.cop_enabled?('Foo/Bar')` instead [...]
RUBY
expect_correction(<<~RUBY)
@config.cop_enabled?('Foo/Bar')
RUBY
end
it 'maintains existing quote style when correcting' do
expect_offense(<<~RUBY)
@config.for_cop("Foo/Bar")["Enabled"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `@config.cop_enabled?("Foo/Bar")` instead [...]
RUBY
expect_correction(<<~RUBY)
@config.cop_enabled?("Foo/Bar")
RUBY
end
it 'does not register an offense when :Enabled is a symbol' do
expect_no_offenses(<<~RUBY)
@config.for_cop('Foo/Bar')[:Enabled]
RUBY
end
end
context "when checking `*_config['Enabled']`" do
it 'registers an offense and does not correct with a method call' do
expect_offense(<<~RUBY)
return false unless argument_alignment_config['Enabled']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider replacing uses of `argument_alignment_config` with `config.for_enabled_cop`.
argument_alignment_config['EnforcedStyle'] == 'with_fixed_indentation'
RUBY
end
it 'registers an offense and does not correct with a local variable' do
expect_offense(<<~RUBY)
argument_alignment_config = config.for_cop('Layout/ArgumentAlignment')
return false unless argument_alignment_config['Enabled']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider replacing uses of `argument_alignment_config` with `config.for_enabled_cop`.
argument_alignment_config['EnforcedStyle'] == 'with_fixed_indentation'
RUBY
end
it 'registers an offense and does not correct with an instance variable' do
expect_offense(<<~RUBY)
@argument_alignment_config = config.for_cop('Layout/ArgumentAlignment')
return false unless @argument_alignment_config['Enabled']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider replacing uses of `@argument_alignment_config` with `config.for_enabled_cop`.
@argument_alignment_config['EnforcedStyle'] == 'with_fixed_indentation'
RUBY
end
it 'does not register an offense when the hash name does not end with `_config`' do
expect_no_offenses(<<~RUBY)
foo['Enabled']
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/internal_affairs/inherit_deprecated_cop_class_spec.rb | spec/rubocop/cop/internal_affairs/inherit_deprecated_cop_class_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::InheritDeprecatedCopClass, :config do
it 'registers an offense when using `Cop`' do
expect_offense(<<~RUBY)
class Foo < Cop
^^^ Use `Base` instead of `Cop`.
end
RUBY
end
it 'registers an offense when using `RuboCop::Cop::Cop`' do
expect_offense(<<~RUBY)
class Foo < RuboCop::Cop::Cop
^^^^^^^^^^^^^^^^^ Use `Base` instead of `Cop`.
end
RUBY
end
it 'does not register an offense when using `Base`' do
expect_no_offenses(<<~RUBY)
class Foo < Base
end
RUBY
end
it 'does not register an offense when not inherited super class' do
expect_no_offenses(<<~RUBY)
class 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/internal_affairs/useless_restrict_on_send_spec.rb | spec/rubocop/cop/internal_affairs/useless_restrict_on_send_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::UselessRestrictOnSend, :config do
it 'registers an offense when using `RESTRICT_ON_SEND` and not defines send callback method' do
expect_offense(<<~RUBY)
class FooCop
RESTRICT_ON_SEND = %i[bad_method].freeze
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless `RESTRICT_ON_SEND` is defined.
end
RUBY
expect_correction(<<~RUBY)
class FooCop
#{' '}
end
RUBY
end
it 'does not register an offense when using `RESTRICT_ON_SEND` and defines `on_send`' do
expect_no_offenses(<<~RUBY)
class FooCop
RESTRICT_ON_SEND = %i[bad_method].freeze
def on_send(node)
# ...
end
end
RUBY
end
it 'does not register an offense when using `RESTRICT_ON_SEND` and defines `on_send` with alias' do
expect_no_offenses(<<~RUBY)
class FooCop
RESTRICT_ON_SEND = %i[bad_method].freeze
def on_def(node)
# ...
end
alias on_send on_def
end
RUBY
end
it 'does not register an offense when using `RESTRICT_ON_SEND` and defines `on_send` with alias_method' do
expect_no_offenses(<<~RUBY)
class FooCop
RESTRICT_ON_SEND = %i[bad_method].freeze
def on_def(node)
# ...
end
alias_method :on_send, :on_def
end
RUBY
end
it 'does not register an offense when using `RESTRICT_ON_SEND` and defines `after_send`' do
expect_no_offenses(<<~RUBY)
class FooCop
RESTRICT_ON_SEND = %i[bad_method].freeze
def after_send(node)
# ...
end
end
RUBY
end
it 'does not register an offense when using `RESTRICT_ON_SEND` and defines `after_send` with alias' do
expect_no_offenses(<<~RUBY)
class FooCop
RESTRICT_ON_SEND = %i[bad_method].freeze
def after_send(node)
# ...
end
alias after_send any
end
RUBY
end
it 'does not register an offense when using `RESTRICT_ON_SEND` and defines `after_send` with alias_method' do
expect_no_offenses(<<~RUBY)
class FooCop
RESTRICT_ON_SEND = %i[bad_method].freeze
def after_send(node)
# ...
end
self.alias_method "after_send", "any"
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/internal_affairs/method_name_end_with_spec.rb | spec/rubocop/cop/internal_affairs/method_name_end_with_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::MethodNameEndWith, :config do
it 'registers an offense if there is potentially usage of `assignment_method?`' do
expect_offense(<<~RUBY)
node.method_name.to_s.end_with?('=')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `assignment_method?` instead of `method_name.to_s.end_with?('=')`.
RUBY
expect_correction(<<~RUBY)
node.assignment_method?
RUBY
end
it 'does not register an offense if `method_name` is a variable' do
expect_no_offenses(<<~RUBY)
def assignment_method?(method_name)
method_name.to_s.end_with?('=')
end
RUBY
end
it 'does not register an offense when using `method_name` without receiver' do
expect_no_offenses(<<~RUBY)
method_name.to_s.end_with?('=')
RUBY
end
it 'registers an offense if there is potentially usage of `predicate_method?`' do
expect_offense(<<~RUBY)
node.method_name.to_s.end_with?('?')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `predicate_method?` instead of `method_name.to_s.end_with?('?')`.
RUBY
expect_correction(<<~RUBY)
node.predicate_method?
RUBY
end
it 'registers an offense if there is potentially usage of `bang_method?`' do
expect_offense(<<~RUBY)
node.method_name.to_s.end_with?('!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `bang_method?` instead of `method_name.to_s.end_with?('!')`.
RUBY
expect_correction(<<~RUBY)
node.bang_method?
RUBY
end
it 'registers an offense if there is potentially usage of `bang_method?` with safe navigation operator' do
expect_offense(<<~RUBY)
node.method_name&.to_s&.end_with?('!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `bang_method?` instead of `method_name&.to_s&.end_with?('!')`.
RUBY
expect_correction(<<~RUBY)
node.bang_method?
RUBY
end
it 'does not register offense if argument for end_with? is some other string' do
expect_no_offenses(<<~RUBY)
node.method_name.to_s.end_with?('_foo')
RUBY
end
context 'Ruby >= 2.7', :ruby27 do
it 'registers an offense if method_name is symbol' do
expect_offense(<<~RUBY)
node.method_name.end_with?('=')
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `assignment_method?` instead of `method_name.end_with?('=')`.
RUBY
expect_correction(<<~RUBY)
node.assignment_method?
RUBY
end
it 'registers an offense if method_name is symbol with safe navigation operator' do
expect_offense(<<~RUBY)
node&.method_name&.end_with?('=')
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `assignment_method?` instead of `method_name&.end_with?('=')`.
RUBY
expect_correction(<<~RUBY)
node&.assignment_method?
RUBY
end
it 'registers an offense if argument for Symbol#end_with? is \'?\'' do
expect_offense(<<~RUBY)
node.method_name.end_with?('?')
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `predicate_method?` instead of `method_name.end_with?('?')`.
RUBY
expect_correction(<<~RUBY)
node.predicate_method?
RUBY
end
it 'registers an offense if argument for Symbol#end_with? is \'?\' with safe navigation operator' do
expect_offense(<<~RUBY)
node.method_name&.end_with?('?')
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `predicate_method?` instead of `method_name&.end_with?('?')`.
RUBY
expect_correction(<<~RUBY)
node.predicate_method?
RUBY
end
it 'registers an offense if argument for Symbol#end_with? is \'!\'' do
expect_offense(<<~RUBY)
node.method_name.end_with?('!')
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `bang_method?` instead of `method_name.end_with?('!')`.
RUBY
expect_correction(<<~RUBY)
node.bang_method?
RUBY
end
it 'registers an offense if argument for Symbol#end_with? is \'!\' with safe navigation operator' do
expect_offense(<<~RUBY)
node.method_name&.end_with?('!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `bang_method?` instead of `method_name&.end_with?('!')`.
RUBY
expect_correction(<<~RUBY)
node.bang_method?
RUBY
end
it 'does not register offense if argument for Symbol#end_with? is some other string' do
expect_no_offenses(<<~RUBY)
node.method_name.end_with?('_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/internal_affairs/undefined_config_spec.rb | spec/rubocop/cop/internal_affairs/undefined_config_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::UndefinedConfig, :config, :isolated_environment do
include FileHelper
before do
create_file('config/default.yml', <<~YAML)
Test/Foo:
Defined: true
X/Y/Z:
Defined: true
YAML
stub_const('RuboCop::Cop::InternalAffairs::UndefinedConfig::CONFIG',
RuboCop::ConfigLoader.load_yaml_configuration('config/default.yml'))
end
it 'does not register an offense for implicit configuration keys' do
expect_no_offenses(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Base
def configured?
#{described_class::ALLOWED_CONFIGURATIONS.map { "cop_config['#{_1}']" }.join("\n ")}
end
end
end
end
end
RUBY
end
it 'registers an offense when the cop has no configuration at all' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Test
class Bar < Base
def configured?
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Bar` in `config/default.yml`.
end
end
end
end
end
RUBY
end
it 'registers an offense when the cop is not within the `RuboCop::Cop` namespace' do
expect_offense(<<~RUBY)
module Test
class Foo < Base
def configured?
cop_config['Defined']
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
RUBY
end
it 'registers an offense when the cop inherits `Cop::Base`' do
expect_offense(<<~RUBY)
module Test
class Foo < Cop::Base
def configured?
cop_config['Defined']
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
RUBY
end
it 'registers an offense when the cop inherits `RuboCop::Cop::Base`' do
expect_offense(<<~RUBY)
module Test
class Foo < RuboCop::Cop::Base
def configured?
cop_config['Defined']
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
RUBY
end
it 'registers an offense when the cop inherits `::RuboCop::Cop::Base`' do
expect_offense(<<~RUBY)
module Test
class Foo < ::RuboCop::Cop::Base
def configured?
cop_config['Defined']
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
RUBY
end
context 'element lookup' do
it 'does not register an offense for defined configuration keys' do
expect_no_offenses(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Base
def configured?
cop_config['Defined']
end
end
end
end
end
RUBY
end
it 'registers an offense for missing configuration keys' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Base
def configured?
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
end
end
RUBY
end
end
context 'fetch' do
it 'does not register an offense for defined configuration keys' do
expect_no_offenses(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Base
def configured?
cop_config.fetch('Defined')
end
end
end
end
end
RUBY
end
it 'registers an offense for missing configuration keys' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Base
def configured?
cop_config.fetch('Missing')
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
end
end
RUBY
end
context 'with a default value' do
it 'does not register an offense for defined configuration keys' do
expect_no_offenses(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Base
def configured?
cop_config.fetch('Defined', default)
end
end
end
end
end
RUBY
end
it 'registers an offense for missing configuration keys' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Base
def configured?
cop_config.fetch('Missing', default)
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
end
end
RUBY
end
end
end
it 'works with deeper nested cop names' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module X
module Y
class Z < Base
def configured?
cop_config['Defined']
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `X/Y/Z` in `config/default.yml`.
end
end
end
end
end
end
RUBY
end
# TODO: Remove this test when the `Cop` base class is removed
it 'works when the base class is `Cop` instead of `Base`' do
expect_offense(<<~RUBY)
module RuboCop
module Cop
module Test
class Foo < Cop
def configured?
cop_config['Defined']
cop_config['Missing']
^^^^^^^^^ `Missing` is not defined in the configuration for `Test/Foo` in `config/default.yml`.
end
end
end
end
end
RUBY
end
it 'ignores `cop_config` in non-cop classes' do
expect_no_offenses(<<~RUBY)
class Test
def configured?
cop_config['Missing']
end
end
RUBY
end
it 'ignores `cop_config` in non-cop subclasses' do
expect_no_offenses(<<~RUBY)
module M
class C < ApplicationRecord::Base
def configured?
cop_config['Missing']
end
end
end
RUBY
end
it 'does not register an offense if using `cop_config` outside of a cop class' do
expect_no_offenses(<<~RUBY)
def configured?
cop_config['Missing']
end
RUBY
end
it 'can handle an empty file' do
expect_no_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/internal_affairs/location_exists_spec.rb | spec/rubocop/cop/internal_affairs/location_exists_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::LocationExists, :config do
context 'within an `and` node' do
context 'code that can be replaced with `loc?`' do
it 'registers an offense when the receiver does not match' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && other_node.loc.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin) && other_node.loc.begin
RUBY
end
it 'registers an offense when the location does not match' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && node.loc.end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin) && node.loc.end
RUBY
end
context 'when there is no receiver' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
loc.respond_to?(:begin) && loc.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `loc?(:begin)` instead of [...]
RUBY
expect_correction(<<~RUBY)
loc?(:begin)
RUBY
end
end
context 'when there is a single receiver' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && node.loc.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of [...]
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin)
RUBY
end
end
context 'when there is a single receiver with safe navigation' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
node&.loc&.respond_to?(:begin) && node&.loc&.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node&.loc?(:begin)` instead of [...]
RUBY
expect_correction(<<~RUBY)
node&.loc?(:begin)
RUBY
end
end
context 'when the receiver is a method chain' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo.bar.loc.respond_to?(:begin) && foo.bar.loc.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo.bar.loc?(:begin)` instead of [...]
RUBY
expect_correction(<<~RUBY)
foo.bar.loc?(:begin)
RUBY
end
end
context 'when the receiver is a method chain with safe navigation' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo&.bar&.loc&.respond_to?(:begin) && foo&.bar&.loc&.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo&.bar&.loc?(:begin)` instead of [...]
RUBY
expect_correction(<<~RUBY)
foo&.bar&.loc?(:begin)
RUBY
end
end
context 'when assigned' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
value = node.loc.respond_to?(:begin) && node.loc.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc.begin if node.loc?(:begin)` instead of [...]
RUBY
expect_correction(<<~RUBY)
value = node.loc.begin if node.loc?(:begin)
RUBY
end
context 'with safe navigation' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
value = node&.loc&.respond_to?(:begin) && node&.loc&.begin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node&.loc&.begin if node&.loc?(:begin)` instead of [...]
RUBY
expect_correction(<<~RUBY)
value = node&.loc&.begin if node&.loc?(:begin)
RUBY
end
end
end
end
context 'code that can potentially be replaced with `loc_is?`' do
it 'registers an offense but does not replace with `loc_is?` when the receiver does not match' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && other_node.loc.begin.is?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin) && other_node.loc.begin.is?('(')
RUBY
end
it 'registers an offense but does not replace with `loc_is?` when the location does not match' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && node.loc.end.is?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin) && node.loc.end.is?('(')
RUBY
end
context 'when there is no receiver' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
loc.respond_to?(:begin) && loc.begin.is?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `loc_is?(:begin, '(')` instead of [...]
RUBY
expect_correction(<<~RUBY)
loc_is?(:begin, '(')
RUBY
end
end
context 'when there is a single receiver' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && node.loc.begin.is?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc_is?(:begin, '(')` instead of [...]
RUBY
expect_correction(<<~RUBY)
node.loc_is?(:begin, '(')
RUBY
end
end
context 'when there is a single receiver with safe navigation' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
node&.loc&.respond_to?(:begin) && node&.loc&.begin.is?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node&.loc_is?(:begin, '(')` instead of [...]
RUBY
expect_correction(<<~RUBY)
node&.loc_is?(:begin, '(')
RUBY
end
end
context 'when the receiver is a method chain' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo.bar.loc.respond_to?(:begin) && foo.bar.loc.begin.is?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo.bar.loc_is?(:begin, '(')` instead of [...]
RUBY
expect_correction(<<~RUBY)
foo.bar.loc_is?(:begin, '(')
RUBY
end
end
context 'when the receiver is a method chain with safe navigation' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
foo&.bar&.loc&.respond_to?(:begin) && foo&.bar&.loc&.begin.is?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo&.bar&.loc_is?(:begin, '(')` instead of [...]
RUBY
expect_correction(<<~RUBY)
foo&.bar&.loc_is?(:begin, '(')
RUBY
end
end
context 'when using `source ==`' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && node.loc.begin.source == '('
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc_is?(:begin, '(')` instead of [...]
RUBY
expect_correction(<<~RUBY)
node.loc_is?(:begin, '(')
RUBY
end
end
context 'when using `source !=`' do
it 'registers an offense but does not replace with `loc_is?`' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && node.loc.begin.source != '('
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin) && node.loc.begin.source != '('
RUBY
end
end
context 'when using `source.start_with?`' do
it 'registers an offense but does not replace with `loc_is?`' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin) && node.loc.begin.source.start_with?('(')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin) && node.loc.begin.source.start_with?('(')
RUBY
end
end
end
end
context 'as a `send` node' do
it 'registers an offense on `node.loc.respond_to?`' do
expect_offense(<<~RUBY)
node.loc.respond_to?(:begin)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
node.loc?(:begin)
RUBY
end
it 'registers an offense and autocorrects on `loc.respond_to?` without receiver' do
expect_offense(<<~RUBY)
loc.respond_to?(:begin)
^^^^^^^^^^^^^^^^^^^^^^^ Use `loc?(:begin)` instead of `loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
loc?(:begin)
RUBY
end
it 'registers an offense within an `if` node' do
expect_offense(<<~RUBY)
foo if node.loc.respond_to?(:begin)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.loc?(:begin)` instead of `node.loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
foo if node.loc?(:begin)
RUBY
end
it 'registers an offense within an `if` node without receiver' do
expect_offense(<<~RUBY)
foo if loc.respond_to?(:begin)
^^^^^^^^^^^^^^^^^^^^^^^ Use `loc?(:begin)` instead of `loc.respond_to?(:begin)`.
RUBY
expect_correction(<<~RUBY)
foo if loc?(:begin)
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/internal_affairs/lambda_or_proc_spec.rb | spec/rubocop/cop/internal_affairs/lambda_or_proc_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::LambdaOrProc, :config do
it 'registers an offense when using `node.lambda? || node.proc?`' do
expect_offense(<<~RUBY)
node.lambda? || node.proc?
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.lambda_or_proc?`.
RUBY
expect_correction(<<~RUBY)
node.lambda_or_proc?
RUBY
end
it 'registers an offense when using `node.proc? || node.lambda?`' do
expect_offense(<<~RUBY)
node.proc? || node.lambda?
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.lambda_or_proc?`.
RUBY
expect_correction(<<~RUBY)
node.lambda_or_proc?
RUBY
end
it 'registers an offense when using `node.parenthesized? || node.lambda? || node.proc?`' do
expect_offense(<<~RUBY)
node.parenthesized? || node.lambda? || node.proc?
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.lambda_or_proc?`.
RUBY
expect_correction(<<~RUBY)
node.parenthesized? || node.lambda_or_proc?
RUBY
end
it 'registers an offense when using `node.parenthesized? || node.proc? || node.lambda?`' do
expect_offense(<<~RUBY)
node.parenthesized? || node.proc? || node.lambda?
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.lambda_or_proc?`.
RUBY
expect_correction(<<~RUBY)
node.parenthesized? || node.lambda_or_proc?
RUBY
end
it 'does not register an offense when using `node.lambda_or_proc?`' do
expect_no_offenses(<<~RUBY)
node.lambda_or_proc?
RUBY
end
it 'does not register an offense when LHS and RHS have different receivers' do
expect_no_offenses(<<~RUBY)
node1.lambda? || node2.proc?
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/internal_affairs/operator_keyword_spec.rb | spec/rubocop/cop/internal_affairs/operator_keyword_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::OperatorKeyword, :config do
it 'registers an offense when using `node.and_type? || node.or_type?`' do
expect_offense(<<~RUBY)
node.and_type? || node.or_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.operator_keyword?`.
RUBY
expect_correction(<<~RUBY)
node.operator_keyword?
RUBY
end
it 'registers an offense when using `node.or_type? || node.and_type?`' do
expect_offense(<<~RUBY)
node.or_type? || node.and_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.operator_keyword?`.
RUBY
expect_correction(<<~RUBY)
node.operator_keyword?
RUBY
end
it 'registers an offense when using `node.parenthesized? || node.and_type? || node.or_type?`' do
expect_offense(<<~RUBY)
node.parenthesized? || node.and_type? || node.or_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.operator_keyword?`.
RUBY
expect_correction(<<~RUBY)
node.parenthesized? || node.operator_keyword?
RUBY
end
it 'registers an offense when using `node.parenthesized? || node.or_type? || node.and_type?`' do
expect_offense(<<~RUBY)
node.parenthesized? || node.or_type? || node.and_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.operator_keyword?`.
RUBY
expect_correction(<<~RUBY)
node.parenthesized? || node.operator_keyword?
RUBY
end
it 'registers an offense when using `and_type? || or_type?` without receivers' do
expect_offense(<<~RUBY)
and_type? || or_type?
^^^^^^^^^^^^^^^^^^^^^ Use `operator_keyword?`.
RUBY
expect_correction(<<~RUBY)
operator_keyword?
RUBY
end
it 'does not register an offense when using `node.operator_keyword?`' do
expect_no_offenses(<<~RUBY)
node.operator_keyword?
RUBY
end
it 'does not register an offense when LHS and RHS have different receivers' do
expect_no_offenses(<<~RUBY)
node1.and_type? || node2.or_type?
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/internal_affairs/node_type_predicate_spec.rb | spec/rubocop/cop/internal_affairs/node_type_predicate_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::NodeTypePredicate, :config do
context 'comparison node type check' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
node.type == :send
^^^^^^^^^^^^^^^^^^ Use `#send_type?` to check node type.
RUBY
expect_correction(<<~RUBY)
node.send_type?
RUBY
end
end
context 'comparison node type check with safe navigation operator' do
it 'registers an offense and autocorrects' do
expect_offense(<<~RUBY)
node&.type == :send
^^^^^^^^^^^^^^^^^^^ Use `#send_type?` to check node type.
RUBY
expect_correction(<<~RUBY)
node&.send_type?
RUBY
end
end
it 'does not register an offense for a predicate node type check' do
expect_no_offenses(<<~RUBY)
node.send_type?
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/internal_affairs/location_line_equality_comparison_spec.rb | spec/rubocop/cop/internal_affairs/location_line_equality_comparison_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::LocationLineEqualityComparison, :config do
it 'registers and corrects an offense when comparing `#loc.line` with LHS and RHS' do
expect_offense(<<~RUBY)
node.loc.line == node.parent.loc.line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `same_line?(node, node.parent)`.
RUBY
expect_correction(<<~RUBY)
same_line?(node, node.parent)
RUBY
end
it 'registers and corrects an offense when comparing `#loc.source_range` with LHS and RHS' do
expect_offense(<<~RUBY)
node.source_range.line == node.parent.source_range.line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `same_line?(node, node.parent)`.
RUBY
expect_correction(<<~RUBY)
same_line?(node, node.parent)
RUBY
end
it 'registers an offense and corrects when using `loc.first_line`' do
expect_offense(<<~RUBY)
node.loc.line == node.parent.loc.first_line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `same_line?(node, node.parent)`.
RUBY
expect_correction(<<~RUBY)
same_line?(node, node.parent)
RUBY
end
it 'registers an offense and corrects when using `source_range.first_line`' do
expect_offense(<<~RUBY)
node.source_range.line == node.parent.source_range.first_line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `same_line?(node, node.parent)`.
RUBY
expect_correction(<<~RUBY)
same_line?(node, node.parent)
RUBY
end
it 'registers an offense and corrects when using `first_line`' do
expect_offense(<<~RUBY)
node.loc.line == node.parent.first_line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `same_line?(node, node.parent)`.
RUBY
expect_correction(<<~RUBY)
same_line?(node, node.parent)
RUBY
end
it 'registers an offense and corrects when using `first_line` inside block' do
expect_offense(<<~RUBY)
nodes.select do |node|
node.first_line == nodes.first.first_line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `same_line?(node, nodes.first)`.
end
RUBY
expect_correction(<<~RUBY)
nodes.select do |node|
same_line?(node, nodes.first)
end
RUBY
end
it 'does not register an offense when using `same_line?`' do
expect_no_offenses(<<~RUBY)
same_line?(node, node.parent)
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/internal_affairs/on_send_without_on_csend_spec.rb | spec/rubocop/cop/internal_affairs/on_send_without_on_csend_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::OnSendWithoutOnCSend, :config do
it 'registers an offense when `on_send` is defined without `on_csend`' do
expect_offense(<<~RUBY)
class MyCop < RuboCop::Cop:Base
def on_send(node)
^^^^^^^^^^^^^^^^^ Cop defines `on_send` but not `on_csend`.
# ...
end
end
RUBY
end
it 'does not register an offense when `on_send` is not defined' do
expect_no_offenses(<<~RUBY)
class MyCop < RuboCop::Cop:Base
def on_def(node)
# ...
end
end
RUBY
end
it 'does not register an offense when `on_csend` is defined but `on_send` is not' do
expect_no_offenses(<<~RUBY)
class MyCop < RuboCop::Cop:Base
def on_csend(node)
# ...
end
end
RUBY
end
it 'does not register an offense when `on_csend` is defined explicitly' do
expect_no_offenses(<<~RUBY)
class MyCop < RuboCop::Cop:Base
def on_send(node)
# ...
end
def on_csend(node)
# ...
end
end
RUBY
end
it 'does not register an offense when `on_csend` is defined with `alias`' do
expect_no_offenses(<<~RUBY)
class MyCop < RuboCop::Cop:Base
def on_send(node)
# ...
end
alias on_csend on_send
end
RUBY
end
it 'does not register an offense when `on_csend` is defined with `alias_method`' do
expect_no_offenses(<<~RUBY)
class MyCop < RuboCop::Cop:Base
def on_send(node)
# ...
end
alias_method :on_csend, :on_send
end
RUBY
end
it 'registers an offense when `alias_method` takes no arguments' do
expect_offense(<<~RUBY)
class MyCop < RuboCop::Cop:Base
def on_send(node)
^^^^^^^^^^^^^^^^^ Cop defines `on_send` but not `on_csend`.
# ...
end
alias_method
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/internal_affairs/processed_source_buffer_name_spec.rb | spec/rubocop/cop/internal_affairs/processed_source_buffer_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::ProcessedSourceBufferName, :config do
it 'registers an offense and corrects when using `processed_source.buffer.name` and `processed_source` is a method call' do
expect_offense(<<~RUBY)
processed_source.buffer.name
^^^^^^^^^^^ Use `file_path` instead.
RUBY
expect_correction(<<~RUBY)
processed_source.file_path
RUBY
end
it 'registers an offense and corrects when using `processed_source.buffer.name` and `processed_source` is a variable' do
expect_offense(<<~RUBY)
processed_source = create_processed_source
processed_source.buffer.name
^^^^^^^^^^^ Use `file_path` instead.
RUBY
expect_correction(<<~RUBY)
processed_source = create_processed_source
processed_source.file_path
RUBY
end
it 'does not register an offense when using `processed_source.file_path`' do
expect_no_offenses(<<~RUBY)
processed_source.file_path
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/internal_affairs/node_matcher_directive_spec.rb | spec/rubocop/cop/internal_affairs/node_matcher_directive_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::NodeMatcherDirective, :config do
%i[def_node_matcher def_node_search].each do |method|
it 'does not register an offense if the node matcher already has a directive' do
expect_no_offenses(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, '(str)'
RUBY
end
it 'does not register an offense if the directive is in a comment block' do
expect_no_offenses(<<~RUBY)
# @!method foo?(node)
# foo? matcher
#{method} :foo?, '(str)'
RUBY
end
it 'registers an offense if the matcher does not have a directive' do
expect_offense(<<~RUBY, method: method)
#{method} :foo?, '(str)'
^{method}^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, '(str)'
RUBY
end
it 'registers an offense if the matcher does not have a directive and a method call is used for a pattern argument' do
expect_offense(<<~RUBY, method: method)
#{method} :foo?, format(PATTERN, type: 'const')
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, format(PATTERN, type: 'const')
RUBY
end
it 'registers an offense if the matcher does not have a directive but has preceding comments' do
expect_offense(<<~RUBY, method: method)
# foo
#{method} :foo?, '(str)'
^{method}^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
# foo bar baz
# foo bar baz
# foo bar baz
#{method} :bar?, '(sym)'
^{method}^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
RUBY
expect_correction(<<~RUBY)
# foo
# @!method foo?(node)
#{method} :foo?, '(str)'
# foo bar baz
# foo bar baz
# foo bar baz
# @!method bar?(node)
#{method} :bar?, '(sym)'
RUBY
end
it 'registers an offense if the directive name does not match the actual name' do
expect_offense(<<~RUBY, method: method)
# @!method bar?(node)
#{method} :foo?, '(str)'
^{method}^^^^^^^^^^^^^^^ `@!method` YARD directive has invalid method name, use `foo?` instead of `bar?`.
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, '(str)'
RUBY
end
it 'registers an offense if the matcher has multiple directives' do
expect_offense(<<~RUBY, method: method)
# @!method foo?(node)
# @!method foo?(node)
#{method} :foo?, '(str)'
^{method}^^^^^^^^^^^^^^^ Multiple `@!method` YARD directives found for this matcher.
RUBY
expect_no_corrections
end
it 'autocorrects with the right arguments if the pattern includes arguments' do
expect_offense(<<~RUBY, method: method)
#{method} :foo?, '(str %1)'
^{method}^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node, arg1)
#{method} :foo?, '(str %1)'
RUBY
end
it 'autocorrects with the right arguments if the pattern references a non-contiguous argument' do
expect_offense(<<~RUBY, method: method)
#{method} :foo?, '(str %4)'
^{method}^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node, arg1, arg2, arg3, arg4)
#{method} :foo?, '(str %4)'
RUBY
end
it 'does not register an offense if called with a dynamic method name' do
expect_no_offenses(<<~'RUBY')
#{method} matcher_name, '(str)'
#{method} "#{matcher_name}", '(str)'
RUBY
end
it 'retains indentation properly when inserting' do
expect_offense(<<~RUBY, method: method)
class MyCop
#{method} :foo?, '(str)'
^{method}^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
end
RUBY
expect_correction(<<~RUBY)
class MyCop
# @!method foo?(node)
#{method} :foo?, '(str)'
end
RUBY
end
it 'retains indentation properly when correcting' do
expect_offense(<<~RUBY, method: method)
class MyCop
# @!method bar?(node)
#{method} :foo?, '(str)'
^{method}^^^^^^^^^^^^^^^ `@!method` YARD directive has invalid method name, use `foo?` instead of `bar?`.
end
RUBY
expect_correction(<<~RUBY)
class MyCop
# @!method foo?(node)
#{method} :foo?, '(str)'
end
RUBY
end
it 'inserts a blank line between multiple pattern matchers' do
expect_offense(<<~RUBY, method: method)
#{method} :foo?, '(str)'
^{method}^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
#{method} :bar?, '(str)'
^{method}^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, '(str)'
# @!method bar?(node)
#{method} :bar?, '(str)'
RUBY
end
it 'inserts a blank line between multiple multi-line pattern matchers' do
expect_offense(<<~RUBY, method: method)
#{method} :foo?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
(str)
PATTERN
#{method} :bar?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, <<~PATTERN
(str)
PATTERN
# @!method bar?(node)
#{method} :bar?, <<~PATTERN
(str)
PATTERN
RUBY
end
it 'does not insert a blank line if one already exists' do
expect_offense(<<~RUBY, method: method)
#{method} :foo?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
(str)
PATTERN
#{method} :bar?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, <<~PATTERN
(str)
PATTERN
# @!method bar?(node)
#{method} :bar?, <<~PATTERN
(str)
PATTERN
RUBY
end
it 'removes `@!scope class` YARD directive if it is not a class method' do
expect_offense(<<~RUBY, method: method)
# @!method foo?(node)
# @!scope class
#{method} :foo?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ Do not use the `@!scope class` YARD directive if it is not a class method.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, <<~PATTERN
(str)
PATTERN
RUBY
end
it 'removes the receiver from the YARD directive if it is not a class method' do
expect_offense(<<~RUBY, method: method)
# @!method self.foo?(node)
#{method} :foo?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ `@!method` YARD directive has invalid method name, use `foo?` instead of `self.foo?`.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, <<~PATTERN
(str)
PATTERN
RUBY
end
it 'removes the receiver from the YARD directive and the scope directive if it is not a class method' do
expect_offense(<<~RUBY, method: method)
# @!method self.foo?(node)
# @!scope class
#{method} :foo?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ Do not use the `@!scope class` YARD directive if it is not a class method.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, <<~PATTERN
(str)
PATTERN
RUBY
end
it 'registers an offense when the directive has the wrong name without self' do
expect_offense(<<~RUBY, method: method)
# @!method self.bar?(node)
#{method} :foo?, <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^ `@!method` YARD directive has invalid method name, use `foo?` instead of `self.bar?`.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
#{method} :foo?, <<~PATTERN
(str)
PATTERN
RUBY
end
it 'registers no offense without second argument' do
expect_no_offenses(<<~RUBY)
#{method} :foo?
RUBY
end
context 'when using class methods' do
it 'registers an offense when the directive is missing' do
expect_offense(<<~RUBY, method: method)
#{method} :"self.foo?", <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
(str)
PATTERN
#{method} "self.bar?", <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^^^^^^^ Precede `#{method}` with a `@!method` YARD directive.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
# @!scope class
#{method} :"self.foo?", <<~PATTERN
(str)
PATTERN
# @!method bar?(node)
# @!scope class
#{method} "self.bar?", <<~PATTERN
(str)
PATTERN
RUBY
end
it 'registers an offense when the directive has the wrong name' do
expect_offense(<<~RUBY, method: method)
# @!method self.bar?(node)
#{method} :"self.foo?", <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^ Follow the `@!method` YARD directive with `@!scope class` if it is a class method.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
# @!scope class
#{method} :"self.foo?", <<~PATTERN
(str)
PATTERN
RUBY
end
it 'registers an offense when the method has the wrong name without self' do
expect_offense(<<~RUBY, method: method)
# @!method bar?(node)
#{method} :"self.foo?", <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^ Follow the `@!method` YARD directive with `@!scope class` if it is a class method.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
# @!scope class
#{method} :"self.foo?", <<~PATTERN
(str)
PATTERN
RUBY
end
it 'registers an offense when the method directive contains self and the scope directive is missing' do
expect_offense(<<~RUBY, method: method)
# @!method self.foo?(node)
#{method} 'self.foo?', <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^^^^^^^ Follow the `@!method` YARD directive with `@!scope class` if it is a class method.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
# @!scope class
#{method} 'self.foo?', <<~PATTERN
(str)
PATTERN
RUBY
end
it 'registers no offenses when it is correctly specified' do
expect_no_offenses(<<~RUBY)
# @!method foo?(node)
# @!scope class
#{method} :"self.foo?", <<~PATTERN
(str)
PATTERN
RUBY
end
it 'registers no offenses when the receiver is not self' do
expect_no_offenses(<<~RUBY)
#{method} :"x.foo?", <<~PATTERN
(str)
PATTERN
RUBY
end
it 'gives the correct message for "self." prefix on @!method when @!scope is correctly "class"' do
expect_offense(<<~RUBY, method: method)
# @!method self.foo?(node)
# @!scope class
#{method} 'self.foo?', <<~PATTERN
^{method}^^^^^^^^^^^^^^^^^^^^^^^^ `@!method` YARD directive has invalid method name, use `foo?` instead of `self.foo?`.
(str)
PATTERN
RUBY
expect_correction(<<~RUBY)
# @!method foo?(node)
# @!scope class
#{method} 'self.foo?', <<~PATTERN
(str)
PATTERN
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/internal_affairs/create_empty_file_spec.rb | spec/rubocop/cop/internal_affairs/create_empty_file_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::CreateEmptyFile, :config do
it "registers an offense when using `create_file(path, '')" do
expect_offense(<<~RUBY)
create_file(path, '')
^^^^^^^^^^^^^^^^^^^^^ Use `create_empty_file(path)`.
RUBY
expect_correction(<<~RUBY)
create_empty_file(path)
RUBY
end
it 'registers an offense when using `create_file(path, "")' do
expect_offense(<<~RUBY)
create_file(path, "")
^^^^^^^^^^^^^^^^^^^^^ Use `create_empty_file(path)`.
RUBY
expect_correction(<<~RUBY)
create_empty_file(path)
RUBY
end
it "does not register an offense when using `create_file(path, 'hello')`" do
expect_no_offenses(<<~RUBY)
create_file(path, 'hello')
RUBY
end
it "does not register an offense when using `create_file(path, ['foo', 'bar'])`" do
expect_no_offenses(<<~RUBY)
create_file(path, ['foo', 'bar'])
RUBY
end
it 'does not register an offense when using `create_file(path)`' do
expect_no_offenses(<<~RUBY)
create_file(path)
RUBY
end
it "does not register an offense when using `receiver.create_file(path, '')`" do
expect_no_offenses(<<~RUBY)
receiver.create_file(path, '')
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/internal_affairs/node_type_multiple_predicates_spec.rb | spec/rubocop/cop/internal_affairs/node_type_multiple_predicates_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::InternalAffairs::NodeTypeMultiplePredicates, :config do
context 'in an `or` node with multiple node type predicate branches' do
it 'does not register an offense for type predicates called without a receiver' do
expect_no_offenses(<<~RUBY)
str_type? || sym_type?
RUBY
end
it 'does not register an offense for type predicates called with different receivers' do
expect_no_offenses(<<~RUBY)
foo.str_type? || bar.sym_type?
RUBY
end
it 'does not register an offense when all method calls are not type predicates' do
expect_no_offenses(<<~RUBY)
foo.bar? || foo.sym_type?
RUBY
end
it 'does not register an offense for negated predicates' do
expect_no_offenses(<<~RUBY)
!node.str_type? || !node.sym_type?
RUBY
end
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
node.str_type? || node.sym_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.type?(:str, :sym)` instead of checking for multiple node types.
RUBY
expect_correction(<<~RUBY)
node.type?(:str, :sym)
RUBY
end
it 'registers an offense and corrects with `defined_type?`' do
expect_offense(<<~RUBY)
node.call_type? || node.defined_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.type?(:call, :defined?)` instead of checking for multiple node types.
RUBY
expect_correction(<<~RUBY)
node.type?(:call, :defined?)
RUBY
end
it 'registers an offense and corrects for nested `or` nodes' do
expect_offense(<<~RUBY)
node.str_type? || node.sym_type? || node.boolean_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.type?(:str, :sym)` instead of checking for multiple node types.
RUBY
expect_correction(<<~RUBY)
node.type?(:str, :sym, :boolean)
RUBY
end
it 'registers an offense and corrects when the LHS is a `type?` call' do
expect_offense(<<~RUBY)
node.type?(:str, :sym) || node.boolean_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.type?(:str, :sym, :boolean)` instead of checking for multiple node types.
RUBY
expect_correction(<<~RUBY)
node.type?(:str, :sym, :boolean)
RUBY
end
it 'registers an offense and corrects when the RHS is a `type?` call' do
expect_offense(<<~RUBY)
node.boolean_type? || node.type?(:str, :sym)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node.type?(:boolean, :str, :sym)` instead of checking for multiple node types.
RUBY
expect_correction(<<~RUBY)
node.type?(:boolean, :str, :sym)
RUBY
end
it 'registers an offense and corrects with safe navigation' do
expect_offense(<<~RUBY)
node&.str_type? || node&.sym_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `node&.type?(:str, :sym)` instead of checking for multiple node types.
RUBY
expect_correction(<<~RUBY)
node&.type?(:str, :sym)
RUBY
end
end
context 'in an `and` node with multiple negated type predicate branches' do
it 'does not register an offense for type predicates called without a receiver' do
expect_no_offenses(<<~RUBY)
!str_type? && !sym_type?
RUBY
end
it 'does not register an offense for type predicates called with different receivers' do
expect_no_offenses(<<~RUBY)
!foo.str_type? && !bar.sym_type?
RUBY
end
it 'does not register an offense when all method calls are not type predicates' do
expect_no_offenses(<<~RUBY)
!foo.bar? && !foo.sym_type?
RUBY
end
it 'does not register an offense for type predicates called without negation' do
expect_no_offenses(<<~RUBY)
node.str_type? && node.sym_type?
RUBY
end
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
!node.str_type? && !node.sym_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!node.type?(:str, :sym)` instead of checking against multiple node types.
RUBY
expect_correction(<<~RUBY)
!node.type?(:str, :sym)
RUBY
end
it 'registers an offense and corrects with `defined_type?`' do
expect_offense(<<~RUBY)
!node.call_type? && !node.defined_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!node.type?(:call, :defined?)` instead of checking against multiple node types.
RUBY
expect_correction(<<~RUBY)
!node.type?(:call, :defined?)
RUBY
end
it 'registers an offense and corrects for nested `and` nodes' do
expect_offense(<<~RUBY)
!node.str_type? && !node.sym_type? && !node.boolean_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!node.type?(:str, :sym)` instead of checking against multiple node types.
RUBY
expect_correction(<<~RUBY)
!node.type?(:str, :sym, :boolean)
RUBY
end
it 'registers an offense and corrects when the LHS is a `type?` call' do
expect_offense(<<~RUBY)
!node.type?(:str, :sym) && !node.boolean_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!node.type?(:str, :sym, :boolean)` instead of checking against multiple node types.
RUBY
expect_correction(<<~RUBY)
!node.type?(:str, :sym, :boolean)
RUBY
end
it 'registers an offense and corrects when the RHS is a `type?` call' do
expect_offense(<<~RUBY)
!node.boolean_type? && !node.type?(:str, :sym)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!node.type?(:boolean, :str, :sym)` instead of checking against multiple node types.
RUBY
expect_correction(<<~RUBY)
!node.type?(:boolean, :str, :sym)
RUBY
end
it 'registers an offense and corrects with safe navigation' do
expect_offense(<<~RUBY)
!node&.str_type? && !node&.sym_type?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!node&.type?(:str, :sym)` instead of checking against multiple node types.
RUBY
expect_correction(<<~RUBY)
!node&.type?(:str, :sym)
RUBY
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.