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/layout/space_before_comma_spec.rb | spec/rubocop/cop/layout/space_before_comma_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::SpaceBeforeComma, :config do
it 'registers an offense and corrects block argument with space before comma' do
expect_offense(<<~RUBY)
each { |s , t| }
^ Space found before comma.
RUBY
expect_correction(<<~RUBY)
each { |s, t| }
RUBY
end
it 'registers an offense and corrects array index with space before comma' do
expect_offense(<<~RUBY)
formats[0 , 1]
^ Space found before comma.
RUBY
expect_correction(<<~RUBY)
formats[0, 1]
RUBY
end
it 'registers an offense and corrects method call arg with space before comma' do
expect_offense(<<~RUBY)
a(1 , 2)
^ Space found before comma.
RUBY
expect_correction(<<~RUBY)
a(1, 2)
RUBY
end
it 'does not register an offense for no spaces before comma' do
expect_no_offenses('a(1, 2)')
end
it 'handles more than one space before a comma' do
expect_offense(<<~RUBY)
each { |s , t| a(1 , formats[0 , 1])}
^^ Space found before comma.
^^ Space found before comma.
^^ Space found before comma.
RUBY
expect_correction(<<~RUBY)
each { |s, t| a(1, formats[0, 1])}
RUBY
end
context 'heredocs' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
a(<<~STR , 2)
^ Space found before comma.
text
STR
RUBY
expect_correction(<<~RUBY)
a(<<~STR, 2)
text
STR
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/layout/first_argument_indentation_spec.rb | spec/rubocop/cop/layout/first_argument_indentation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::FirstArgumentIndentation, :config do
let(:cop_config) { { 'EnforcedStyle' => style } }
let(:other_cops) { { 'Layout/IndentationWidth' => { 'Width' => indentation_width } } }
shared_examples 'common behavior' do
context 'when IndentationWidth:Width is 2' do
let(:indentation_width) { 2 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument of `super`' do
expect_offense(<<~RUBY)
super(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
super(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument on an alphanumeric method name' do
expect_offense(<<~RUBY)
self.run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
self.run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument on a pipe method name' do
expect_offense(<<~RUBY)
self.|(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
self.|(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument on a plus sign method name' do
expect_offense(<<~RUBY)
self.+(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
self.+(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects lines affected by another offense' do
expect_offense(<<~RUBY)
foo(
bar(
^^^^ Indent the first argument one step more than the start of the previous line.
7
^ Bad indentation of the first argument.
)
)
RUBY
# The first `)` Will be corrected by IndentationConsistency.
expect_correction(<<~RUBY, loop: false)
foo(
bar(
7
)
)
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense and corrects an under-indented 1st argument' do
expect_offense(<<~RUBY)
receiver&.run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
receiver&.run(
:foo,
bar: 3
)
RUBY
end
end
context 'for a setter call' do
it 'accepts an unindented value' do
expect_no_offenses(<<~RUBY)
foo.baz =
bar
RUBY
end
end
context 'for assignment' do
it 'accepts a correctly indented first argument and does not care ' \
'about the second argument' do
expect_no_offenses(<<~RUBY)
x = run(
:foo,
bar: 3
)
RUBY
end
context 'with line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
x =
run(
:foo)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
@x =
run(
:foo)
^^^^ Indent the first argument one step more than the start of the previous line.
RUBY
expect_correction(<<~RUBY)
@x =
run(
:foo)
RUBY
end
end
end
it 'accepts a first argument that is not preceded by a line break' do
expect_no_offenses(<<~RUBY)
run :foo,
bar: 3
RUBY
end
context 'when the receiver contains a line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
puts x.
merge(
b: 2
^^^^ Indent the first argument one step more than the start of the previous line.
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'accepts a correctly indented first argument preceded by an empty line' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
context 'when preceded by a comment line' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge( # EOL comment
# comment
b: 2
)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
puts x.
merge(
# comment
b: 2
^^^^ Indent the first argument one step more than the start of the previous line (not counting the comment).
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
# comment
b: 2
)
RUBY
end
end
end
it 'accepts method calls with no arguments' do
expect_no_offenses(<<~RUBY)
run()
run_again
RUBY
end
it 'accepts operator calls' do
expect_no_offenses(<<~RUBY)
params = default_cfg.keys - %w(Description) -
cfg.keys
RUBY
end
it 'does not view []= as an outer method call' do
expect_no_offenses(<<~RUBY)
@subject_results[subject] = original.update(
mutation_results: (dup << mutation_result),
tests: test_result.tests
)
RUBY
end
it 'does not view chained call as an outer method call' do
expect_no_offenses(<<~'RUBY')
A = Regexp.union(
/[A-Za-z_][A-Za-z\d_]*[!?=]?/,
*AST::Types::OPERATOR_METHODS.map(&:to_s)
).freeze
RUBY
end
end
context 'when IndentationWidth:Width is 4' do
let(:indentation_width) { 4 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
context 'when indentation width is overridden for this cop only' do
let(:cop_config) { { 'EnforcedStyle' => style, 'IndentationWidth' => 4 } }
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than the start of the previous line.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
end
context 'when EnforcedStyle is special_for_inner_method_call' do
let(:style) { 'special_for_inner_method_call' }
let(:indentation_width) { 2 }
it_behaves_like 'common behavior'
context 'for method calls within method calls' do
context 'with outer parentheses' do
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than `defaults.merge(`.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
end
context 'without outer parentheses' do
it 'accepts a first argument with special indentation' do
expect_no_offenses(<<~RUBY)
run :foo, defaults.merge(
bar: 3)
RUBY
end
end
end
end
context 'when EnforcedStyle is special_for_inner_method_call_in_parentheses' do
let(:style) { 'special_for_inner_method_call_in_parentheses' }
let(:indentation_width) { 2 }
it_behaves_like 'common behavior'
context 'for method calls within method calls' do
context 'with outer parentheses' do
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than `defaults.merge(`.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.
merge(
bar: 3))
^^^^^^ Indent the first argument one step more than the start of the previous line.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.
merge(
bar: 3))
RUBY
end
it 'accepts a correctly indented first argument in interpolation' do
expect_no_offenses(<<~'RUBY')
puts %(
<p>
#{Array(
42
)}
</p>
)
RUBY
end
it 'accepts a correctly indented first argument with fullwidth characters' do
expect_no_offenses(<<~RUBY)
puts('Ruby', f(
a))
RUBY
end
end
context 'without outer parentheses' do
it 'accepts a first argument with consistent style indentation' do
expect_no_offenses(<<~RUBY)
run :foo, defaults.merge(
bar: 3)
RUBY
end
end
end
end
context 'when EnforcedStyle is consistent' do
let(:style) { 'consistent' }
let(:indentation_width) { 2 }
it_behaves_like 'common behavior'
context 'for method calls within method calls' do
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than the start of the previous line.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
it 'accepts first argument indented relative to previous line' do
expect_no_offenses(<<~RUBY)
@diagnostics.process(Diagnostic.new(
:error, :token, { :token => name }, location))
RUBY
end
end
end
context 'when EnforcedStyle is consistent_relative_to_receiver' do
let(:style) { 'consistent_relative_to_receiver' }
context 'when IndentationWidth:Width is 2' do
let(:indentation_width) { 2 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects lines affected by other offenses' do
expect_offense(<<~RUBY)
foo(
bar(
^^^^ Indent the first argument one step more than `foo(`.
7
^ Bad indentation of the first argument.
)
)
RUBY
# The first `)` Will be corrected by IndentationConsistency.
expect_correction(<<~RUBY, loop: false)
foo(
bar(
7
)
)
RUBY
end
context 'for assignment' do
it 'registers an offense and corrects a correctly indented first ' \
'argument and does not care about the second argument' do
expect_offense(<<~RUBY)
x = run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3
)
RUBY
expect_correction(<<~RUBY)
x = run(
:foo,
bar: 3
)
RUBY
end
context 'with line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
x =
run(
:foo)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
@x =
run(
:foo)
^^^^ Indent the first argument one step more than `run(`.
RUBY
expect_correction(<<~RUBY)
@x =
run(
:foo)
RUBY
end
end
end
it 'accepts a first argument that is not preceded by a line break' do
expect_no_offenses(<<~RUBY)
run :foo,
bar: 3
RUBY
end
it 'does not register an offense when argument has expected indent width and ' \
'the method is preceded by splat' do
expect_no_offenses(<<~RUBY)
[
item,
*do_something(
arg)
]
RUBY
end
it 'does not register an offense when argument has expected indent width and ' \
'the method is preceded by double splat' do
expect_no_offenses(<<~RUBY)
[
item,
**do_something(
arg)
]
RUBY
end
context 'when the receiver contains a line break' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'registers an offense and corrects an over-indented 1st argument' do
expect_offense(<<~RUBY)
puts x.
merge(
b: 2
^^^^ Indent the first argument one step more than the start of the previous line.
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
it 'accepts a correctly indented first argument preceded by an empty line' do
expect_no_offenses(<<~RUBY)
puts x.
merge(
b: 2
)
RUBY
end
context 'when preceded by a comment line' do
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
puts x.
merge( # EOL comment
# comment
b: 2
)
RUBY
end
it 'registers an offense and corrects an under-indented first argument' do
expect_offense(<<~RUBY)
puts x.
merge(
# comment
b: 2
^^^^ Indent the first argument one step more than the start of the previous line (not counting the comment).
)
RUBY
expect_correction(<<~RUBY)
puts x.
merge(
# comment
b: 2
)
RUBY
end
end
end
it 'accepts method calls with no arguments' do
expect_no_offenses(<<~RUBY)
run()
run_again
RUBY
end
it 'accepts operator calls' do
expect_no_offenses(<<~RUBY)
params = default_cfg.keys - %w(Description) -
cfg.keys
RUBY
end
it 'does not view []= as an outer method call' do
expect_no_offenses(<<~RUBY)
@subject_results[subject] = original.update(
mutation_results: (dup << mutation_result),
tests: test_result.tests
)
RUBY
end
it 'does not view chained call as an outer method call' do
expect_no_offenses(<<~'RUBY')
A = Regexp.union(
/[A-Za-z_][A-Za-z\d_]*[!?=]?/,
*AST::Types::OPERATOR_METHODS.map(&:to_s)
).freeze
RUBY
end
end
context 'when IndentationWidth:Width is 4' do
let(:indentation_width) { 4 }
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
context 'when indentation width is overridden for this cop only' do
let(:indentation_width) { nil }
let(:cop_config) { { 'EnforcedStyle' => style, 'IndentationWidth' => 4 } }
it 'accepts a correctly indented first argument' do
expect_no_offenses(<<~RUBY)
run(
:foo,
bar: 3
)
RUBY
end
it 'registers an offense and corrects an over-indented first argument' do
expect_offense(<<~RUBY)
run(
:foo,
^^^^ Indent the first argument one step more than `run(`.
bar: 3)
RUBY
expect_correction(<<~RUBY)
run(
:foo,
bar: 3)
RUBY
end
end
context 'for method calls within method calls' do
let(:indentation_width) { 2 }
context 'with outer parentheses' do
it 'registers an offense and corrects an over-indented 1st argument' do
expect_offense(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
^^^^^^ Indent the first argument one step more than `defaults.merge(`.
RUBY
expect_correction(<<~RUBY)
run(:foo, defaults.merge(
bar: 3))
RUBY
end
it 'indents all relative to the receiver' do
expect_no_offenses(<<~RUBY)
foo = run(
:foo, defaults.merge(
bar: 3)
)
RUBY
expect_no_offenses(<<~RUBY)
MyClass.my_method(a_hash.merge(
hello: :world,
some: :hash,
goes: :here
), other_arg)
RUBY
expect_no_offenses(<<~RUBY)
foo = bar * run(
:foo, defaults.merge(
bar: 3)
)
RUBY
end
end
context 'without outer parentheses' do
it 'accepts a first argument with special indentation' do
expect_no_offenses(<<~RUBY)
run :foo, defaults.merge(
bar: 3)
RUBY
end
it 'indents all relative to the receiver' do
expect_no_offenses(<<~RUBY)
foo = run :foo, defaults.merge(
bar: 3)
RUBY
expect_no_offenses(<<~RUBY)
foo = bar * run(
:foo, defaults.merge(
bar: 3))
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/layout/access_modifier_indentation_spec.rb | spec/rubocop/cop/layout/access_modifier_indentation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::AccessModifierIndentation, :config do
let(:config) do
c = cop_config.merge('SupportedStyles' => %w[indent outdent])
RuboCop::Config
.new('Layout/AccessModifierIndentation' => c,
'Layout/IndentationWidth' => { 'Width' => indentation_width })
end
let(:indentation_width) { 2 }
context 'when EnforcedStyle is set to indent' do
let(:cop_config) { { 'EnforcedStyle' => 'indent' } }
it 'registers an offense and corrects misaligned private' do
expect_offense(<<~RUBY)
class Test
private
^^^^^^^ Indent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
class Test
private
def test; end
end
RUBY
end
it 'registers an offense and corrects misaligned private in module' do
expect_offense(<<~RUBY)
module Test
private
^^^^^^^ Indent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
private
def test; end
end
RUBY
end
it 'registers an offense and corrects misaligned module_function in module' do
expect_offense(<<~RUBY)
module Test
module_function
^^^^^^^^^^^^^^^ Indent access modifiers like `module_function`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
module_function
def test; end
end
RUBY
end
it 'registers an offense and corrects correct + opposite alignment' do
expect_offense(<<~RUBY)
module Test
public
private
^^^^^^^ Indent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
public
private
def test; end
end
RUBY
end
it 'registers an offense and corrects opposite + correct alignment' do
expect_offense(<<~RUBY)
module Test
public
^^^^^^ Indent access modifiers like `public`.
private
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
public
private
def test; end
end
RUBY
end
it 'registers an offense and corrects misaligned private in a singleton class' do
expect_offense(<<~RUBY)
class << self
private
^^^^^^^ Indent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
class << self
private
def test; end
end
RUBY
end
it 'registers an offense and corrects misaligned private in class defined with Class.new' do
expect_offense(<<~RUBY)
Test = Class.new do
private
^^^^^^^ Indent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
Test = Class.new do
private
def test; end
end
RUBY
end
it 'registers an offense and corrects access modifiers in arbitrary blocks' do
expect_offense(<<~RUBY)
func do
private
^^^^^^^ Indent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
func do
private
def test; end
end
RUBY
end
it 'registers an offense and corrects misaligned private in module defined with Module.new' do
expect_offense(<<~RUBY)
Test = Module.new do
private
^^^^^^^ Indent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
Test = Module.new do
private
def test; end
end
RUBY
end
it 'registers an offense and corrects misaligned protected' do
expect_offense(<<~RUBY)
class Test
protected
^^^^^^^^^ Indent access modifiers like `protected`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
class Test
protected
def test; end
end
RUBY
end
it 'accepts properly indented private' do
expect_no_offenses(<<~RUBY)
class Test
private
def test; end
end
RUBY
end
it 'accepts properly indented protected' do
expect_no_offenses(<<~RUBY)
class Test
protected
def test; end
end
RUBY
end
it 'accepts properly indented private in module defined with Module.new' do
expect_no_offenses(<<~RUBY)
Test = Module.new do
private
def test; end
end
RUBY
end
it 'accepts an empty class' do
expect_no_offenses(<<~RUBY)
class Test
end
RUBY
end
it 'accepts methods with a body' do
expect_no_offenses(<<~RUBY)
module Test
def test
foo
end
end
RUBY
end
it 'registers an offense and corrects misaligned access modifiers in nested classes' do
expect_offense(<<~RUBY)
class Test
class Nested
private
^^^^^^^ Indent access modifiers like `private`.
def a; end
end
protected
def test; end
end
RUBY
expect_correction(<<~RUBY)
class Test
class Nested
private
def a; end
end
protected
def test; end
end
RUBY
end
it 'accepts indented access modifiers with arguments in nested classes' do
expect_no_offenses(<<~RUBY)
class A
module Test
private :test
end
end
RUBY
expect_no_offenses(<<~RUBY)
class A
class Test
private :test
end
end
RUBY
expect_no_offenses(<<~RUBY)
class A
class << self
private :test
end
end
RUBY
end
it 'does not register an offense when the access modifier is on the same line as the class definition' do
expect_no_offenses(<<~RUBY)
class A; private; def foo; end; end
RUBY
end
context 'when 4 spaces per indent level are used' do
let(:indentation_width) { 4 }
it 'accepts properly indented private' do
expect_no_offenses(<<~RUBY)
class Test
private
def test; end
end
RUBY
end
end
context 'when indentation width is overridden for this cop only' do
let(:cop_config) { { 'EnforcedStyle' => 'indent', 'IndentationWidth' => 4 } }
it 'accepts properly indented private' do
expect_no_offenses(<<~RUBY)
class Test
private
def test; end
end
RUBY
end
end
end
context 'when EnforcedStyle is set to outdent' do
let(:cop_config) { { 'EnforcedStyle' => 'outdent' } }
it 'registers an offense and corrects private indented to method depth in a class' do
expect_offense(<<~RUBY)
class Test
private
^^^^^^^ Outdent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
class Test
private
def test; end
end
RUBY
end
it 'accepts private with argument indented to method depth in a class' do
expect_no_offenses(<<~RUBY)
class Test
def test; end
private :test
end
RUBY
end
it 'accepts private def indented to method depth in a class' do
expect_no_offenses(<<~RUBY)
class Test
private def test; end
end
RUBY
end
it 'registers an offense and corrects private indented to method depth in a module' do
expect_offense(<<~RUBY)
module Test
private
^^^^^^^ Outdent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
private
def test; end
end
RUBY
end
it 'accepts private with argument indented to method depth in a module' do
expect_no_offenses(<<~RUBY)
module Test
def test; end
private :test
end
RUBY
end
it 'accepts private def indented to method depth in a module' do
expect_no_offenses(<<~RUBY)
module Test
private def test; end
end
RUBY
end
it 'registers an offense and corrects module_function indented to method depth in a module' do
expect_offense(<<~RUBY)
module Test
module_function
^^^^^^^^^^^^^^^ Outdent access modifiers like `module_function`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
module Test
module_function
def test; end
end
RUBY
end
it 'accepts module fn with argument indented to method depth in a module' do
expect_no_offenses(<<~RUBY)
module Test
def test; end
module_function :test
end
RUBY
end
it 'accepts module fn def indented to method depth in a module' do
expect_no_offenses(<<~RUBY)
module Test
module_function def test; end
end
RUBY
end
it 'registers an offense and corrects private indented to method depth in singleton class' do
expect_offense(<<~RUBY)
class << self
private
^^^^^^^ Outdent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
class << self
private
def test; end
end
RUBY
end
it 'accepts private with argument indented to method depth in singleton class' do
expect_no_offenses(<<~RUBY)
class << self
def test; end
private :test
end
RUBY
end
it 'accepts private def indented to method depth in singleton class' do
expect_no_offenses(<<~RUBY)
class << self
private def test; end
end
RUBY
end
it 'registers an offense and corrects private indented to method depth ' \
'in class defined with Class.new' do
expect_offense(<<~RUBY)
Test = Class.new do
private
^^^^^^^ Outdent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
Test = Class.new do
private
def test; end
end
RUBY
end
it 'accepts private with argument indented to method depth in class defined with Class.new' do
expect_no_offenses(<<~RUBY)
Test = Class.new do
def test; end
private :test
end
RUBY
end
it 'accepts private def indented to method depth in class defined with Class.new' do
expect_no_offenses(<<~RUBY)
Test = Class.new do
private def test; end
end
RUBY
end
it 'registers an offense and corrects private indented to method depth ' \
'in module defined with Module.new' do
expect_offense(<<~RUBY)
Test = Module.new do
private
^^^^^^^ Outdent access modifiers like `private`.
def test; end
end
RUBY
expect_correction(<<~RUBY)
Test = Module.new do
private
def test; end
end
RUBY
end
it 'accepts private with argument indented to method depth in module defined with Module.new' do
expect_no_offenses(<<~RUBY)
Test = Module.new do
def test; end
private :test
end
RUBY
end
it 'accepts private def indented to method depth in module defined with Module.new' do
expect_no_offenses(<<~RUBY)
Test = Module.new do
private def test; end
end
RUBY
end
it 'accepts private indented to the containing class indent level' do
expect_no_offenses(<<~RUBY)
class Test
private
def test; end
end
RUBY
end
it 'accepts protected indented to the containing class indent level' do
expect_no_offenses(<<~RUBY)
class Test
protected
def test; end
end
RUBY
end
it 'registers an offense and corrects misaligned access modifiers in nested classes' do
expect_offense(<<~RUBY)
class Test
class Nested
private
^^^^^^^ Outdent access modifiers like `private`.
def a; end
end
protected
def test; end
end
RUBY
expect_correction(<<~RUBY)
class Test
class Nested
private
def a; end
end
protected
def test; 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/layout/parameter_alignment_spec.rb | spec/rubocop/cop/layout/parameter_alignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::ParameterAlignment, :config do
let(:config) do
RuboCop::Config.new('Layout/ParameterAlignment' => cop_config,
'Layout/IndentationWidth' => {
'Width' => indentation_width
})
end
let(:indentation_width) { 2 }
context 'aligned with first parameter' do
let(:cop_config) { { 'EnforcedStyle' => 'with_first_parameter' } }
it 'registers an offense and corrects parameters with single indent' do
expect_offense(<<~RUBY)
def method(a,
b)
^ Align the parameters of a method definition if they span more than one line.
end
RUBY
expect_correction(<<~RUBY)
def method(a,
b)
end
RUBY
end
it 'registers an offense and corrects parameters with double indent' do
expect_offense(<<~RUBY)
def method(a,
b)
^ Align the parameters of a method definition if they span more than one line.
end
RUBY
expect_correction(<<~RUBY)
def method(a,
b)
end
RUBY
end
it 'accepts parameter lists on a single line' do
expect_no_offenses(<<~RUBY)
def method(a, b)
end
RUBY
end
it 'accepts proper indentation' do
expect_no_offenses(<<~RUBY)
def method(a,
b)
end
RUBY
end
it 'accepts the first parameter being on a new row' do
expect_no_offenses(<<~RUBY)
def method(
a,
b)
end
RUBY
end
it 'accepts a method definition without parameters' do
expect_no_offenses(<<~RUBY)
def method
end
RUBY
end
it "doesn't get confused by splat" do
expect_offense(<<~RUBY)
def func2(a,
*b,
^^ Align the parameters of a method definition if they span more than one line.
c)
end
RUBY
expect_correction(<<~RUBY)
def func2(a,
*b,
c)
end
RUBY
end
context 'defining self.method' do
it 'registers an offense and corrects parameters with single indent' do
expect_offense(<<~RUBY)
def self.method(a,
b)
^ Align the parameters of a method definition if they span more than one line.
end
RUBY
expect_correction(<<~RUBY)
def self.method(a,
b)
end
RUBY
end
it 'accepts proper indentation' do
expect_no_offenses(<<~RUBY)
def self.method(a,
b)
end
RUBY
end
end
it 'registers an offense and corrects alignment in simple case' do
expect_offense(<<~RUBY)
def func(a,
b,
^ Align the parameters of a method definition if they span more than one line.
c)
^ Align the parameters of a method definition if they span more than one line.
123
end
RUBY
expect_correction(<<~RUBY)
def func(a,
b,
c)
123
end
RUBY
end
end
context 'aligned with fixed indentation' do
let(:cop_config) { { 'EnforcedStyle' => 'with_fixed_indentation' } }
it 'registers an offense and corrects parameters aligned to first param' do
expect_offense(<<~RUBY)
def method(a,
b)
^ Use one level of indentation for parameters following the first line of a multi-line method definition.
end
RUBY
expect_correction(<<~RUBY)
def method(a,
b)
end
RUBY
end
it 'registers an offense and corrects parameters with double indent' do
expect_offense(<<~RUBY)
def method(a,
b)
^ Use one level of indentation for parameters following the first line of a multi-line method definition.
end
RUBY
expect_correction(<<~RUBY)
def method(a,
b)
end
RUBY
end
it 'accepts parameter lists on a single line' do
expect_no_offenses(<<~RUBY)
def method(a, b)
end
RUBY
end
it 'accepts proper indentation' do
expect_no_offenses(<<~RUBY)
def method(a,
b)
end
RUBY
end
it 'accepts the first parameter being on a new row' do
expect_no_offenses(<<~RUBY)
def method(
a,
b)
end
RUBY
end
it 'accepts a method definition without parameters' do
expect_no_offenses(<<~RUBY)
def method
end
RUBY
end
it "doesn't get confused by splat" do
expect_offense(<<~RUBY)
def func2(a,
*b,
^^ Use one level of indentation for parameters following the first line of a multi-line method definition.
c)
^ Use one level of indentation for parameters following the first line of a multi-line method definition.
end
RUBY
expect_correction(<<~RUBY)
def func2(a,
*b,
c)
end
RUBY
end
context 'defining self.method' do
it 'registers an offense and corrects parameters aligned to first param' do
expect_offense(<<~RUBY)
def self.method(a,
b)
^ Use one level of indentation for parameters following the first line of a multi-line method definition.
end
RUBY
expect_correction(<<~RUBY)
def self.method(a,
b)
end
RUBY
end
it 'accepts proper indentation' do
expect_no_offenses(<<~RUBY)
def self.method(a,
b)
end
RUBY
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/layout/else_alignment_spec.rb | spec/rubocop/cop/layout/else_alignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::ElseAlignment, :config do
let(:config) { RuboCop::Config.new('Layout/EndAlignment' => end_alignment_config) }
let(:end_alignment_config) { { 'Enabled' => true, 'EnforcedStyleAlignWith' => 'variable' } }
it 'accepts a ternary if' do
expect_no_offenses('cond ? func1 : func2')
end
context 'with if statement' do
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
if cond
func1
else
^^^^ Align `else` with `if`.
func2
end
RUBY
expect_correction(<<~RUBY)
if cond
func1
else
func2
end
RUBY
end
it 'registers an offense for misaligned elsif' do
expect_offense(<<-RUBY.strip_margin('|'))
| if a1
| b1
| elsif a2
| ^^^^^ Align `elsif` with `if`.
| b2
| end
RUBY
expect_correction(<<-RUBY.strip_margin('|'))
| if a1
| b1
| elsif a2
| b2
| end
RUBY
end
it 'accepts indentation after else when if is on new line after assignment' do
expect_no_offenses(<<~RUBY)
Rails.application.config.ideal_postcodes_key =
if Rails.env.production? || Rails.env.staging?
"AAAA-AAAA-AAAA-AAAA"
else
"BBBB-BBBB-BBBB-BBBB"
end
RUBY
end
it 'accepts a one line if statement' do
expect_no_offenses('if cond then func1 else func2 end')
end
it 'accepts a correctly aligned if/elsif/else/end' do
expect_no_offenses(<<~RUBY)
if a1
b1
elsif a2
b2
else
c
end
RUBY
end
context 'for a file with byte order mark' do
let(:bom) { "\xef\xbb\xbf" }
it 'accepts a correctly aligned if/elsif/else/end' do
expect_no_offenses(<<~RUBY)
#{bom}if a1
b1
elsif a2
b2
else
c
end
RUBY
end
end
context 'with assignment' do
context 'when alignment style is variable' do
context 'and end is aligned with variable' do
it 'accepts an if-else with end aligned with setter' do
expect_no_offenses(<<~RUBY)
foo.bar = if baz
derp1
else
derp2
end
RUBY
end
it 'accepts an if-elsif-else with end aligned with setter' do
expect_no_offenses(<<~RUBY)
foo.bar = if baz
derp1
elsif meh
derp2
else
derp3
end
RUBY
end
it 'accepts an if with end aligned with element assignment' do
expect_no_offenses(<<~RUBY)
foo[bar] = if baz
derp
end
RUBY
end
it 'accepts an if/else' do
expect_no_offenses(<<~RUBY)
var = if a
0
else
1
end
RUBY
end
it 'accepts an if/else with chaining after the end' do
expect_no_offenses(<<~RUBY)
var = if a
0
else
1
end.abc.join("")
RUBY
end
it 'accepts an if/else with chaining with a block after the end' do
expect_no_offenses(<<~RUBY)
var = if a
0
else
1
end.abc.tap {}
RUBY
end
end
context 'and end is aligned with keyword' do
it 'registers offenses for an if with setter' do
expect_offense(<<~RUBY)
foo.bar = if baz
derp1
elsif meh
^^^^^ Align `elsif` with `foo.bar`.
derp2
else
^^^^ Align `else` with `foo.bar`.
derp3
end
RUBY
end
it 'registers an offense for an if with element assignment' do
expect_offense(<<~RUBY)
foo[bar] = if baz
derp1
else
^^^^ Align `else` with `foo[bar]`.
derp2
end
RUBY
end
it 'registers an offense for an if' do
expect_offense(<<~RUBY)
var = if a
0
else
^^^^ Align `else` with `var`.
1
end
RUBY
end
end
end
shared_examples 'assignment and if with keyword alignment' do
context 'and end is aligned with variable' do
it 'registers an offense for an `if`' do
expect_offense(<<~RUBY)
var = if a
0
else b
^^^^ Align `else` with `if`.
1
end
RUBY
expect_correction(<<~RUBY)
var = if a
0
else b
1
end
RUBY
end
it 'registers an offense for an `elsif`' do
expect_offense(<<~RUBY)
var = if a
0
elsif b
^^^^^ Align `elsif` with `if`.
1
end
RUBY
expect_correction(<<~RUBY)
var = if a
0
elsif b
1
end
RUBY
end
it 'registers an offense for an `case`...`when`' do
expect_offense(<<~RUBY)
var = case condition
when a
0
else
^^^^ Align `else` with `when`.
1
end
RUBY
expect_correction(<<~RUBY)
var = case condition
when a
0
else
1
end
RUBY
end
it 'registers an offense for an `case`...`in`' do
expect_offense(<<~RUBY)
var = case expr
in a
0
else
^^^^ Align `else` with `in`.
1
end
RUBY
expect_correction(<<~RUBY)
var = case expr
in a
0
else
1
end
RUBY
end
end
context 'and end is aligned with keyword' do
it 'accepts an if in assignment' do
expect_no_offenses(<<~RUBY)
var = if a
0
end
RUBY
end
it 'accepts an if/else in assignment' do
expect_no_offenses(<<~RUBY)
var = if a
0
else
1
end
RUBY
end
it 'accepts an if/else in assignment on next line' do
expect_no_offenses(<<~RUBY)
var =
if a
0
else
1
end
RUBY
end
it 'accepts a while in assignment' do
expect_no_offenses(<<~RUBY)
var = while a
b
end
RUBY
end
it 'accepts an until in assignment' do
expect_no_offenses(<<~RUBY)
var = until a
b
end
RUBY
end
end
end
context 'when alignment style is keyword by choice' do
let(:end_alignment_config) do
{ 'Enabled' => true, 'EnforcedStyleAlignWith' => 'keyword' }
end
it_behaves_like 'assignment and if with keyword alignment'
end
end
it 'accepts an if/else branches with rescue clauses' do
# Because of how the rescue clauses come out of Parser, these are
# special and need to be tested.
expect_no_offenses(<<~RUBY)
if a
a rescue nil
else
a rescue nil
end
RUBY
end
end
context 'with unless' do
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
unless cond
func1
else
^^^^ Align `else` with `unless`.
func2
end
RUBY
end
it 'accepts a correctly aligned else in an otherwise empty unless' do
expect_no_offenses(<<~RUBY)
unless a
else
end
RUBY
end
it 'accepts an empty unless' do
expect_no_offenses(<<~RUBY)
unless a
end
RUBY
end
end
context 'with case' do
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
case a
when b
c
when d
e
else
^^^^ Align `else` with `when`.
f
end
RUBY
end
it 'accepts correctly aligned case/when/else' do
expect_no_offenses(<<~RUBY)
case a
when b
c
c
when d
else
f
end
RUBY
end
it 'accepts case without else' do
expect_no_offenses(<<~'RUBY')
case superclass
when /\A(#{NAMESPACEMATCH})(?:\s|\Z)/
$1
when "self"
namespace.path
end
RUBY
end
context '>= Ruby 2.7', :ruby27 do
context 'with case match' do
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
case 0
in 0
foo
in -1..1
bar
in Integer
baz
else
^^^^ Align `else` with `in`.
qux
end
RUBY
end
it 'accepts correctly aligned case/when/else' do
expect_no_offenses(<<~RUBY)
case 0
in 0
foo
in -1..1
bar
in Integer
baz
else
qux
end
RUBY
end
it 'accepts correctly aligned empty else' do
expect_no_offenses(<<~RUBY)
case 0
in 0
foo
in -1..1
bar
in Integer
baz
else
end
RUBY
end
it 'accepts case match without else' do
expect_no_offenses(<<~RUBY)
case 0
in a
p a
end
RUBY
end
end
end
it 'accepts else aligned with when but not with case' do
# "Indent when as deep as case" is the job of another cop, and this is
# one of the possible styles supported by configuration.
expect_no_offenses(<<~RUBY)
case code_type
when 'ruby', 'sql', 'plain'
code_type
when 'erb'
'ruby; html-script: true'
when "html"
'xml'
else
'plain'
end
RUBY
end
end
context 'with def/defs' do
it 'accepts an empty def body' do
expect_no_offenses(<<~RUBY)
def test
end
RUBY
end
it 'accepts an empty defs body' do
expect_no_offenses(<<~RUBY)
def self.test
end
RUBY
end
context 'when modifier and def are on the same line' do
it 'accepts a correctly aligned body' do
expect_no_offenses(<<~RUBY)
private def test
something
rescue
handling
else
something_else
end
RUBY
end
it 'registers an offense for else not aligned with private' do
expect_offense(<<~RUBY)
private def test
something
rescue
handling
else
^^^^ Align `else` with `private`.
something_else
end
RUBY
end
end
end
context 'with begin/rescue/else/ensure/end' do
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
def my_func
puts 'do something outside block'
begin
puts 'do something error prone'
rescue SomeException, SomeOther => e
puts 'wrongly intended error handling'
rescue
puts 'wrongly intended error handling'
else
^^^^ Align `else` with `begin`.
puts 'wrongly intended normal case handling'
ensure
puts 'wrongly intended common handling'
end
end
RUBY
end
it 'accepts a correctly aligned else' do
expect_no_offenses(<<~RUBY)
begin
raise StandardError.new('Fail') if rand(2).odd?
rescue StandardError => error
$stderr.puts error.message
else
$stdout.puts 'Lucky you!'
end
RUBY
end
end
context 'with def/rescue/else/ensure/end' do
it 'accepts a correctly aligned else' do
expect_no_offenses(<<~RUBY)
def my_func(string)
puts string
rescue => e
puts e
else
puts e
ensure
puts 'I love methods that print'
end
RUBY
end
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
def my_func(string)
puts string
rescue => e
puts e
else
^^^^ Align `else` with `def`.
puts e
ensure
puts 'I love methods that print'
end
RUBY
end
end
context 'with def/rescue/else/end' do
it 'accepts a correctly aligned else' do
expect_no_offenses(<<~RUBY)
def my_func
puts 'do something error prone'
rescue SomeException
puts 'error handling'
rescue
puts 'error handling'
else
puts 'normal handling'
end
RUBY
end
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
def my_func
puts 'do something error prone'
rescue SomeException
puts 'error handling'
rescue
puts 'error handling'
else
^^^^ Align `else` with `def`.
puts 'normal handling'
end
RUBY
end
end
context 'ensure/rescue/else in Block Argument' do
it 'accepts a correctly aligned else' do
expect_no_offenses(<<~RUBY)
array_like.each do |n|
puts 'do something error prone'
rescue SomeException
puts 'error handling'
rescue
puts 'error handling'
else
puts 'normal handling'
end
RUBY
end
it 'accepts a correctly aligned else from numblock' do
expect_no_offenses(<<~RUBY)
array_like.each do
_1
puts 'do something error prone'
rescue SomeException
puts 'error handling'
rescue
puts 'error handling'
else
puts 'normal handling'
end
RUBY
end
it 'accepts a correctly aligned else from itblock', :ruby34 do
expect_no_offenses(<<~RUBY)
array_like.each do
it
puts 'do something error prone'
rescue SomeException
puts 'error handling'
rescue
puts 'error handling'
else
puts 'normal handling'
end
RUBY
end
it 'accepts a correctly aligned else with assignment' do
expect_no_offenses(<<~RUBY)
result = array_like.each do |n|
puts 'do something error prone'
rescue SomeException
puts 'error handling'
rescue
puts 'error handling'
else
puts 'normal handling'
end
RUBY
end
it 'registers an offense for misaligned else' do
expect_offense(<<~RUBY)
array_like.each do |n|
puts 'do something error prone'
rescue SomeException
puts 'error handling'
rescue
puts 'error handling'
else
^^^^ Align `else` with `array_like.each`.
puts 'normal handling'
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/layout/multiline_array_brace_layout_spec.rb | spec/rubocop/cop/layout/multiline_array_brace_layout_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::MultilineArrayBraceLayout, :config do
let(:cop_config) { { 'EnforcedStyle' => 'symmetrical' } }
it 'ignores implicit arrays' do
expect_no_offenses(<<~RUBY)
foo = a,
b
RUBY
end
it 'ignores single-line arrays' do
expect_no_offenses('[a, b, c]')
end
it 'ignores empty arrays' do
expect_no_offenses('[]')
end
it_behaves_like 'multiline literal brace layout' do
let(:open) { '[' }
let(:close) { ']' }
end
it_behaves_like 'multiline literal brace layout method argument' do
let(:open) { '[' }
let(:close) { ']' }
let(:a) { 'a: 1' }
let(:b) { 'b: 2' }
end
it_behaves_like 'multiline literal brace layout trailing comma' do
let(:open) { '[' }
let(:close) { ']' }
let(:same_line_message) do
'The closing array brace must be on the same line as the last array ' \
'element when the opening [...]'
end
let(:always_same_line_message) do
'The closing array brace must be on the same line as the last array ' \
'element.'
end
end
context 'when comment present before closing brace' do
it 'corrects closing brace without crashing' do
expect_offense(<<~RUBY)
{
key1: [a, # comment 1
b # comment 2
],
^ The closing array brace must be on the same line as the last array element when the opening brace is on the same line as the first array element.
key2: 'foo'
}
RUBY
expect_correction(<<~RUBY)
{
key1: [a, # comment 1
b], # comment 2
key2: '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/layout/space_inside_parens_spec.rb | spec/rubocop/cop/layout/space_inside_parens_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::SpaceInsideParens, :config do
context 'when EnforcedStyle is no_space' do
let(:cop_config) { { 'EnforcedStyle' => 'no_space' } }
it 'registers an offense for spaces inside parens' do
expect_offense(<<~RUBY)
f( 3)
^ Space inside parentheses detected.
g = (a + 3 )
^ Space inside parentheses detected.
f( )
^ Space inside parentheses detected.
RUBY
expect_correction(<<~RUBY)
f(3)
g = (a + 3)
f()
RUBY
end
it 'registers an offense for space around heredoc start' do
expect_offense(<<~RUBY)
f( <<~HEREDOC )
^ Space inside parentheses detected.
^ Space inside parentheses detected.
This is my text
HEREDOC
RUBY
expect_correction(<<~RUBY)
f(<<~HEREDOC)
This is my text
HEREDOC
RUBY
end
it 'accepts parentheses in block parameter list' do
expect_no_offenses(<<~RUBY)
list.inject(Tms.new) { |sum, (label, item)|
}
RUBY
end
it 'accepts parentheses with no spaces' do
expect_no_offenses('split("\\n")')
end
it 'accepts parentheses with line break' do
expect_no_offenses(<<~RUBY)
f(
1)
RUBY
end
it 'accepts parentheses with comment and line break' do
expect_no_offenses(<<~RUBY)
f( # Comment
1)
RUBY
end
end
context 'when EnforcedStyle is space' do
let(:cop_config) { { 'EnforcedStyle' => 'space' } }
it 'registers an offense for no spaces inside parens' do
expect_offense(<<~RUBY)
f( 3)
^ No space inside parentheses detected.
g = (a + 3 )
^ No space inside parentheses detected.
split("\\n")
^ No space inside parentheses detected.
^ No space inside parentheses detected.
RUBY
expect_correction(<<~RUBY)
f( 3 )
g = ( a + 3 )
split( "\\n" )
RUBY
end
it 'registers an offense for space inside empty parens' do
expect_offense(<<~RUBY)
f( )
^ Space inside parentheses detected.
RUBY
expect_correction(<<~RUBY)
f()
RUBY
end
it 'registers an offense in block parameter list with no spaces' do
expect_offense(<<~RUBY)
list.inject( Tms.new ) { |sum, (label, item)|
^ No space inside parentheses detected.
^ No space inside parentheses detected.
}
RUBY
expect_correction(<<~RUBY)
list.inject( Tms.new ) { |sum, ( label, item )|
}
RUBY
end
it 'registers an offense for no space around heredoc start' do
expect_offense(<<~RUBY)
f(<<~HEREDOC)
^ No space inside parentheses detected.
^ No space inside parentheses detected.
This is my text
HEREDOC
RUBY
expect_correction(<<~RUBY)
f( <<~HEREDOC )
This is my text
HEREDOC
RUBY
end
it 'accepts empty parentheses without spaces' do
expect_no_offenses('f()')
end
it 'accepts parentheses with spaces' do
expect_no_offenses(<<~RUBY)
f( 3 )
g = ( a + 3 )
split( "\\n" )
RUBY
end
it 'accepts parentheses with line break' do
expect_no_offenses(<<~RUBY)
f(
1 )
RUBY
end
it 'accepts parentheses with comment and line break' do
expect_no_offenses(<<~RUBY)
f( # Comment
1 )
RUBY
end
end
context 'when EnforcedStyle is compact' do
let(:cop_config) { { 'EnforcedStyle' => 'compact' } }
it 'registers an offense for no spaces inside parens' do
expect_offense(<<~RUBY)
f( 3)
^ No space inside parentheses detected.
g = (a + 3 )
^ No space inside parentheses detected.
split("\\n")
^ No space inside parentheses detected.
^ No space inside parentheses detected.
RUBY
expect_correction(<<~RUBY)
f( 3 )
g = ( a + 3 )
split( "\\n" )
RUBY
end
it 'registers an offense for space inside empty parens' do
expect_offense(<<~RUBY)
f( )
^ Space inside parentheses detected.
RUBY
expect_correction(<<~RUBY)
f()
RUBY
end
it 'registers an offense in block parameter list with no spaces' do
expect_offense(<<~RUBY)
list.inject( Tms.new ) { |sum, (label, item)|
^ No space inside parentheses detected.
^ No space inside parentheses detected.
}
RUBY
expect_correction(<<~RUBY)
list.inject( Tms.new ) { |sum, ( label, item )|
}
RUBY
end
it 'registers an offense for no space around heredoc start' do
expect_offense(<<~RUBY)
f(<<~HEREDOC)
^ No space inside parentheses detected.
^ No space inside parentheses detected.
This is my text
HEREDOC
RUBY
expect_correction(<<~RUBY)
f( <<~HEREDOC )
This is my text
HEREDOC
RUBY
end
it 'accepts empty parentheses without spaces' do
expect_no_offenses('f()')
end
it 'accepts parentheses with spaces' do
expect_no_offenses(<<~RUBY)
f( 3 )
g = ( a + 3 )
split( "\\n" )
RUBY
end
it 'accepts parentheses with line break' do
expect_no_offenses(<<~RUBY)
f(
1 )
RUBY
end
it 'accepts parentheses with comment and line break' do
expect_no_offenses(<<~RUBY)
f( # Comment
1 )
RUBY
end
it 'accepts two consecutive left parentheses' do
expect_no_offenses(<<~RUBY)
f(( 3 + 5 ) * x )
RUBY
end
it 'accepts two consecutive right parentheses' do
expect_no_offenses(<<~RUBY)
f( x( 3 ))
g( f( x( 3 )), 5 )
RUBY
end
it 'accepts three consecutive left parentheses' do
expect_no_offenses(<<~RUBY)
g((( 3 + 5 ) * f ) ** x, 5 )
RUBY
end
it 'accepts three consecutive right parentheses' do
expect_no_offenses(<<~RUBY)
g( f( x( 3 )))
w( g( f( x( 3 ))), 5 )
RUBY
end
it 'registers an offense for space between consecutive brackets' do
expect_offense(<<~RUBY)
f( ( 3 + 5 ) * x )
^ Space inside parentheses detected.
g( ( ( 3 + 5 ) * f ) ** x, 5 )
^ Space inside parentheses detected.
^ Space inside parentheses detected.
f( x( 3 ) )
^ Space inside parentheses detected.
g( f( x( 3 ) ), 5 )
^ Space inside parentheses detected.
RUBY
expect_correction(<<~RUBY)
f(( 3 + 5 ) * x )
g((( 3 + 5 ) * f ) ** x, 5 )
f( x( 3 ))
g( f( x( 3 )), 5 )
RUBY
end
it 'registers multiple offenses for a missing and extra space between consecutive brackets' do
expect_offense(<<~RUBY)
g( (( 3 + 5 ) * f) ** x, 5)
^ No space inside parentheses detected.
^ No space inside parentheses detected.
^ Space inside parentheses detected.
(g( f( x( 3 ) ), 5 ) )
^ Space inside parentheses detected.
^ Space inside parentheses detected.
^ No space inside parentheses detected.
RUBY
expect_correction(<<~RUBY)
g((( 3 + 5 ) * f ) ** x, 5 )
( g( f( x( 3 )), 5 ))
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/layout/empty_lines_around_arguments_spec.rb | spec/rubocop/cop/layout/empty_lines_around_arguments_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::EmptyLinesAroundArguments, :config do
let(:empty_line_annotation) { '^{} Empty line detected around arguments.' }
context 'when extra lines' do
it 'registers and autocorrects offense for empty line before arg' do
expect_offense(<<~RUBY)
foo(
#{empty_line_annotation}
bar
)
RUBY
expect_correction(<<~RUBY)
foo(
bar
)
RUBY
end
it 'registers and autocorrects offense for empty line after arg' do
expect_offense(<<~RUBY)
bar(
[baz, qux]
#{empty_line_annotation}
)
RUBY
expect_correction(<<~RUBY)
bar(
[baz, qux]
)
RUBY
end
it 'registers and autocorrects offense for empty line between args' do
expect_offense(<<~RUBY)
foo.do_something(
baz,
#{empty_line_annotation}
qux: 0
)
RUBY
expect_correction(<<~RUBY)
foo.do_something(
baz,
qux: 0
)
RUBY
end
it 'registers and autocorrects offenses when multiple empty lines are detected' do
expect_offense(<<~RUBY)
foo(
baz,
#{empty_line_annotation}
qux,
#{empty_line_annotation}
biz,
#{empty_line_annotation}
)
RUBY
expect_correction(<<~RUBY)
foo(
baz,
qux,
biz,
)
RUBY
end
it 'registers and autocorrects offense when args start on definition line' do
expect_offense(<<~RUBY)
foo(biz,
#{empty_line_annotation}
baz: 0)
RUBY
expect_correction(<<~RUBY)
foo(biz,
baz: 0)
RUBY
end
it 'registers and autocorrects offense when empty line between normal arg & block arg' do
expect_offense(<<~RUBY)
Foo.prepend(
a,
#{empty_line_annotation}
Module.new do
def something; end
def anything; end
end
)
RUBY
expect_correction(<<~RUBY)
Foo.prepend(
a,
Module.new do
def something; end
def anything; end
end
)
RUBY
end
it 'registers and autocorrects offense on correct line for single offense example' do
expect_offense(<<~RUBY)
class Foo
include Bar
def baz(qux)
fizz(
qux,
#{empty_line_annotation}
10
)
end
end
RUBY
expect_correction(<<~RUBY)
class Foo
include Bar
def baz(qux)
fizz(
qux,
10
)
end
end
RUBY
end
it 'registers and autocorrects offense on correct lines for multi-offense example' do
expect_offense(<<~RUBY)
something(1, 5)
something_else
foo(biz,
#{empty_line_annotation}
qux)
quux.map do
end.another.thing(
#{empty_line_annotation}
[baz]
)
RUBY
expect_correction(<<~RUBY)
something(1, 5)
something_else
foo(biz,
qux)
quux.map do
end.another.thing(
[baz]
)
RUBY
end
context 'when using safe navigation operator' do
it 'registers and autocorrects offense for empty line before arg' do
expect_offense(<<~RUBY)
receiver&.foo(
#{empty_line_annotation}
bar
)
RUBY
expect_correction(<<~RUBY)
receiver&.foo(
bar
)
RUBY
end
end
it 'registers autocorrects empty line when args start on definition line' do
expect_offense(<<~RUBY)
bar(qux,
#{empty_line_annotation}
78)
RUBY
expect_correction(<<~RUBY)
bar(qux,
78)
RUBY
end
end
context 'when no extra lines' do
it 'accepts one line methods' do
expect_no_offenses(<<~RUBY)
foo(bar)
RUBY
end
it 'accepts multiple listed mixed args' do
expect_no_offenses(<<~RUBY)
foo(
bar,
[],
baz = nil,
qux: 2
)
RUBY
end
it 'accepts listed args starting on definition line' do
expect_no_offenses(<<~RUBY)
foo(bar,
[],
qux: 2)
RUBY
end
it 'accepts block argument with empty line' do
expect_no_offenses(<<~RUBY)
Foo.prepend(Module.new do
def something; end
def anything; end
end)
RUBY
end
it 'accepts method with argument that trails off block' do
expect_no_offenses(<<~RUBY)
fred.map do
<<-EOT
bar
foo
EOT
end.join("\n")
RUBY
end
it 'accepts method with no arguments that trails off block' do
expect_no_offenses(<<~RUBY)
foo.baz do
bar
end.compact
RUBY
end
it 'accepts method with argument that trails off heredoc' do
expect_no_offenses(<<~RUBY)
bar(<<-DOCS)
foo
DOCS
.call!(true)
RUBY
end
it 'accepts when blank line is inserted between method with arguments and receiver' do
expect_no_offenses(<<~RUBY)
foo.
bar(arg)
RUBY
end
it 'accepts multiline style argument for method call without selector' do
expect_no_offenses(<<~RUBY)
foo.(
arg
)
RUBY
end
it 'ignores a multiline string with only whitespace on one line and []-style method call after' do
expect_no_offenses(<<~RUBY)
format('%d
', 1)[0]
RUBY
end
context 'with one argument' do
it 'ignores empty lines inside of method arguments' do
expect_no_offenses(<<~RUBY)
private(def bar
baz
end)
RUBY
end
end
context 'with multiple arguments' do
it 'ignores empty lines inside of method arguments' do
expect_no_offenses(<<~RUBY)
foo(:bar, [1,
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/layout/empty_line_after_guard_clause_spec.rb | spec/rubocop/cop/layout/empty_line_after_guard_clause_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::EmptyLineAfterGuardClause, :config do
it 'does not register an offense when the clause is not followed by other code' do
expect_no_offenses(<<~RUBY)
return unless item.positive?
RUBY
end
it 'registers an offense and corrects a guard clause not followed by empty line' do
expect_offense(<<~RUBY)
def foo
return if need_return?
^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
foobar
end
RUBY
expect_correction(<<~RUBY)
def foo
return if need_return?
foobar
end
RUBY
end
context 'Ruby <= 3.2', :ruby32, unsupported_on: :prism do
it 'registers an offense and corrects `next` guard clause not followed by empty line' do
expect_offense(<<~RUBY)
def foo
next unless need_next? # comment
^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
foobar
end
RUBY
expect_correction(<<~RUBY)
def foo
next unless need_next? # comment
foobar
end
RUBY
end
end
it 'registers an offense and corrects a guard clause is before `begin`' do
expect_offense(<<~RUBY)
def foo
return another_object if something_different?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
begin
bar
rescue SomeException
baz
end
end
RUBY
expect_correction(<<~RUBY)
def foo
return another_object if something_different?
begin
bar
rescue SomeException
baz
end
end
RUBY
end
it 'registers an offense and corrects a `raise` guard clause not followed ' \
'by empty line when `unless` condition is after heredoc' do
expect_offense(<<~RUBY)
def foo
raise ArgumentError, <<-MSG unless path
Must be called with mount point
MSG
^^^^^ Add empty line after guard clause.
bar
end
RUBY
expect_correction(<<~RUBY)
def foo
raise ArgumentError, <<-MSG unless path
Must be called with mount point
MSG
bar
end
RUBY
end
it 'registers an offense and corrects a `raise` guard clause not followed ' \
'by empty line when `if` condition is after heredoc' do
expect_offense(<<~RUBY)
def foo
raise ArgumentError, <<-MSG if path
Must be called with mount point
MSG
^^^^^ Add empty line after guard clause.
bar
end
RUBY
expect_correction(<<~RUBY)
def foo
raise ArgumentError, <<-MSG if path
Must be called with mount point
MSG
bar
end
RUBY
end
it 'registers an offense and corrects a next guard clause not followed by ' \
'empty line when guard clause is after heredoc including string interpolation' do
expect_offense(<<~'RUBY')
raise(<<-FAIL) unless true
#{1 + 1}
FAIL
^^^^ Add empty line after guard clause.
1
RUBY
expect_correction(<<~'RUBY')
raise(<<-FAIL) unless true
#{1 + 1}
FAIL
1
RUBY
end
it 'accepts a `raise` guard clause not followed by empty line when guard ' \
'clause is after condition without method invocation' do
expect_no_offenses(<<~RUBY)
def foo
raise unless $1 == o
bar
end
RUBY
end
it 'registers an offense and corrects a `raise` guard clause not followed ' \
'by empty line when guard clause is after method call with argument' do
expect_offense(<<~'RUBY')
def foo
raise SerializationError.new("Unsupported argument type: #{argument.class.name}") unless serializer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
serializer.serialize(argument)
end
RUBY
expect_correction(<<~'RUBY')
def foo
raise SerializationError.new("Unsupported argument type: #{argument.class.name}") unless serializer
serializer.serialize(argument)
end
RUBY
end
it 'registers an offense and corrects when using `and return` before guard condition' do
expect_offense(<<~RUBY)
def foo
render :foo and return if condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
do_something
end
RUBY
expect_correction(<<~RUBY)
def foo
render :foo and return if condition
do_something
end
RUBY
end
it 'registers an offense and corrects when using `or return` before guard condition' do
expect_offense(<<~RUBY)
def foo
render :foo or return if condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
do_something
end
RUBY
expect_correction(<<~RUBY)
def foo
render :foo or return if condition
do_something
end
RUBY
end
it 'registers and corrects when using guard clause is after `rubocop:disable` comment' do
expect_offense(<<~RUBY)
def foo
return if condition
^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
# rubocop:disable Department/Cop
bar
# rubocop:enable Department/Cop
end
RUBY
expect_correction(<<~RUBY)
def foo
return if condition
# rubocop:disable Department/Cop
bar
# rubocop:enable Department/Cop
end
RUBY
end
it 'registers and corrects when using guard clause is after `rubocop:enable` comment' do
expect_offense(<<~RUBY)
def foo
# rubocop:disable Department/Cop
return if condition
^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
# rubocop:enable Department/Cop
bar
end
RUBY
expect_correction(<<~RUBY)
def foo
# rubocop:disable Department/Cop
return if condition
# rubocop:enable Department/Cop
bar
end
RUBY
end
it 'accepts modifier if' do
expect_no_offenses(<<~RUBY)
def foo
foo += 1 if need_add?
foobar
end
RUBY
end
it 'accepts a guard clause followed by empty line when guard clause including heredoc' do
expect_no_offenses(<<~RUBY)
def method
if truthy
raise <<-MSG
This is an error.
MSG
end
value
end
RUBY
end
it 'registers an offense and corrects a guard clause not followed by ' \
'empty line when guard clause including heredoc' do
expect_offense(<<~RUBY)
def method
if truthy
raise <<-MSG
This is an error.
MSG
end
^^^ Add empty line after guard clause.
value
end
RUBY
expect_correction(<<~RUBY)
def method
if truthy
raise <<-MSG
This is an error.
MSG
end
value
end
RUBY
end
it 'accepts a guard clause followed by end' do
expect_no_offenses(<<~RUBY)
def foo
if something?
return
end
end
RUBY
end
it 'accepts using guard clause is after `raise`' do
expect_no_offenses(<<~RUBY)
def foo
raise ArgumentError, 'HTTP redirect too deep' if limit.zero?
foobar
end
RUBY
end
it 'accepts using guard clause is after `rubocop:enable` comment' do
expect_no_offenses(<<~RUBY)
def foo
# rubocop:disable Department/Cop
return if condition
# rubocop:enable Department/Cop
bar
end
RUBY
end
it 'accepts using guard clause is after `:nocov:` comment' do
expect_no_offenses(<<~RUBY)
def foo
# :nocov:
return if condition
# :nocov:
bar
end
RUBY
end
it 'accepts a guard clause inside oneliner block' do
expect_no_offenses(<<~RUBY)
def foo
object.tap { |obj| return another_object if something? }
foobar
end
RUBY
end
it 'registers a guard clause outside difference line block' do
expect_offense(<<~RUBY)
return if condition
^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
foo do
bar
end
baz
RUBY
expect_correction(<<~RUBY)
return if condition
foo do
bar
end
baz
RUBY
end
it 'accepts a guard clause outside oneliner block' do
expect_no_offenses(<<~RUBY)
return if condition; foo do
bar
end
baz
RUBY
end
it 'accepts a guard clause outside oneliner numbered block' do
expect_no_offenses(<<~RUBY)
return if condition; foo do
bar(_1)
end
baz
RUBY
end
it 'accepts multiple guard clauses' do
expect_no_offenses(<<~RUBY)
def foo
return another_object if something?
return another_object if something_else?
return another_object if something_different?
foobar
end
RUBY
end
it 'accepts a modifier if when the next line is `end`' do
expect_no_offenses(<<~RUBY)
def foo
return another_object if something_different?
end
RUBY
end
it 'accepts a guard clause when the next line is `rescue`' do
expect_no_offenses(<<~RUBY)
def foo
begin
return another_object if something_different?
rescue SomeException
bar
end
end
RUBY
end
it 'accepts a guard clause when the next line is `ensure`' do
expect_no_offenses(<<~RUBY)
def foo
begin
return another_object if something_different?
ensure
bar
end
end
RUBY
end
it 'accepts a guard clause when the next line is `rescue`-`else`' do
expect_no_offenses(<<~RUBY)
def foo
begin
bar
rescue SomeException
return another_object if something_different?
else
bar
end
end
RUBY
end
it 'accepts a guard clause when the next line is `else`' do
expect_no_offenses(<<~RUBY)
def foo
if cond
return another_object if something_different?
else
bar
end
end
RUBY
end
it 'accepts a guard clause when the next line is `elsif`' do
expect_no_offenses(<<~RUBY)
def foo
if cond
return another_object if something_different?
elsif
bar
end
end
RUBY
end
it 'accepts a guard clause after a single line heredoc' do
expect_no_offenses(<<~RUBY)
def foo
raise ArgumentError, <<-MSG unless path
Must be called with mount point
MSG
bar
end
RUBY
end
it 'accepts a guard clause that is after multiline heredoc' do
expect_no_offenses(<<~RUBY)
def foo
raise ArgumentError, <<-MSG unless path
foo
bar
baz
MSG
bar
end
RUBY
end
it 'accepts a guard clause that is after a multiline heredoc with chained calls' do
expect_no_offenses(<<~RUBY)
def foo
raise ArgumentError, <<~END.squish.it.good unless guard
A multiline message
that will be squished.
END
return_value
end
RUBY
end
it 'accepts a guard clause that is after a multiline heredoc nested argument call' do
expect_no_offenses(<<~RUBY)
def foo
raise ArgumentError, call(<<~END.squish) unless guard
A multiline message
that will be squished.
END
return_value
end
RUBY
end
it 'accepts a guard clause that is after a multiline heredoc with parenthesized method call' do
expect_no_offenses(<<~RUBY)
def foo
raise ArgumentError, (<<~END.squish) unless guard
A multiline message
that will be squished.
END
return_value
end
RUBY
end
it 'does not register an offense when using `return` before guard condition with heredoc' do
expect_no_offenses(<<~RUBY)
def foo
return true if <<~TEXT.length > bar
hi
TEXT
false
end
RUBY
end
it 'does not register an offense when using `raise` before guard condition with heredoc' do
expect_no_offenses(<<~RUBY)
def foo
raise if <<~TEXT.length > bar
hi
TEXT
baz
end
RUBY
end
it 'registers an offense and corrects a guard clause that is a ternary operator' do
expect_offense(<<~RUBY)
def foo
puts 'some action happens here'
rescue => e
a_check ? raise(e) : other_thing
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
true
end
RUBY
expect_correction(<<~RUBY)
def foo
puts 'some action happens here'
rescue => e
a_check ? raise(e) : other_thing
true
end
RUBY
end
it 'registers an offense and corrects a method starting with end_' do
expect_offense(<<~RUBY)
def foo
return unless need_next?
^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
end_this!
end
RUBY
expect_correction(<<~RUBY)
def foo
return unless need_next?
end_this!
end
RUBY
end
it 'registers an offense and corrects only the last guard clause' do
expect_offense(<<~RUBY)
def foo
return if foo?
return if bar?
^^^^^^^^^^^^^^ Add empty line after guard clause.
foobar
end
RUBY
expect_correction(<<~RUBY)
def foo
return if foo?
return if bar?
foobar
end
RUBY
end
it 'registers no offenses using heredoc with `and return` before guard condition with empty line' do
expect_no_offenses(<<~RUBY)
def foo
puts(<<~MSG) and return if bar
A multiline
message
MSG
baz
end
RUBY
end
it 'registers an offense and corrects using heredoc with `and return` before guard condition' do
expect_offense(<<~RUBY)
def foo
puts(<<~MSG) and return if bar
A multiline
message
MSG
^^^^^ Add empty line after guard clause.
baz
end
RUBY
expect_correction(<<~RUBY)
def foo
puts(<<~MSG) and return if bar
A multiline
message
MSG
baz
end
RUBY
end
it 'does not register an offense when there are multiple clauses on the same line' do
expect_no_offenses(<<~RUBY)
def foo(item)
return unless item.positive?; item * 2
end
RUBY
end
it 'registers an offense when the clause ends with a semicolon but the next clause is on the next line' do
expect_offense(<<~RUBY)
def foo(item)
return unless item.positive?;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add empty line after guard clause.
item * 2
end
RUBY
expect_correction(<<~RUBY)
def foo(item)
return unless item.positive?;
item * 2
end
RUBY
end
it 'does not register an offense when calling a method on the result of a single-line `if` with `return`' do
expect_no_offenses(<<~RUBY)
if cond then return end.then { 42 }
RUBY
end
it 'does not register an offense when the clause ends with a semicolon but is followed by a newline' do
expect_no_offenses(<<~RUBY)
def foo(item)
return unless item.positive?;
item * 2
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/layout/multiline_method_call_indentation_spec.rb | spec/rubocop/cop/layout/multiline_method_call_indentation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::MultilineMethodCallIndentation, :config do
let(:config) do
merged = RuboCop::ConfigLoader
.default_configuration['Layout/MultilineMethodCallIndentation']
.merge(cop_config)
.merge('IndentationWidth' => cop_indent)
RuboCop::Config
.new('Layout/MultilineMethodCallIndentation' => merged,
'Layout/IndentationWidth' => { 'Width' => indentation_width })
end
let(:indentation_width) { 2 }
let(:cop_indent) { nil } # use indentation width from Layout/IndentationWidth
shared_examples 'common' do
it 'accepts indented methods in LHS of []= assignment' do
expect_no_offenses(<<~RUBY)
a
.b[c] = 0
RUBY
end
it 'accepts indented methods inside and outside a block' do
expect_no_offenses(<<~RUBY)
a = b.map do |c|
c
.b
.d do
x
.y
end
end
RUBY
end
it 'accepts indentation relative to first receiver' do
expect_no_offenses(<<~RUBY)
node
.children.map { |n| string_source(n) }.compact
.any? { |s| preferred.any? { |d| s.include?(d) } }
RUBY
end
it 'accepts indented methods in ordinary statement' do
expect_no_offenses(<<~RUBY)
a.
b
RUBY
end
it 'accepts no extra indentation of third line' do
expect_no_offenses(<<~RUBY)
a.
b.
c
RUBY
end
it 'accepts indented methods in for body' do
expect_no_offenses(<<~RUBY)
for x in a
something.
something_else
end
RUBY
end
it 'accepts alignment inside a grouped expression' do
expect_no_offenses(<<~RUBY)
(a.
b)
RUBY
end
it 'accepts arithmetic operation with block inside a grouped expression' do
expect_no_offenses(<<~RUBY)
(
a * b do
end
)
.c
RUBY
end
it 'accepts an expression where the first method spans multiple lines' do
expect_no_offenses(<<~RUBY)
subject.each do |item|
result = resolve(locale) and return result
end.a
RUBY
end
it 'accepts any indentation of parameters to #[]' do
expect_no_offenses(<<~RUBY)
payment = Models::IncomingPayments[
id: input['incoming-payment-id'],
user_id: @user[:id]]
RUBY
end
it 'accepts aligned methods when multiline method chain with a block argument and method chain' do
expect_no_offenses(<<~RUBY)
a(b)
.c(
d do
end.f
)
RUBY
end
it "doesn't crash on unaligned multiline lambdas" do
expect_no_offenses(<<~RUBY)
MyClass.(my_args)
.my_method
RUBY
end
it 'accepts alignment of method with assignment and operator-like method' do
expect_no_offenses(<<~RUBY)
query = x.|(
foo,
bar
)
RUBY
end
end
shared_examples 'common for aligned and indented' do
it 'accepts even indentation of consecutive lines in typical RSpec code' do
expect_no_offenses(<<~RUBY)
expect { Foo.new }.
to change { Bar.count }.
from(1).to(2)
RUBY
end
it 'registers an offense and corrects no indentation of second line' do
expect_offense(<<~RUBY)
a.
b
^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a.
b
RUBY
end
it 'registers an offense and corrects 3 spaces indentation of 2nd line' do
expect_offense(<<~RUBY)
a.
b
^ Use 2 (not 3) spaces for indenting an expression spanning multiple lines.
c.
d
^ Use 2 (not 3) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a.
b
c.
d
RUBY
end
it 'registers an offense and corrects extra indentation of third line' do
expect_offense(<<~RUBY)
a.
b.
c
^ Use 2 (not 4) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a.
b.
c
RUBY
end
it 'registers an offense and corrects the emacs ruby-mode 1.1 ' \
'indentation of an expression in an array' do
expect_offense(<<~RUBY)
[
a.
b
^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
]
RUBY
expect_correction(<<~RUBY)
[
a.
b
]
RUBY
end
it 'registers an offense and corrects extra indentation of 3rd line in typical RSpec code' do
expect_offense(<<~RUBY)
expect { Foo.new }.
to change { Bar.count }.
from(1).to(2)
^^^^ Use 2 (not 6) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
expect { Foo.new }.
to change { Bar.count }.
from(1).to(2)
RUBY
end
it 'registers an offense and corrects proc call without a selector' do
expect_offense(<<~RUBY)
a
.(args)
^^ Use 2 (not 1) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a
.(args)
RUBY
end
it 'registers an offense and corrects one space indentation of 2nd line' do
expect_offense(<<~RUBY)
a
.b
^^ Use 2 (not 1) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a
.b
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense and corrects no indentation of second line' do
expect_offense(<<~RUBY)
a&.
b
^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a&.
b
RUBY
end
it 'registers an offense and corrects 3 spaces indentation of 2nd line' do
expect_offense(<<~RUBY)
a&.
b
^ Use 2 (not 3) spaces for indenting an expression spanning multiple lines.
c&.
d
^ Use 2 (not 3) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a&.
b
c&.
d
RUBY
end
it 'registers an offense and corrects extra indentation of third line' do
expect_offense(<<~RUBY)
a&.
b&.
c
^ Use 2 (not 4) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a&.
b&.
c
RUBY
end
it 'registers an offense and corrects the emacs ruby-mode 1.1 ' \
'indentation of an expression in an array' do
expect_offense(<<~RUBY)
[
a&.
b
^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
]
RUBY
expect_correction(<<~RUBY)
[
a&.
b
]
RUBY
end
it 'registers an offense and corrects extra indentation of 3rd line in typical RSpec code' do
expect_offense(<<~RUBY)
expect { Foo.new }&.
to change { Bar.count }&.
from(1)&.to(2)
^^^^ Use 2 (not 6) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
expect { Foo.new }&.
to change { Bar.count }&.
from(1)&.to(2)
RUBY
end
it 'registers an offense and corrects proc call without a selector' do
expect_offense(<<~RUBY)
a
&.(args)
^^^ Use 2 (not 1) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a
&.(args)
RUBY
end
it 'registers an offense and corrects one space indentation of 2nd line' do
expect_offense(<<~RUBY)
a
&.b
^^^ Use 2 (not 1) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a
&.b
RUBY
end
it 'accepts aligned methods when multiline method chain with a block argument and method chain' do
expect_no_offenses(<<~RUBY)
a&.(b)
.c(
d do
end.f
)
RUBY
end
it "doesn't crash on multiline method calls with safe navigation and assignment" do
expect_offense(<<~RUBY)
MyClass.
foo&.bar = 'baz'
^^^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
MyClass.
foo&.bar = 'baz'
RUBY
end
end
end
context 'when EnforcedStyle is aligned' do
let(:cop_config) { { 'EnforcedStyle' => 'aligned' } }
it_behaves_like 'common'
it_behaves_like 'common for aligned and indented'
it "doesn't fail on unary operators" do
expect_offense(<<~RUBY)
def foo
!0
.nil?
^^^^^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
end
RUBY
end
# We call it semantic alignment when a dot is aligned with the first dot in
# a chain of calls, and that first dot does not begin its line.
context 'for semantic alignment' do
it 'accepts method being aligned with method' do
expect_no_offenses(<<~RUBY)
User.all.first
.age.to_s
RUBY
end
it 'accepts methods being aligned with method that is an argument' do
expect_no_offenses(<<~RUBY)
authorize scope.includes(:user)
.where(name: 'Bob')
.order(:name)
RUBY
end
it 'accepts methods being aligned with safe navigation method call that is an argument' do
expect_no_offenses(<<~RUBY)
do_something obj.foo(key: value)
&.bar(arg)
RUBY
end
context '>= Ruby 2.7', :ruby27 do
it 'accepts methods being aligned with method that is an argument' \
'when using numbered parameter' do
expect_no_offenses(<<~RUBY)
File.read('data.yml')
.then { YAML.safe_load _1 }
.transform_values(&:downcase)
RUBY
end
end
context '>= Ruby 3.4', :ruby34 do
it 'accepts methods being aligned with method that is an argument' \
'when using `it` parameter' do
expect_no_offenses(<<~RUBY)
File.read('data.yml')
.then { YAML.safe_load it }
.transform_values(&:downcase)
RUBY
end
end
it 'accepts methods being aligned with method that is an argument in assignment' do
expect_no_offenses(<<~RUBY)
user = authorize scope.includes(:user)
.where(name: 'Bob')
.order(:name)
RUBY
end
it 'accepts method being aligned with method in assignment' do
expect_no_offenses(<<~RUBY)
age = User.all.first
.age.to_s
RUBY
end
it 'accepts aligned method even when an aref is in the chain' do
expect_no_offenses(<<~RUBY)
foo = '123'.a
.b[1]
.c
RUBY
end
it 'accepts aligned method even when an aref is first in the chain' do
expect_no_offenses(<<~RUBY)
foo = '123'[1].a
.b
.c
RUBY
end
it "doesn't fail on a chain of aref calls" do
expect_no_offenses('a[1][2][3]')
end
it 'accepts aligned method with blocks in operation assignment' do
expect_no_offenses(<<~RUBY)
@comment_lines ||=
src.comments
.select { |c| begins_its_line?(c) }
.map { |c| c.loc.line }
RUBY
end
it 'accepts key access to hash' do
expect_no_offenses(<<~RUBY)
hash[key] { 10 / 0 }
.fmap { |x| x * 3 }
RUBY
end
it 'accepts 3 aligned methods' do
expect_no_offenses(<<~RUBY)
a_class.new(severity, location, 'message', 'CopName')
.severity
.level
RUBY
end
it 'registers an offense and corrects unaligned methods' do
expect_offense(<<~RUBY)
User.a
.b
^^ Align `.b` with `.a` on line 1.
.c
^^ Align `.c` with `.a` on line 1.
RUBY
expect_correction(<<~RUBY)
User.a
.b
.c
RUBY
end
it 'registers an offense and corrects unaligned method in block body' do
expect_offense(<<~RUBY)
a do
b.c
.d
^^ Align `.d` with `.c` on line 2.
end
RUBY
expect_correction(<<~RUBY)
a do
b.c
.d
end
RUBY
end
it 'accepts nested method calls' do
expect_no_offenses(<<~RUBY)
expect { post :action, params: params, format: :json }.to change { Foo.bar }.by(0)
.and change { Baz.quux }.by(0)
.and raise_error(StandardError)
RUBY
end
end
it 'accepts correctly aligned methods in operands' do
expect_no_offenses(<<~RUBY)
1 + a
.b
.c + d.
e
RUBY
end
it 'accepts correctly aligned methods in assignment' do
expect_no_offenses(<<~RUBY)
def investigate(processed_source)
@modifier = processed_source
.tokens
.select { |t| t.type == :k }
.map(&:pos)
end
RUBY
end
it 'accepts aligned methods in if + assignment' do
expect_no_offenses(<<~RUBY)
KeyMap = Hash.new do |map, key|
value = if key.respond_to?(:to_str)
key
else
key.to_s.split('_').
each { |w| w.capitalize! }.
join('-')
end
keymap_mutex.synchronize { map[key] = value }
end
RUBY
end
it 'accepts indented method when there is nothing to align with' do
expect_no_offenses(<<~RUBY)
expect { custom_formatter_class('NonExistentClass') }
.to raise_error(NameError)
RUBY
end
it 'registers an offense and corrects one space indentation of 3rd line' do
expect_offense(<<~RUBY)
a
.b
.c
^^ Use 2 (not 1) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a
.b
.c
RUBY
end
it 'accepts indented and aligned methods in binary operation' do
# b is indented relative to a
# .d is aligned with c
expect_no_offenses(<<~RUBY)
a.
b + c
.d
RUBY
end
it 'accepts aligned methods in if condition' do
expect_no_offenses(<<~RUBY)
if a.
b
something
end
RUBY
end
it 'accepts aligned methods in a begin..end block' do
expect_no_offenses(<<~RUBY)
@dependencies ||= begin
DEFAULT_DEPRUBYENCIES
.reject { |e| e }
.map { |e| e }
end
RUBY
end
it 'registers an offense and corrects misaligned methods in if condition' do
expect_offense(<<~RUBY)
if a.
b
^ Align `b` with `a.` on line 1.
something
end
RUBY
expect_correction(<<~RUBY)
if a.
b
something
end
RUBY
end
it 'does not check binary operations when string wrapped with backslash' do
expect_no_offenses(<<~'RUBY')
flash[:error] = 'Here is a string ' \
'That spans' <<
'multiple lines'
RUBY
end
it 'does not check binary operations when string wrapped with +' do
expect_no_offenses(<<~RUBY)
flash[:error] = 'Here is a string ' +
'That spans' <<
'multiple lines'
RUBY
end
it 'registers an offense and corrects misaligned method in []= call' do
expect_offense(<<~RUBY)
flash[:error] = here_is_a_string.
that_spans.
multiple_lines
^^^^^^^^^^^^^^ Align `multiple_lines` with `here_is_a_string.` on line 1.
RUBY
expect_correction(<<~RUBY)
flash[:error] = here_is_a_string.
that_spans.
multiple_lines
RUBY
end
it 'registers an offense and corrects misaligned methods in unless condition' do
expect_offense(<<~RUBY)
unless a
.b
^^ Align `.b` with `a` on line 1.
something
end
RUBY
expect_correction(<<~RUBY)
unless a
.b
something
end
RUBY
end
it 'registers an offense and corrects misaligned methods in while condition' do
expect_offense(<<~RUBY)
while a.
b
^ Align `b` with `a.` on line 1.
something
end
RUBY
expect_correction(<<~RUBY)
while a.
b
something
end
RUBY
end
it 'registers an offense and corrects misaligned methods in until condition' do
expect_offense(<<~RUBY)
until a.
b
^ Align `b` with `a.` on line 1.
something
end
RUBY
expect_correction(<<~RUBY)
until a.
b
something
end
RUBY
end
it 'accepts aligned method in return' do
expect_no_offenses(<<~RUBY)
def a
return b.
c
end
RUBY
end
it 'accepts aligned method in assignment + block + assignment' do
expect_no_offenses(<<~RUBY)
a = b do
c.d = e.
f
end
RUBY
end
it 'accepts aligned methods in assignment' do
expect_no_offenses(<<~RUBY)
formatted_int = int_part
.to_s
.reverse
.gsub(/...(?=.)/, '&_')
RUBY
end
it 'registers an offense and corrects misaligned methods in multiline block chain' do
expect_offense(<<~RUBY)
do_something.foo do
end.bar
.baz
^^^^ Align `.baz` with `.bar` on line 2.
RUBY
expect_correction(<<~RUBY)
do_something.foo do
end.bar
.baz
RUBY
end
it 'accepts aligned methods in multiline block chain' do
expect_no_offenses(<<~RUBY)
do_something.foo do
end.bar
.baz
RUBY
end
it 'accepts aligned methods in multiline numbered block chain' do
expect_no_offenses(<<~RUBY)
do_something.foo do
bar(_1)
end.baz
.qux
RUBY
end
it 'accepts aligned methods in multiline `it` block chain', :ruby34 do
expect_no_offenses(<<~RUBY)
do_something.foo do
bar(it)
end.baz
.qux
RUBY
end
it 'accepts aligned methods in multiline block chain with safe navigation operator' do
expect_no_offenses(<<~RUBY)
do_something.foo do
end&.bar
&.baz
RUBY
end
it 'registers an offense and corrects misaligned methods in local variable assignment' do
expect_offense(<<~RUBY)
a = b.c.
d
^ Align `d` with `b.c.` on line 1.
RUBY
expect_correction(<<~RUBY)
a = b.c.
d
RUBY
end
it 'accepts aligned methods in constant assignment' do
expect_no_offenses(<<~RUBY)
A = b
.c
RUBY
end
it 'accepts aligned methods in operator assignment' do
expect_no_offenses(<<~RUBY)
a +=
b
.c
RUBY
end
it 'registers an offense and corrects unaligned methods in assignment' do
expect_offense(<<~RUBY)
bar = Foo
.a
^^ Align `.a` with `Foo` on line 1.
.b(c)
RUBY
expect_correction(<<~RUBY)
bar = Foo
.a
.b(c)
RUBY
end
end
shared_examples 'both indented* styles' do
# We call it semantic alignment when a dot is aligned with the first dot in
# a chain of calls, and that first dot does not begin its line. But for the
# indented style, it doesn't come into play.
context 'for possible semantic alignment' do
it 'accepts indented methods' do
expect_no_offenses(<<~RUBY)
User.a
.c
.b
RUBY
end
end
end
context 'when EnforcedStyle is indented_relative_to_receiver' do
let(:cop_config) { { 'EnforcedStyle' => 'indented_relative_to_receiver' } }
it_behaves_like 'common'
it_behaves_like 'both indented* styles'
it "doesn't fail on unary operators" do
expect_offense(<<~RUBY)
def foo
!0
.nil?
^^^^^ Indent `.nil?` 2 spaces more than `0` on line 2.
end
RUBY
end
it 'accepts correctly indented methods in operation' do
expect_no_offenses(<<~RUBY)
1 + a
.b
.c
RUBY
end
it 'accepts indentation of consecutive lines in typical RSpec code' do
expect_no_offenses(<<~RUBY)
expect { Foo.new }.to change { Bar.count }
.from(1).to(2)
RUBY
end
it 'registers an offense and corrects no indentation of second line' do
expect_offense(<<~RUBY)
a.
b
^ Indent `b` 2 spaces more than `a` on line 1.
RUBY
expect_correction(<<~RUBY)
a.
b
RUBY
end
it 'registers an offense and corrects extra indentation of 3rd line in typical RSpec code' do
expect_offense(<<~RUBY)
expect { Foo.new }.
to change { Bar.count }.
from(1).to(2)
^^^^ Indent `from` 2 spaces more than `change { Bar.count }` on line 2.
RUBY
expect_correction(<<~RUBY)
expect { Foo.new }.
to change { Bar.count }.
from(1).to(2)
RUBY
end
it 'registers an offense and corrects proc call without a selector' do
expect_offense(<<~RUBY)
a
.(args)
^^ Indent `.(` 2 spaces more than `a` on line 1.
RUBY
expect_correction(<<~RUBY)
a
.(args)
RUBY
end
it 'does not register an offense when multiline method chain has expected indent width and ' \
'the method is preceded by splat' do
expect_no_offenses(<<~RUBY)
[
*foo
.bar(
arg)
]
RUBY
end
it 'does not register an offense when multiline method chain with block has expected indent width and ' \
'the method is preceded by splat' do
expect_no_offenses(<<~RUBY)
[
*foo
.bar { |arg| baz(arg) }
]
RUBY
end
it 'does not register an offense when multiline method chain with numbered block has expected indent width and ' \
'the method is preceded by splat' do
expect_no_offenses(<<~RUBY)
[
*foo
.bar { baz(_1) }
]
RUBY
end
it 'does not register an offense when multiline method chain with `it` block has expected indent width and ' \
'the method is preceded by splat', :ruby34 do
expect_no_offenses(<<~RUBY)
[
*foo
.bar { baz(it) }
]
RUBY
end
it 'does not register an offense when multiline method chain has expected indent width and ' \
'the method is preceded by double splat' do
expect_no_offenses(<<~RUBY)
[
**foo
.bar(
arg)
]
RUBY
end
it 'does not register an offense when multiline method chain with block has expected indent width and ' \
'the method is preceded by double splat' do
expect_no_offenses(<<~RUBY)
[
**foo
.bar { |arg| baz(arg) }
]
RUBY
end
it 'does not register an offense when multiline method chain with numbered block has expected indent width and ' \
'the method is preceded by double splat' do
expect_no_offenses(<<~RUBY)
[
**foo
.bar { baz(_1) }
]
RUBY
end
it 'does not register an offense when multiline method chain with `it` block has expected indent width and ' \
'the method is preceded by double splat', :ruby34 do
expect_no_offenses(<<~RUBY)
[
**foo
.bar { baz(it) }
]
RUBY
end
it 'registers an offense and corrects one space indentation of 2nd line' do
expect_offense(<<~RUBY)
a
.b
^^ Indent `.b` 2 spaces more than `a` on line 1.
RUBY
expect_correction(<<~RUBY)
a
.b
RUBY
end
it 'registers an offense and corrects 3 spaces indentation of second line' do
expect_offense(<<~RUBY)
a.
b
^ Indent `b` 2 spaces more than `a` on line 1.
c.
d
^ Indent `d` 2 spaces more than `c` on line 3.
RUBY
expect_correction(<<~RUBY)
a.
b
c.
d
RUBY
end
it 'registers an offense and corrects extra indentation of 3rd line' do
expect_offense(<<~RUBY)
a.
b.
c
^ Indent `c` 2 spaces more than `a` on line 1.
RUBY
expect_correction(<<~RUBY)
a.
b.
c
RUBY
end
it 'registers an offense and corrects the emacs ruby-mode 1.1 ' \
'indentation of an expression in an array' do
expect_offense(<<~RUBY)
[
a.
b
^ Indent `b` 2 spaces more than `a` on line 2.
]
RUBY
expect_correction(<<~RUBY)
[
a.
b
]
RUBY
end
end
context 'when EnforcedStyle is indented' do
let(:cop_config) { { 'EnforcedStyle' => 'indented' } }
it_behaves_like 'common'
it_behaves_like 'common for aligned and indented'
it_behaves_like 'both indented* styles'
it "doesn't fail on unary operators" do
expect_offense(<<~RUBY)
def foo
!0
.nil?
^^^^^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
end
RUBY
end
it 'accepts correctly indented methods in operation' do
expect_no_offenses(<<~RUBY)
1 + a
.b
.c
RUBY
end
it 'registers an offense and corrects 1 space indentation of 3rd line' do
expect_offense(<<~RUBY)
a
.b
.c
^^ Use 2 (not 1) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a
.b
.c
RUBY
end
it 'accepts indented methods in if condition' do
expect_no_offenses(<<~RUBY)
if a.
b
something
end
RUBY
end
it 'registers an offense and corrects 0 space indentation inside square brackets' do
expect_offense(<<~RUBY)
foo[
bar
.baz
^^^^ Use 2 (not 0) spaces for indenting an expression spanning multiple lines.
]
RUBY
expect_correction(<<~RUBY)
foo[
bar
.baz
]
RUBY
end
it 'registers an offense and corrects aligned methods in if condition' do
expect_offense(<<~RUBY)
if a.
b
^ Use 4 (not 3) spaces for indenting a condition in an `if` statement spanning multiple lines.
something
end
RUBY
expect_correction(<<~RUBY)
if a.
b
something
end
RUBY
end
it 'accepts normal indentation of method parameters' do
expect_no_offenses(<<~RUBY)
Parser::Source::Range.new(expr.source_buffer,
begin_pos,
begin_pos + line.length)
RUBY
end
it 'accepts any indentation of method parameters' do
expect_no_offenses(<<~RUBY)
a(b.
c
.d)
RUBY
end
it 'accepts normal indentation inside grouped expression' do
expect_no_offenses(<<~RUBY)
arg_array.size == a.size && (
arg_array == a ||
arg_array.map(&:children) == a.map(&:children)
)
RUBY
end
[
%w[an if],
%w[an unless],
%w[a while],
%w[an until]
].each do |article, keyword|
it "accepts double indentation of #{keyword} condition" do
expect_no_offenses(<<~RUBY)
#{keyword} receiver.
nil? &&
!args.empty?
end
RUBY
end
it "registers an offense for a 2 space indentation of #{keyword} condition" do
expect_offense(<<~RUBY)
#{keyword} receiver
.nil? &&
^^^^^ Use 4 (not 2) spaces for indenting a condition in #{article} `#{keyword}` statement spanning multiple lines.
!args.empty?
end
RUBY
end
it "accepts indented methods in #{keyword} body" do
expect_no_offenses(<<~RUBY)
#{keyword} a
something.
something_else
end
RUBY
end
end
%w[unless if].each do |keyword|
it "accepts special indentation of return #{keyword} condition" do
expect_no_offenses(<<~RUBY)
return #{keyword} receiver.nil? &&
!args.empty? &&
FORBIDDEN_METHODS.include?(method_name)
RUBY
end
end
it 'registers an offense and corrects wrong indentation of for expression' do
expect_offense(<<~RUBY)
for n in a.
b
^ Use 4 (not 2) spaces for indenting a collection in a `for` statement spanning multiple lines.
end
RUBY
expect_correction(<<~RUBY)
for n in a.
b
end
RUBY
end
it 'accepts special indentation of for expression' do
expect_no_offenses(<<~RUBY)
for n in a.
b
end
RUBY
end
shared_examples 'assignment' do |lhs|
it "accepts indentation of assignment to #{lhs} with rhs on same line" do
expect_no_offenses(<<~RUBY)
#{lhs} = int_part
.abs
.to_s
.reverse
.gsub(/...(?=.)/, '&_')
.reverse
RUBY
end
it "accepts indentation of assignment to #{lhs} with newline after =" do
expect_no_offenses(<<~RUBY)
#{lhs} =
int_part
.abs
.to_s
RUBY
end
it "accepts indentation of assignment to obj.#{lhs} with newline after =" do
expect_no_offenses(<<~RUBY)
obj.#{lhs} =
int_part
.abs
.to_s
RUBY
end
end
it_behaves_like 'assignment', 'a'
it_behaves_like 'assignment', 'a[:key]'
it 'registers an offense and corrects correct + unrecognized style' do
expect_offense(<<~RUBY)
a.
b
c.
d
^ Use 2 (not 4) spaces for indenting an expression spanning multiple lines.
RUBY
expect_correction(<<~RUBY)
a.
b
c.
d
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/layout/comment_indentation_spec.rb | spec/rubocop/cop/layout/comment_indentation_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::CommentIndentation, :config do
let(:config) do
RuboCop::Config
.new('Layout/IndentationWidth' => { 'Width' => indentation_width },
'Layout/CommentIndentation' => { 'AllowForAlignment' => allow_for_alignment })
end
let(:indentation_width) { 2 }
shared_examples 'any allow_for_alignment' do
context 'on outer level' do
it 'accepts a correctly indented comment' do
expect_no_offenses('# comment')
end
it 'accepts a comment that follows code' do
expect_no_offenses('hello # comment')
end
it 'registers an offense and corrects a documentation comment' do
expect_offense(<<~RUBY)
=begin
Doc comment
=end
hello
#
^ Incorrect indentation detected (column 1 instead of 0).
hi
RUBY
expect_correction(<<~RUBY)
=begin
Doc comment
=end
hello
#
hi
RUBY
end
it 'registers an offense and corrects an incorrectly indented (1) comment' do
expect_offense(<<-RUBY.strip_margin('|'))
| # comment
| ^^^^^^^^^ Incorrect indentation detected (column 1 instead of 0).
RUBY
expect_correction(<<~RUBY)
# comment
RUBY
end
it 'registers an offense and corrects an incorrectly indented (2) comment' do
expect_offense(<<-RUBY.strip_margin('|'))
| # comment
| ^^^^^^^^^ Incorrect indentation detected (column 2 instead of 0).
RUBY
expect_correction(<<~RUBY)
# comment
RUBY
end
it 'registers an offense for each incorrectly indented comment' do
expect_offense(<<~RUBY)
# a
^^^ Incorrect indentation detected (column 0 instead of 2).
# b
^^^ Incorrect indentation detected (column 2 instead of 4).
# c
^^^ Incorrect indentation detected (column 4 instead of 0).
# d
def test; end
RUBY
end
end
it 'registers offenses and corrects before __END__ but not after' do
expect_offense(<<~RUBY)
#
^ Incorrect indentation detected (column 1 instead of 0).
__END__
#
RUBY
expect_correction(<<~RUBY)
#
__END__
#
RUBY
end
context 'around program structure keywords' do
it 'accepts correctly indented comments' do
expect_no_offenses(<<~RUBY)
#
def m
#
if a
#
b
# this is accepted
elsif aa
# this is accepted
else
#
end
#
case a
# this is accepted
when 0
#
b
end
# this is accepted
case a
# this is accepted
in 0
#
b
end
# this is accepted
rescue
# this is accepted
ensure
#
end
#
RUBY
end
context 'with a blank line following the comment' do
it 'accepts a correctly indented comment' do
expect_no_offenses(<<~RUBY)
def m
# comment
end
RUBY
end
end
end
context 'near various kinds of brackets' do
it 'accepts correctly indented comments' do
expect_no_offenses(<<~RUBY)
#
a = {
#
x: [
1
#
],
#
y: func(
1
#
)
#
}
#
RUBY
end
it 'is unaffected by closing bracket that does not begin a line' do
expect_no_offenses(<<~RUBY)
#
result = []
RUBY
end
end
it 'registers an offense and corrects' do
expect_offense(<<~RUBY)
# comment 1
# comment 2
# comment 3
^^^^^^^^^^^ Incorrect indentation detected (column 1 instead of 0).
hash1 = { a: 0,
# comment 4
^^^^^^^^^^^ Incorrect indentation detected (column 5 instead of 10).
bb: 1,
ccc: 2 }
if a
#
^ Incorrect indentation detected (column 2 instead of 4).
b
# this is accepted
elsif aa
# so is this
elsif bb
#
^ Incorrect indentation detected (column 0 instead of 4).
else
#
^ Incorrect indentation detected (column 3 instead of 4).
end
case a
# this is accepted
when 0
# so is this
when 1
#
^ Incorrect indentation detected (column 5 instead of 4).
b
when 2
# this is also accepted
end
case a
# this is accepted
in 0
# so is this
in 1
#
^ Incorrect indentation detected (column 2 instead of 4).
b
in 2
# this is also accepted
end
RUBY
expect_correction(<<~RUBY)
# comment 1
# comment 2
# comment 3
hash1 = { a: 0,
# comment 4
bb: 1,
ccc: 2 }
if a
#
b
# this is accepted
elsif aa
# so is this
elsif bb
#
else
#
end
case a
# this is accepted
when 0
# so is this
when 1
#
b
when 2
# this is also accepted
end
case a
# this is accepted
in 0
# so is this
in 1
#
b
in 2
# this is also accepted
end
RUBY
end
end
context 'when allow_for_alignment is false' do
let(:allow_for_alignment) { false }
it_behaves_like 'any allow_for_alignment'
it 'registers an offense for comments with extra indentation' do
expect_offense(<<~RUBY)
def compile_sequence(seq, seq_var)
@seq_var = seq_var # Holds the name of the variable holding the AST::Node we are matching
context.with_temp_variables do |cur_child, cur_index, previous_index|
@cur_child_var = cur_child # To hold the current child node
@cur_index_var = cur_index # To hold the current child index (always >= 0)
@prev_index_var = previous_index # To hold the child index before we enter the looping nodes
@cur_index = :seq_head # Can be any of:
# :seq_head : when the current child is actually the sequence head
# :variadic_mode : child index held by @cur_index_var
# >= 0 : when the current child index is known (from the beginning)
# < 0 : when the index is known from the end, where -1 is *past the end*,
# -2 is the last child, etc...
# This shift of 1 from standard Ruby indices is stored in DELTA
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Incorrect indentation detected (column 38 instead of 4).
@in_sync = false # `true` iff `@cur_child_var` and `@cur_index_var` correspond to `@cur_index`
# Must be true if `@cur_index` is `:variadic_mode`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Incorrect indentation detected (column 38 instead of 4).
compile_terms(seq)
end
end
RUBY
end
end
context 'when allow_for_alignment is true' do
let(:allow_for_alignment) { true }
it_behaves_like 'any allow_for_alignment'
it 'accepts comments with extra indentation if aligned with comment on previous line' do
expect_no_offenses(<<~RUBY)
def compile_sequence(seq, seq_var)
@seq_var = seq_var # Holds the name of the variable holding the AST::Node we are matching
context.with_temp_variables do |cur_child, cur_index, previous_index|
@cur_child_var = cur_child # To hold the current child node
@cur_index_var = cur_index # To hold the current child index (always >= 0)
@prev_index_var = previous_index # To hold the child index before we enter the looping nodes
@cur_index = :seq_head # Can be any of:
# :seq_head : when the current child is actually the sequence head
# :variadic_mode : child index held by @cur_index_var
# >= 0 : when the current child index is known (from the beginning)
# < 0 : when the index is known from the end, where -1 is *past the end*,
# -2 is the last child, etc...
# This shift of 1 from standard Ruby indices is stored in DELTA
@in_sync = false # `true` iff `@cur_child_var` and `@cur_index_var` correspond to `@cur_index`
# Must be true if `@cur_index` is `:variadic_mode`
compile_terms(seq)
end
end
RUBY
end
end
context 'when `Layout/AccessModifierIndentation EnforcedStyle: outdent`' do
let(:indentation_width) { 2 }
let(:config) do
RuboCop::Config.new(
'Layout/AccessModifierIndentation' => {
'Enabled' => true,
'EnforcedStyle' => 'outdent'
},
'Layout/CommentIndentation' => {
'Enabled' => true
},
'Layout/IndentationWidth' => {
'Width' => indentation_width
}
)
end
it 'does not register an offense with indentation if aligned with code on previous line' do
expect_no_offenses(<<~RUBY)
class A
# rubocop:disable
def foo
end
# rubocop:enable
private
def bar
end
end
RUBY
end
it 'registers an offense with indentation if aligned with access modifier on next line' do
expect_offense(<<~RUBY)
class A
# rubocop:disable
def foo
end
# rubocop:enable
^^^^^^^^^^^^^^^^ Incorrect indentation detected (column 0 instead of 2).
private
def bar
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/layout/leading_comment_space_spec.rb | spec/rubocop/cop/layout/leading_comment_space_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::LeadingCommentSpace, :config do
it 'registers an offense and corrects comment without leading space' do
expect_offense(<<~RUBY)
#missing space
^^^^^^^^^^^^^^ Missing space after `#`.
RUBY
expect_correction(<<~RUBY)
# missing space
RUBY
end
it 'does not register an offense for # followed by no text' do
expect_no_offenses('#')
end
it 'does not register an offense for more than one space' do
expect_no_offenses('# heavily indented')
end
it 'does not register an offense for more than one #' do
expect_no_offenses('###### heavily indented')
end
it 'does not register an offense for only #s' do
expect_no_offenses('######')
end
it 'does not register an offense for #! on first line' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/ruby
test
RUBY
end
it 'does not register an offense for a multiline shebang starting on the first line' do
expect_no_offenses(<<~RUBY)
#!/usr/bin/env nix-shell
#! nix-shell -i ruby --pure
#! nix-shell -p ruby gh git
test
RUBY
end
it 'registers an offense and corrects #! after the first line' do
expect_offense(<<~RUBY)
test
#!/usr/bin/ruby
^^^^^^^^^^^^^^^ Missing space after `#`.
RUBY
expect_correction(<<~RUBY)
test
# !/usr/bin/ruby
RUBY
end
it 'registers an offense and corrects for a multiline shebang starting after the first line' do
expect_offense(<<~RUBY)
test
#!/usr/bin/env nix-shell
^^^^^^^^^^^^^^^^^^^^^^^^ Missing space after `#`.
#! nix-shell -i ruby --pure
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing space after `#`.
#! nix-shell -p ruby gh git
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing space after `#`.
RUBY
expect_correction(<<~RUBY)
test
# !/usr/bin/env nix-shell
# ! nix-shell -i ruby --pure
# ! nix-shell -p ruby gh git
RUBY
end
context 'file named config.ru' do
it 'does not register an offense for #\ on first line' do
expect_no_offenses(<<~'RUBY', 'config.ru')
#\ -w -p 8765
test
RUBY
end
it 'registers an offense and corrects for #\ after the first line' do
expect_offense(<<~'RUBY')
test
#\ -w -p 8765
^^^^^^^^^^^^^ Missing space after `#`.
RUBY
expect_correction(<<~'RUBY')
test
# \ -w -p 8765
RUBY
end
end
context 'file not named config.ru' do
it 'registers an offense and corrects #\ on first line' do
expect_offense(<<~'RUBY')
#\ -w -p 8765
^^^^^^^^^^^^^ Missing space after `#`.
test
RUBY
expect_correction(<<~'RUBY')
# \ -w -p 8765
test
RUBY
end
it 'registers an offense and corrects #\ after the first line' do
expect_offense(<<~'RUBY')
test
#\ -w -p 8765
^^^^^^^^^^^^^ Missing space after `#`.
RUBY
expect_correction(<<~'RUBY')
test
# \ -w -p 8765
RUBY
end
end
describe 'Doxygen style' do
context 'when config option is disabled' do
let(:cop_config) { { 'AllowDoxygenCommentStyle' => false } }
it 'registers an offense and corrects using Doxygen style' do
expect_offense(<<~RUBY)
#**
^^^ Missing space after `#`.
# Some comment
# Another comment on a second line
#*
^^ Missing space after `#`.
RUBY
expect_correction(<<~RUBY)
# **
# Some comment
# Another comment on a second line
# *
RUBY
end
end
context 'when config option is enabled' do
let(:cop_config) { { 'AllowDoxygenCommentStyle' => true } }
it 'does not register offense when using Doxygen style' do
expect_no_offenses(<<~RUBY)
#**
# Some comment
# Another comment on a second line
#*
RUBY
end
end
end
describe 'RDoc syntax' do
it 'does not register an offense when using `#++` or `#--`' do
expect_no_offenses(<<~RUBY)
#++
#--
RUBY
end
it 'registers an offense when using `#+` or `#-` as they are not RDoc comments' do
expect_offense(<<~RUBY)
#+
^^ Missing space after `#`.
#-
^^ Missing space after `#`.
RUBY
expect_correction(<<~RUBY)
# +
# -
RUBY
end
it 'registers an offense when starting `:`' do
expect_offense(<<~RUBY)
#:nodoc:
^^^^^^^^ Missing space after `#`.
RUBY
end
end
it 'accepts sprockets directives' do
expect_no_offenses('#= require_tree .')
end
it 'accepts =begin/=end comments' do
expect_no_offenses(<<~RUBY)
=begin
#blahblah
=end
RUBY
end
describe 'Gemfile Ruby comment' do
context 'when config option is disabled' do
let(:cop_config) { { 'AllowGemfileRubyComment' => false } }
it 'registers an offense when using ruby config as comment' do
expect_offense(<<~RUBY)
# Specific version (comment) will be used by RVM
#ruby=2.7.0
^^^^^^^^^^^ Missing space after `#`.
#ruby-gemset=myproject
^^^^^^^^^^^^^^^^^^^^^^ Missing space after `#`.
ruby '~> 2.7.0'
RUBY
end
end
context 'when config option is enabled' do
let(:cop_config) { { 'AllowGemfileRubyComment' => true } }
context 'file not named Gemfile' do
it 'registers an offense when using ruby config as comment' do
expect_offense(<<~RUBY, 'test/test_case.rb')
# Specific version (comment) will be used by RVM
#ruby=2.7.0
^^^^^^^^^^^ Missing space after `#`.
#ruby-gemset=myproject
^^^^^^^^^^^^^^^^^^^^^^ Missing space after `#`.
ruby '~> 2.7.0'
RUBY
end
end
context 'file named Gemfile' do
it 'does not register an offense when using ruby config as comment' do
expect_no_offenses(<<~RUBY, 'Gemfile')
# Specific version (comment) will be used by RVM
#ruby=2.7.0
#ruby-gemset=myproject
ruby '~> 2.7.0'
RUBY
end
end
end
end
describe 'RBS::Inline annotation' do
context 'when config option is disabled' do
let(:cop_config) { { 'AllowRBSInlineAnnotation' => false } }
it 'registers an offense and corrects using RBS::Inline annotation' do
expect_offense(<<~RUBY)
include Enumerable #[Integer]
^^^^^^^^^^ Missing space after `#`.
attr_reader :name #: String
^^^^^^^^^ Missing space after `#`.
attr_reader :age #: Integer?
^^^^^^^^^^^ Missing space after `#`.
#: (
^^^^ Missing space after `#`.
#| Integer,
^^^^^^^^^^^^^ Missing space after `#`.
#| String
^^^^^^^^^^^ Missing space after `#`.
#| ) -> void
^^^^^^^^^^^^ Missing space after `#`.
def foo; end
RUBY
expect_correction(<<~RUBY)
include Enumerable # [Integer]
attr_reader :name # : String
attr_reader :age # : Integer?
# : (
# | Integer,
# | String
# | ) -> void
def foo; end
RUBY
end
end
context 'when config option is enabled' do
let(:cop_config) { { 'AllowRBSInlineAnnotation' => true } }
it 'does not register an offense when using RBS::Inline annotation' do
expect_no_offenses(<<~RUBY)
include Enumerable #[Integer]
attr_reader :name #: String
attr_reader :age #: Integer?
#: (
#| Integer,
#| String
#| ) -> void
def foo; end
RUBY
end
end
end
describe 'Steep annotation' do
context 'when config option is disabled' do
let(:cop_config) { { 'AllowSteepAnnotation' => false } }
it 'registers an offense and corrects using Steep annotation' do
expect_offense(<<~RUBY)
[1, 2, 3].each_with_object([]) do |n, list| #$ Array[Integer]
^^^^^^^^^^^^^^^^^ Missing space after `#`.
list << n
end
name = 'John' #: String
^^^^^^^^^ Missing space after `#`.
RUBY
expect_correction(<<~RUBY)
[1, 2, 3].each_with_object([]) do |n, list| # $ Array[Integer]
list << n
end
name = 'John' # : String
RUBY
end
end
context 'when config option is enabled' do
let(:cop_config) { { 'AllowSteepAnnotation' => true } }
it 'does not register an offense when using Steep annotation' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].each_with_object([]) do |n, list| #$ Array[Integer]
list << n
end
name = 'John' #: String
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/layout/multiline_block_layout_spec.rb | spec/rubocop/cop/layout/multiline_block_layout_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::MultilineBlockLayout, :config do
it 'registers an offense for missing newline in do/end block w/o params' do
expect_offense(<<~RUBY)
test do foo
^^^ Block body expression is on the same line as the block start.
end
RUBY
expect_correction(<<~RUBY)
test do#{trailing_whitespace}
foo
end
RUBY
end
it 'registers an offense and corrects for missing newline in {} block w/o params' do
expect_offense(<<~RUBY)
test { foo
^^^ Block body expression is on the same line as the block start.
}
RUBY
expect_correction(<<~RUBY)
test {#{trailing_whitespace}
foo
}
RUBY
end
it 'registers an offense and corrects for missing newline in do/end block with params' do
expect_offense(<<~RUBY)
test do |x| foo
^^^ Block body expression is on the same line as the block start.
end
RUBY
expect_correction(<<~RUBY)
test do |x|#{trailing_whitespace}
foo
end
RUBY
end
it 'registers an offense and corrects for missing newline in {} block with params' do
expect_offense(<<~RUBY)
test { |x| foo
^^^ Block body expression is on the same line as the block start.
}
RUBY
expect_correction(<<~RUBY)
test { |x|#{trailing_whitespace}
foo
}
RUBY
end
it 'does not register an offense for one-line do/end blocks' do
expect_no_offenses('test do foo end')
end
it 'does not register an offense for one-line {} blocks' do
expect_no_offenses('test { foo }')
end
it 'does not register offenses when there is a newline for do/end block' do
expect_no_offenses(<<~RUBY)
test do
foo
end
RUBY
end
it 'does not register offenses when there are too many parameters to fit on one line' do
expect_no_offenses(<<~RUBY)
some_result = lambda do |
so_many,
parameters,
it_will,
be_too_long,
for_one_line,
line_length,
has_increased,
add_3_more|
do_something
end
RUBY
end
it 'registers offenses when there are not too many parameters to fit on one line' do
expect_offense(<<~RUBY)
some_result = lambda do |
^ Block argument expression is not on the same line as the block start.
so_many,
parameters,
it_will,
be_too_long,
for_one_line,
line_length,
has_increased,
add_3_mor|
do_something
end
RUBY
expect_correction(<<~RUBY)
some_result = lambda do |so_many, parameters, it_will, be_too_long, for_one_line, line_length, has_increased, add_3_mor|
do_something
end
RUBY
end
it 'considers the extra space required to join the lines together' do
expect_no_offenses(<<~RUBY)
some_result = lambda do
|so_many, parameters, it_will, be_too_long, for_one_line, line_length, has_increased, add_3_more|
do_something
end
RUBY
end
it 'does not error out when the block is empty' do
expect_no_offenses(<<~RUBY)
test do |x|
end
RUBY
end
it 'does not register offenses when there is a newline for {} block' do
expect_no_offenses(<<~RUBY)
test {
foo
}
RUBY
end
it 'registers offenses and corrects for lambdas' do
expect_offense(<<~RUBY)
-> (x) do foo
^^^ Block body expression is on the same line as the block start.
bar
end
RUBY
expect_correction(<<~RUBY)
-> (x) do#{trailing_whitespace}
foo
bar
end
RUBY
end
it 'registers offenses and corrects for new lambda literal syntax' do
expect_offense(<<~RUBY)
-> x do foo
^^^ Block body expression is on the same line as the block start.
bar
end
RUBY
expect_correction(<<~RUBY)
-> x do#{trailing_whitespace}
foo
bar
end
RUBY
end
it 'registers an offense and corrects line-break before arguments' do
expect_offense(<<~RUBY)
test do
|x| play_with(x)
^^^ Block argument expression is not on the same line as the block start.
end
RUBY
expect_correction(<<~RUBY)
test do |x|
play_with(x)
end
RUBY
end
it 'registers an offense and corrects line-break before arguments with empty block' do
expect_offense(<<~RUBY)
test do
|x|
^^^ Block argument expression is not on the same line as the block start.
end
RUBY
expect_correction(<<~RUBY)
test do |x|
end
RUBY
end
it 'registers an offense and corrects line-break within arguments' do
expect_offense(<<~RUBY)
test do |x,
^^^ Block argument expression is not on the same line as the block start.
y|
end
RUBY
expect_correction(<<~RUBY)
test do |x, y|
end
RUBY
end
it 'registers an offense and corrects a do/end block with a multi-line body' do
expect_offense(<<~RUBY)
test do |foo| bar
^^^ Block body expression is on the same line as the block start.
test
end
RUBY
expect_correction(<<~RUBY)
test do |foo|#{trailing_whitespace}
bar
test
end
RUBY
end
it 'autocorrects in more complex case with lambda and assignment, and ' \
'aligns the next line two spaces out from the start of the block' do
expect_offense(<<~RUBY)
x = -> (y) { foo
^^^ Block body expression is on the same line as the block start.
bar
}
RUBY
expect_correction(<<~RUBY)
x = -> (y) {#{trailing_whitespace}
foo
bar
}
RUBY
end
it 'registers an offense and corrects for missing newline before opening parenthesis `(` for block body' do
expect_offense(<<~RUBY)
foo do |o| (
^ Block body expression is on the same line as the block start.
bar
)
end
RUBY
expect_correction(<<~RUBY)
foo do |o|#{trailing_whitespace}
(
bar
)
end
RUBY
end
it 'registers an offense and corrects a line-break within arguments' do
expect_offense(<<~RUBY)
test do |x,
^^^ Block argument expression is not on the same line as the block start.
y| play_with(x, y)
end
RUBY
expect_correction(<<~RUBY)
test do |x, y|
play_with(x, y)
end
RUBY
end
it 'registers an offense and corrects a line break within destructured arguments' do
expect_offense(<<~RUBY)
test do |(x,
^^^^ Block argument expression is not on the same line as the block start.
y)| play_with(x, y)
end
RUBY
expect_correction(<<~RUBY)
test do |(x, y)|
play_with(x, y)
end
RUBY
end
it "doesn't move end keyword in a way which causes infinite loop " \
'in combination with Style/BlockEndNewLine' do
expect_offense(<<~RUBY)
def f
X.map do |(a,
^^^^ Block argument expression is not on the same line as the block start.
b)|
end
end
RUBY
expect_correction(<<~RUBY)
def f
X.map do |(a, b)|
end
end
RUBY
end
it 'does not remove a trailing comma when only one argument is present' do
expect_offense(<<~RUBY)
def f
X.map do |
^ Block argument expression is not on the same line as the block start.
a,
|
end
end
RUBY
expect_correction(<<~RUBY)
def f
X.map do |a,|
end
end
RUBY
end
it 'autocorrects nested parens correctly' do
expect_offense(<<~RUBY)
def f
X.map do |
^ Block argument expression is not on the same line as the block start.
(((a), b), c)
|
end
end
RUBY
expect_correction(<<~RUBY)
def f
X.map do |(((a), b), c)|
end
end
RUBY
end
context 'when `Layout/LineLength` is disabled' do
let(:config) do
RuboCop::Config.new('Layout/LineLength' => { 'Enabled' => false })
end
it 'registers an offense' do
expect_offense(<<~RUBY)
test do
|(x, y)|
^^^^^^^^ Block argument expression is not on the same line as the block start.
play_with(x, y)
end
RUBY
expect_correction(<<~RUBY)
test do |(x, y)|
play_with(x, y)
end
RUBY
end
end
context 'Ruby 2.7', :ruby27 do
it 'registers an offense and corrects for missing newline in {} block w/o params' do
expect_offense(<<~RUBY)
test { _1
^^ Block body expression is on the same line as the block start.
}
RUBY
expect_correction(<<~RUBY)
test {#{trailing_whitespace}
_1
}
RUBY
end
it 'registers an offense and corrects for missing newline in do/end block with params' do
expect_offense(<<~RUBY)
test do _1
^^ Block body expression is on the same line as the block start.
end
RUBY
expect_correction(<<~RUBY)
test do#{trailing_whitespace}
_1
end
RUBY
end
end
context 'Ruby 3.4', :ruby34 do
it 'registers an offense and corrects for missing newline in {} block w/o params' do
expect_offense(<<~RUBY)
test { it
^^ Block body expression is on the same line as the block start.
}
RUBY
expect_correction(<<~RUBY)
test {#{trailing_whitespace}
it
}
RUBY
end
it 'registers an offense and corrects for missing newline in do/end block with params' do
expect_offense(<<~RUBY)
test do it
^^ Block body expression is on the same line as the block start.
end
RUBY
expect_correction(<<~RUBY)
test do#{trailing_whitespace}
it
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/layout/dot_position_spec.rb | spec/rubocop/cop/layout/dot_position_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Layout::DotPosition, :config do
context 'Leading dots style' do
let(:cop_config) { { 'EnforcedStyle' => 'leading' } }
it 'registers an offense for trailing dot in multi-line call' do
expect_offense(<<~RUBY)
something.
^ Place the . on the next line, together with the method name.
method_name
RUBY
expect_correction(<<~RUBY)
something
.method_name
RUBY
end
it 'registers an offense for correct + opposite' do
expect_offense(<<~RUBY)
something
.method_name
something.
^ Place the . on the next line, together with the method name.
method_name
RUBY
expect_correction(<<~RUBY)
something
.method_name
something
.method_name
RUBY
end
it 'registers an offense for only dot line' do
expect_offense(<<~RUBY)
foo
.bar
.
^ Place the . on the next line, together with the method name.
baz
RUBY
expect_correction(<<~RUBY)
foo
.bar
.baz
RUBY
end
it 'accepts leading do in multi-line method call' do
expect_no_offenses(<<~RUBY)
something
.method_name
RUBY
end
it 'does not err on method call with no dots' do
expect_no_offenses('puts something')
end
it 'does not err on method call without a method name' do
expect_offense(<<~RUBY)
l.
^ Place the . on the next line, together with the method name.
(1)
RUBY
expect_correction(<<~RUBY)
l
.(1)
RUBY
end
it 'does not err on method call on same line' do
expect_no_offenses('something.method_name')
end
context 'when there is an intervening line comment' do
it 'does not register offense' do
expect_no_offenses(<<~RUBY)
something.
# a comment here
method_name
RUBY
end
end
context 'when there is an intervening blank line' do
it 'does not register offense' do
expect_no_offenses(<<~RUBY)
something.
method_name
RUBY
end
end
context 'when a method spans multiple lines' do
it 'registers an offense' do
expect_offense(<<~RUBY)
something(
foo, bar
).
^ Place the . on the next line, together with the method name.
method_name
RUBY
expect_correction(<<~RUBY)
something(
foo, bar
)
.method_name
RUBY
end
end
context 'when using safe navigation operator' do
it 'registers an offense for correct + opposite' do
expect_offense(<<~RUBY)
something
&.method_name
something&.
^^ Place the &. on the next line, together with the method name.
method_name
RUBY
expect_correction(<<~RUBY)
something
&.method_name
something
&.method_name
RUBY
end
it 'accepts leading do in multi-line method call' do
expect_no_offenses(<<~RUBY)
something
&.method_name
RUBY
end
end
context 'with multiple offenses' do
it 'registers all of them' do
expect_offense(<<~RUBY)
@objects = @objects.where(type: :a)
@objects = @objects.
^ Place the . on the next line, together with the method name.
with_relation.
^ Place the . on the next line, together with the method name.
paginate
RUBY
expect_correction(<<~RUBY)
@objects = @objects.where(type: :a)
@objects = @objects
.with_relation
.paginate
RUBY
end
end
context 'when the receiver has a heredoc argument' do
context 'as the last argument' do
it 'registers an offense' do
expect_offense(<<~RUBY)
my_method.
^ Place the . on the next line, together with the method name.
something(<<~HERE).
^ Place the . on the next line, together with the method name.
something
HERE
somethingelse
RUBY
expect_correction(<<~RUBY)
my_method
.something(<<~HERE)
something
HERE
.somethingelse
RUBY
end
end
context 'with a dynamic heredoc' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
my_method.
^ Place the . on the next line, together with the method name.
something(<<~HERE).
^ Place the . on the next line, together with the method name.
#{something}
HERE
somethingelse
RUBY
expect_correction(<<~'RUBY')
my_method
.something(<<~HERE)
#{something}
HERE
.somethingelse
RUBY
end
end
context 'with an xstr heredoc' do
it 'registers an offense' do
expect_offense(<<~RUBY)
my_method.
^ Place the . on the next line, together with the method name.
something(<<~`HERE`).
^ Place the . on the next line, together with the method name.
ls -la
HERE
somethingelse
RUBY
expect_correction(<<~RUBY)
my_method
.something(<<~`HERE`)
ls -la
HERE
.somethingelse
RUBY
end
end
context 'as the first argument' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
my_method.
^ Place the . on the next line, together with the method name.
something(<<~HERE, true).
^ Place the . on the next line, together with the method name.
#{something}
HERE
somethingelse
RUBY
expect_correction(<<~'RUBY')
my_method
.something(<<~HERE, true)
#{something}
HERE
.somethingelse
RUBY
end
end
context 'with multiple heredocs' do
it 'registers an offense' do
expect_offense(<<~RUBY)
my_method.
^ Place the . on the next line, together with the method name.
something(<<~HERE, <<~THERE).
^ Place the . on the next line, together with the method name.
something
HERE
another thing
THERE
somethingelse
RUBY
expect_correction(<<~RUBY)
my_method
.something(<<~HERE, <<~THERE)
something
HERE
another thing
THERE
.somethingelse
RUBY
end
end
context 'with another method on the same line' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo(<<~HEREDOC).squish
something
HEREDOC
RUBY
end
end
end
context 'when the receiver is a heredoc' do
it 'registers an offense' do
expect_offense(<<~RUBY)
<<~HEREDOC.
^ Place the . on the next line, together with the method name.
something
HEREDOC
method_name
RUBY
expect_correction(<<~RUBY)
<<~HEREDOC
something
HEREDOC
.method_name
RUBY
end
end
context 'when the receiver is an `xstr` heredoc' do
it 'registers an offense' do
expect_offense(<<~RUBY)
<<~`HEREDOC`.
^ Place the . on the next line, together with the method name.
ls -la
HEREDOC
method_name
RUBY
expect_correction(<<~RUBY)
<<~`HEREDOC`
ls -la
HEREDOC
.method_name
RUBY
end
end
end
context 'Trailing dots style' do
let(:cop_config) { { 'EnforcedStyle' => 'trailing' } }
it 'registers an offense for leading dot in multi-line call' do
expect_offense(<<~RUBY)
something
.method_name
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
something.
method_name
RUBY
end
it 'accepts trailing dot in multi-line method call' do
expect_no_offenses(<<~RUBY)
something.
method_name
RUBY
end
it 'does not err on method call with no dots' do
expect_no_offenses('puts something')
end
it 'does not err on method call with multi-line arguments' do
expect_no_offenses(<<~RUBY)
foo(
bar
).baz
RUBY
end
it 'does not err on method call without a method name' do
expect_offense(<<~RUBY)
l
.(1)
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
l.
(1)
RUBY
end
it 'does not err on method call on same line' do
expect_no_offenses('something.method_name')
end
it 'does not get confused by several lines of chained methods' do
expect_no_offenses(<<~RUBY)
File.new(something).
readlines.map.
compact.join("\n")
RUBY
end
context 'when using safe navigation operator' do
it 'registers an offense for correct + opposite' do
expect_offense(<<~RUBY)
something
&.method_name
^^ Place the &. on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
something&.
method_name
RUBY
end
it 'accepts trailing dot in multi-line method call' do
expect_no_offenses(<<~RUBY)
something&.
method_name
RUBY
end
end
context 'when the receiver has a heredoc argument' do
context 'as the last argument' do
it 'registers an offense' do
expect_offense(<<~RUBY)
my_method
.something(<<~HERE)
^ Place the . on the previous line, together with the method call receiver.
something
HERE
.somethingelse
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
my_method.
something(<<~HERE).
something
HERE
somethingelse
RUBY
end
end
context 'with a dynamic heredoc' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
my_method
.something(<<~HERE)
^ Place the . on the previous line, together with the method call receiver.
#{something}
HERE
.somethingelse
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~'RUBY')
my_method.
something(<<~HERE).
#{something}
HERE
somethingelse
RUBY
end
end
context 'with an `xstr` heredoc' do
it 'registers an offense' do
expect_offense(<<~RUBY)
my_method
.something(<<~`HERE`)
^ Place the . on the previous line, together with the method call receiver.
ls -la
HERE
.somethingelse
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
my_method.
something(<<~`HERE`).
ls -la
HERE
somethingelse
RUBY
end
end
context 'as the first argument' do
it 'registers an offense' do
expect_offense(<<~'RUBY')
my_method
.something(<<~HERE, true)
^ Place the . on the previous line, together with the method call receiver.
#{something}
HERE
.somethingelse
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~'RUBY')
my_method.
something(<<~HERE, true).
#{something}
HERE
somethingelse
RUBY
end
end
context 'with multiple heredocs' do
it 'registers an offense' do
expect_offense(<<~RUBY)
my_method
.something(<<~HERE, <<~THERE)
^ Place the . on the previous line, together with the method call receiver.
something
HERE
another thing
THERE
.somethingelse
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
my_method.
something(<<~HERE, <<~THERE).
something
HERE
another thing
THERE
somethingelse
RUBY
end
end
context 'with another method on the same line' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo(<<~HEREDOC).squish
something
HEREDOC
RUBY
end
end
end
context 'when the receiver is a heredoc' do
it 'registers an offense' do
expect_offense(<<~RUBY)
<<~HEREDOC
something
HEREDOC
.method_name
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
<<~HEREDOC.
something
HEREDOC
method_name
RUBY
end
end
context 'when the receiver is an `xstr` heredoc' do
it 'registers an offense' do
expect_offense(<<~RUBY)
<<~`HEREDOC`
ls -la
HEREDOC
.method_name
^ Place the . on the previous line, together with the method call receiver.
RUBY
expect_correction(<<~RUBY)
<<~`HEREDOC`.
ls -la
HEREDOC
method_name
RUBY
end
end
context 'when there is a heredoc with a following method' do
it 'does not register an offense for a heredoc' do
expect_no_offenses(<<~RUBY)
<<~HEREDOC.squish
something
HEREDOC
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/mixin/enforce_superclass_spec.rb | spec/rubocop/cop/mixin/enforce_superclass_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::EnforceSuperclass, :restore_registry do
subject(:cop) { cop_class.new(configuration) }
let(:cop_class) { RuboCop::Cop::RSpec::ApplicationRecord }
let(:msg) { 'Models should subclass `ApplicationRecord`' }
before do
stub_cop_class('RuboCop::Cop::RSpec::ApplicationRecord')
stub_const("#{cop_class}::MSG", 'Models should subclass `ApplicationRecord`')
stub_const("#{cop_class}::SUPERCLASS", 'ApplicationRecord')
stub_const("#{cop_class}::BASE_PATTERN", '(const (const {nil? cbase} :ActiveRecord) :Base)')
allow(described_class).to receive(:warn).with(
/`RuboCop::Cop::EnforceSuperclass` is deprecated and will be removed/
)
RuboCop::Cop::RSpec::ApplicationRecord.include(described_class)
end
shared_examples 'no offense' do |code|
it "registers no offenses for `#{code}`" do
expect_no_offenses(code)
end
end
it 'registers an offense for models that subclass ActiveRecord::Base' do
expect_offense(<<~RUBY)
class MyModel < ActiveRecord::Base
^^^^^^^^^^^^^^^^^^ #{msg}
end
RUBY
end
it 'registers an offense for single-line definitions' do
expect_offense(<<~RUBY)
class MyModel < ActiveRecord::Base; end
^^^^^^^^^^^^^^^^^^ #{msg}
RUBY
end
it 'registers an offense for Class.new definition' do
expect_offense(<<~RUBY)
MyModel = Class.new(ActiveRecord::Base) {}
^^^^^^^^^^^^^^^^^^ #{msg}
RUBY
expect_offense(<<~RUBY)
MyModel = Class.new(ActiveRecord::Base)
^^^^^^^^^^^^^^^^^^ #{msg}
RUBY
end
it 'registers an offense for model defined using top-level' do
expect_offense(<<~RUBY)
class ::MyModel < ActiveRecord::Base
^^^^^^^^^^^^^^^^^^ #{msg}
end
RUBY
end
it 'registers an offense for models that subclass ::ActiveRecord::Base' do
expect_offense(<<~RUBY)
class MyModel < ::ActiveRecord::Base
^^^^^^^^^^^^^^^^^^^^ #{msg}
end
RUBY
end
it 'registers an offense for top-level constant ::Class.new definition' do
expect_offense(<<~RUBY)
::MyModel = ::Class.new(::ActiveRecord::Base) {}
^^^^^^^^^^^^^^^^^^^^ #{msg}
RUBY
expect_offense(<<~RUBY)
::MyModel = ::Class.new(::ActiveRecord::Base)
^^^^^^^^^^^^^^^^^^^^ #{msg}
RUBY
end
context 'when ApplicationRecord subclasses ActiveRecord::Base' do
it_behaves_like 'no offense', 'class ApplicationRecord < ActiveRecord::Base; end'
it_behaves_like 'no offense', 'class ::ApplicationRecord < ActiveRecord::Base; end'
it_behaves_like 'no offense', <<~RUBY
ApplicationRecord = Class.new(ActiveRecord::Base) do; end
RUBY
it_behaves_like 'no offense', <<~RUBY
ApplicationRecord = Class.new(::ActiveRecord::Base) do; end
RUBY
it_behaves_like 'no offense', <<~RUBY
ApplicationRecord = Class.new(ActiveRecord::Base)
RUBY
it_behaves_like 'no offense', <<~RUBY
::ApplicationRecord = Class.new(ActiveRecord::Base) do; end
RUBY
it_behaves_like 'no offense', <<~RUBY
::ApplicationRecord = ::Class.new(::ActiveRecord::Base) do; end
RUBY
it_behaves_like 'no offense', <<~RUBY
::ApplicationRecord = ::Class.new(::ActiveRecord::Base)
RUBY
end
context 'when MyModel subclasses ApplicationRecord' do
it_behaves_like 'no offense', 'class MyModel < ApplicationRecord; end'
it_behaves_like 'no offense', 'class MyModel < ::ApplicationRecord; end'
it_behaves_like 'no offense', <<~RUBY
MyModel = Class.new(ApplicationRecord) do
end
MyModel = Class.new(ApplicationRecord)
RUBY
it_behaves_like 'no offense', <<~RUBY
MyModel = ::Class.new(::ApplicationRecord) do
end
MyModel = ::Class.new(::ApplicationRecord)
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/gemspec/ordered_dependencies_spec.rb | spec/rubocop/cop/gemspec/ordered_dependencies_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::OrderedDependencies, :config do
let(:cop_config) { { 'TreatCommentsAsGroupSeparators' => treat_comments_as_group_separators } }
let(:treat_comments_as_group_separators) { false }
shared_examples 'ordered dependency' do |add_dependency|
context "when #{add_dependency}" do
context 'When gems are alphabetically sorted' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.#{add_dependency} 'rspec'
spec.#{add_dependency} 'rubocop'
end
RUBY
end
end
context 'when gems are not alphabetically sorted' do
it 'registers an offense' do
expect_offense(<<~RUBY, add_dependency: add_dependency)
Gem::Specification.new do |spec|
spec.%{add_dependency} 'rubocop'
spec.%{add_dependency} 'rspec'
^^^^^^{add_dependency}^^^^^^^^ Dependencies should be sorted in an alphabetical order within their section of the gemspec. Dependency `rspec` should appear before `rubocop`.
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.#{add_dependency} 'rspec'
spec.#{add_dependency} 'rubocop'
end
RUBY
end
end
context 'when each individual group of line is sorted' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.#{add_dependency} 'rspec'
spec.#{add_dependency} 'rubocop'
spec.#{add_dependency} 'hello'
spec.#{add_dependency} 'world'
end
RUBY
end
end
context 'when dependency is separated by multiline comment' do
context 'with TreatCommentsAsGroupSeparators: true' do
let(:treat_comments_as_group_separators) { true }
it 'accepts' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
# For code quality
spec.#{add_dependency} 'rubocop'
# For
# test
spec.#{add_dependency} 'rspec'
end
RUBY
end
end
context 'with TreatCommentsAsGroupSeparators: false' do
it 'registers an offense' do
expect_offense(<<~RUBY, add_dependency: add_dependency)
Gem::Specification.new do |spec|
# For code quality
spec.%{add_dependency} 'rubocop'
# For
# test
spec.%{add_dependency} 'rspec'
^^^^^^{add_dependency}^^^^^^^^ Dependencies should be sorted in an alphabetical order within their section of the gemspec. Dependency `rspec` should appear before `rubocop`.
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
# For
# test
spec.#{add_dependency} 'rspec'
# For code quality
spec.#{add_dependency} 'rubocop'
end
RUBY
end
end
end
end
end
it_behaves_like 'ordered dependency', 'add_dependency'
it_behaves_like 'ordered dependency', 'add_runtime_dependency'
it_behaves_like 'ordered dependency', 'add_development_dependency'
context 'when different dependencies are consecutive' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop'
spec.add_runtime_dependency 'rspec'
end
RUBY
end
end
context 'When using method call to gem names' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop'.freeze
spec.add_runtime_dependency 'rspec'.freeze
end
RUBY
end
end
context 'When using a local variable in an argument of dependent gem' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
%w(rubocop-performance rubocop-rails).each { |dep| spec.add_dependency dep }
spec.add_dependency 'parser'
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/gemspec/deprecated_attribute_assignment_spec.rb | spec/rubocop/cop/gemspec/deprecated_attribute_assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::DeprecatedAttributeAssignment, :config do
shared_examples 'deprecated attributes' do |attribute, value|
it 'registers and corrects an offense when using `s.rubygems_version =`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |s|
s.name = 'your_cool_gem_name'
s.#{attribute} = #{value}
^^^^^#{'^' * (attribute.size + value.size)} Do not set `#{attribute}` in gemspec.
s.bindir = 'exe'
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |s|
s.name = 'your_cool_gem_name'
s.bindir = 'exe'
end
RUBY
end
it 'registers and corrects an offense when using `spec.rubygems_version =`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.name = 'your_cool_gem_name'
spec.#{attribute} = #{value}
^^^^^^^^#{'^' * (attribute.size + value.size)} Do not set `#{attribute}` in gemspec.
spec.bindir = 'exe'
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.name = 'your_cool_gem_name'
spec.bindir = 'exe'
end
RUBY
end
it 'does not register an offense when using `s.rubygems_version =` outside `Gem::Specification.new`' do
expect_no_offenses(<<~RUBY)
s.#{attribute} = #{value}
RUBY
end
it 'does not register an offense when using `rubygems_version =` and receiver is not `Gem::Specification.new` block variable' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
s.#{attribute} = #{value}
end
RUBY
end
end
shared_examples 'deprecated attributes with addition' do |attribute, value|
it 'registers and corrects an offense when using `s.rubygems_version +=`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |s|
s.name = 'your_cool_gem_name'
s.#{attribute} += #{value}
^^^^^^#{'^' * (attribute.size + value.size)} Do not set `#{attribute}` in gemspec.
s.bindir = 'exe'
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |s|
s.name = 'your_cool_gem_name'
s.bindir = 'exe'
end
RUBY
end
it 'registers and corrects an offense when using `spec.rubygems_version +=`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.name = 'your_cool_gem_name'
spec.#{attribute} += #{value}
^^^^^^^^^#{'^' * (attribute.size + value.size)} Do not set `#{attribute}` in gemspec.
spec.bindir = 'exe'
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.name = 'your_cool_gem_name'
spec.bindir = 'exe'
end
RUBY
end
end
it_behaves_like 'deprecated attributes', 'date', "Time.now.strftime('%Y-%m-%d')"
it_behaves_like 'deprecated attributes', 'rubygems_version', '2.5'
it_behaves_like 'deprecated attributes', 'specification_version', '2.5'
it_behaves_like 'deprecated attributes', 'test_files', "Dir.glob('test/**/*')"
it_behaves_like 'deprecated attributes with addition', 'test_files', "Dir.glob('test/**/*')"
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/gemspec/add_runtime_dependency_spec.rb | spec/rubocop/cop/gemspec/add_runtime_dependency_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::AddRuntimeDependency, :config do
it 'registers an offense when using `add_runtime_dependency`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop')
^^^^^^^^^^^^^^^^^^^^^^ Use `add_dependency` instead of `add_runtime_dependency`.
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop')
end
RUBY
end
it 'does not register an offense when using `add_dependency`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop')
end
RUBY
end
it 'does not register an offense when using `add_development_dependency`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop')
end
RUBY
end
it 'does not register an offense when using `add_runtime_dependency` without receiver' do
expect_no_offenses(<<~RUBY)
add_runtime_dependency('rubocop')
RUBY
end
it 'does not register an offense when using `add_runtime_dependency` without arguments' do
expect_no_offenses(<<~RUBY)
spec.add_runtime_dependency
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/gemspec/duplicated_assignment_spec.rb | spec/rubocop/cop/gemspec/duplicated_assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::DuplicatedAssignment, :config do
it 'registers an offense when using `name=` twice' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.name = 'rubocop'
spec.name = 'rubocop2'
^^^^^^^^^^^^^^^^^^^^^^ `name=` method calls already given on line 2 of the gemspec.
end
RUBY
end
it 'registers an offense when using `name=` twice and using `_1` as a specification variable' do
expect_offense(<<~RUBY)
Gem::Specification.new do
_1.name = 'rubocop'
_1.name = 'rubocop2'
^^^^^^^^^^^^^^^^^^^^ `name=` method calls already given on line 2 of the gemspec.
end
RUBY
end
it 'registers an offense when using `name=` twice and using `it` as a specification variable', :ruby34 do
expect_offense(<<~RUBY)
Gem::Specification.new do
it.name = 'rubocop'
it.name = 'rubocop2'
^^^^^^^^^^^^^^^^^^^^ `name=` method calls already given on line 2 of the gemspec.
end
RUBY
end
it 'registers an offense when using `version=` twice' do
expect_offense(<<~RUBY)
require 'rubocop/version'
Gem::Specification.new do |spec|
spec.version = RuboCop::Version::STRING
spec.version = RuboCop::Version::STRING
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `version=` method calls already given on line 4 of the gemspec.
end
RUBY
end
it 'registers an offense when using `name=` twice with `cbase`' do
expect_offense(<<~RUBY)
::Gem::Specification.new do |spec|
spec.name = 'rubocop'
spec.name = 'rubocop2'
^^^^^^^^^^^^^^^^^^^^^^ `name=` method calls already given on line 2 of the gemspec.
end
RUBY
end
it 'registers an offense when using `required_ruby_version=` twice' do
expect_offense(<<~RUBY)
::Gem::Specification.new do |spec|
spec.required_ruby_version = '2.5'
spec.required_ruby_version = '2.6'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `required_ruby_version=` method calls already given on line 2 of the gemspec.
end
RUBY
end
it 'registers an offense when using `metadata#[]=` with same key twice' do
expect_offense(<<~RUBY)
::Gem::Specification.new do |spec|
spec.metadata['key'] = 1
spec.metadata[:key] = 2
spec.metadata['key'] = 2
^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['key']=` method calls already given on line 2 of the gemspec.
spec.metadata['key'] = 3
^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['key']=` method calls already given on line 2 of the gemspec.
end
RUBY
end
it 'does not register an offense when using `<<` twice' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.requirements << 'libmagick, v6.0'
spec.requirements << 'A good graphics card'
end
RUBY
end
it 'does not register an offense when using `spec.add_dependency` twice' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('parallel', '~> 1.10')
spec.add_runtime_dependency('parser', '>= 2.3.3.1', '< 3.0')
end
RUBY
end
it 'does not register an offense when `name=` method call is not block value' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
foo = Foo.new
foo.name = :foo
foo.name = :bar
end
RUBY
end
it 'does not register an offense when using `#[]=` with different keys' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata['foo'] = 1
spec.metadata['bar'] = 2
end
RUBY
end
it 'does not register an offense when using `#[]=` with same keys and different receivers' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.misc['foo'] = 1
spec.metadata['foo'] = 2
end
RUBY
end
it 'does not register an offense when using both `metadata#[]=` and `metadata=`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata = { 'foo' => 1 }
spec.metadata['foo'] = 1
end
RUBY
end
it 'does not register an offense when using indexed array assignment' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.authors = []
spec.authors[0] = "author-1"
spec.authors[1] = "author-2"
spec.authors << "author-3"
spec.authors << "author-4"
end
RUBY
end
it 'does not register an offense when using `metadata#[]=` with same key twice which are not literals' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata[foo()] = 1
spec.metadata[foo()] = 2
end
RUBY
end
context 'with non-standard `[]=` method arity' do
it 'does not register an offense with single argument' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata.[]=(1)
spec.metadata.[]=(2)
end
RUBY
end
it 'does not register an offense with more than two arguments' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata[1, 2] = 3
spec.metadata[1, 2] = 3
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/gemspec/ruby_version_globals_usage_spec.rb | spec/rubocop/cop/gemspec/ruby_version_globals_usage_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::RubyVersionGlobalsUsage, :config do
it 'registers an offense when using `RUBY_VERSION`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
RUBY_VERSION
^^^^^^^^^^^^ Do not use `RUBY_VERSION` in gemspec file.
end
RUBY
end
it 'registers an offense when using `::RUBY_VERSION`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
::RUBY_VERSION
^^^^^^^^^^^^^^ Do not use `::RUBY_VERSION` in gemspec file.
end
RUBY
end
it 'registers an offense when using `Ruby::VERSION`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
Ruby::VERSION
^^^^^^^^^^^^^ Do not use `Ruby::VERSION` in gemspec file.
end
RUBY
end
it 'registers an offense when using `::Ruby::VERSION`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
::Ruby::VERSION
^^^^^^^^^^^^^^^ Do not use `::Ruby::VERSION` in gemspec file.
end
RUBY
end
it 'does not register an offense when no `RUBY_VERSION`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
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/gemspec/require_mfa_spec.rb | spec/rubocop/cop/gemspec/require_mfa_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::RequireMFA, :config do
context 'when the gemspec is blank' do
it 'does not register an offense' do
expect_no_offenses('', 'my.gemspec')
end
end
context 'when the specification is blank' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata['rubygems_mfa_required'] = 'true'
end
RUBY
end
end
context 'when the specification has a metadata hash but no rubygems_mfa_required key' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
spec.metadata = {
}
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata = {
'rubygems_mfa_required' => 'true'}
end
RUBY
end
end
context 'when the specification has a non-hash metadata' do
it 'registers an offense but does not correct' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
spec.metadata = Metadata.new
end
RUBY
end
end
context 'when there are other metadata keys' do
context 'and `rubygems_mfa_required` is included' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
spec.metadata = {
'foo' => 'bar',
'rubygems_mfa_required' => 'true',
'baz' => 'quux'
}
end
RUBY
end
end
context 'and `rubygems_mfa_required` is not included' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
spec.metadata = {
'foo' => 'bar',
'baz' => 'quux'
}
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata = {
'foo' => 'bar',
'baz' => 'quux',
'rubygems_mfa_required' => 'true'
}
end
RUBY
end
end
end
context 'when metadata is set by key assignment' do
context 'and `rubygems_mfa_required` is included' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
spec.metadata['foo'] = 'bar'
spec.metadata['rubygems_mfa_required'] = 'true'
end
RUBY
end
end
context 'and `rubygems_mfa_required` is not included' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
spec.metadata['foo'] = 'bar'
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata['foo'] = 'bar'
spec.metadata['rubygems_mfa_required'] = 'true'
end
RUBY
end
context 'when `metadata` assignment is not the last one' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
spec.metadata['foo'] = 'bar'
spec.author = 'viralpraxis'
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata['foo'] = 'bar'
spec.metadata['rubygems_mfa_required'] = 'true'
spec.author = 'viralpraxis'
end
RUBY
end
end
end
end
context 'with rubygems_mfa_required: true' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
spec.metadata = {
'rubygems_mfa_required' => 'true'
}
end
RUBY
end
end
context 'with rubygems_mfa_required: false' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
spec.metadata = {
'rubygems_mfa_required' => 'false'
^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
}
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata = {
'rubygems_mfa_required' => 'true'
}
end
RUBY
end
end
context 'with rubygems_mfa_required: false by key access' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, 'my.gemspec')
Gem::Specification.new do |spec|
spec.metadata['rubygems_mfa_required'] = 'false'
^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
end
RUBY
expect_correction(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata['rubygems_mfa_required'] = 'true'
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/gemspec/dependency_version_spec.rb | spec/rubocop/cop/gemspec/dependency_version_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::DependencyVersion, :config do
let(:cop_config) do
{
'Enabled' => true,
'EnforcedStyle' => enforced_style,
'AllowedGems' => allowed_gems
}
end
let(:allowed_gems) { [] }
let(:config) do
base = RuboCop::ConfigLoader
.default_configuration['Gemspec/DependencyVersion']
.merge(cop_config)
RuboCop::Config.new('Gemspec/DependencyVersion' => base)
end
context 'with `EnforcedStyle: required`' do
let(:enforced_style) { 'required' }
context 'using add_dependency' do
it 'registers an offense when adding dependency without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'parser'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding dependency by parenthesized call without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('parser')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding dependency without version specification and method called on gem name argument' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('parser'.freeze)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding dependency using git option without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding dependency using git option by parenthesized call without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'does not register an offense when adding dependency with version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'parser', '~> 3.1', '>= 3.1.1.0'
end
RUBY
end
it 'does not register an offense when adding dependency by parenthesized call with version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('parser', '>= 3.1.1.0')
end
RUBY
end
it 'does not register an offense when adding dependency with commit ref specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228'
end
RUBY
end
it 'does not register an offense when adding dependency by parenthesized call with commit ref specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228')
end
RUBY
end
it 'does not register an offense when adding dependency with tag specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0'
end
RUBY
end
it 'does not register an offense when adding dependency by parenthesized call with tag specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0')
end
RUBY
end
it 'does not register an offense when adding dependency with branch specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main'
end
RUBY
end
it 'does not register an offense when adding dependency by parenthesized call with branch specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main')
end
RUBY
end
end
context 'using add_development_dependency' do
it 'registers an offense when adding development dependency without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'parser'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding development dependency by parenthesized call without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('parser')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding development dependency using git option without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding development dependency using git option by parenthesized call without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'does not register an offense when adding development dependency with version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'parser', '~> 3.1', '>= 3.1.1.0'
end
RUBY
end
it 'does not register an offense when adding development dependency by parenthesized call with version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('parser', '>= 3.1.1.0')
end
RUBY
end
it 'does not register an offense when adding development dependency with commit ref specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228'
end
RUBY
end
it 'does not register an offense when adding development dependency by parenthesized call with commit ref specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228')
end
RUBY
end
it 'does not register an offense when adding development dependency with tag specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0'
end
RUBY
end
it 'does not register an offense when adding development dependency by parenthesized call with tag specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0')
end
RUBY
end
it 'does not register an offense when adding development dependency with branch specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main'
end
RUBY
end
it 'does not register an offense when adding development dependency by parenthesized call with branch specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main')
end
RUBY
end
end
context 'using add_runtime_dependency' do
it 'registers an offense when adding runtime dependency without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'parser'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding runtime dependency by parenthesized call without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('parser')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding runtime dependency using git option without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding runtime dependency using git option by parenthesized call without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'does not register an offense when adding runtime dependency with version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'parser', '~> 3.1', '>= 3.1.1.0'
end
RUBY
end
it 'does not register an offense when adding runtime dependency by parenthesized call with version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('parser', '>= 3.1.1.0')
end
RUBY
end
it 'does not register an offense when adding runtime dependency with commit ref specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228'
end
RUBY
end
it 'does not register an offense when adding runtime dependency by parenthesized call with commit ref specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228')
end
RUBY
end
it 'does not register an offense when adding runtime dependency with tag specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0'
end
RUBY
end
it 'does not register an offense when adding runtime dependency by parenthesized call with tag specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0')
end
RUBY
end
it 'does not register an offense when adding runtime dependency with branch specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main'
end
RUBY
end
it 'does not register an offense when adding runtime dependency by parenthesized call with branch specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main')
end
RUBY
end
end
context 'with `AllowedGems`' do
let(:allowed_gems) { ['rubocop'] }
it 'registers an offense when adding dependency without version specification excepts allowed gems' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop'
spec.add_development_dependency 'rubocop-ast', '~> 0.1'
spec.add_dependency 'parser'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
it 'registers an offense when adding dependency by parenthesized call without version specification excepts allowed gems' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop')
spec.add_development_dependency('rubocop-ast', '~> 0.1')
spec.add_dependency('parser')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is required.
end
RUBY
end
end
end
context 'with `EnforcedStyle: forbidden`' do
let(:enforced_style) { 'forbidden' }
context 'using add_dependency' do
it 'does not register an offense when adding dependency without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'parser'
end
RUBY
end
it 'does not register an offense when adding dependency by parenthesized call without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('parser')
end
RUBY
end
it 'does not register an offense when adding dependency using git option without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop'
end
RUBY
end
it 'does not register an offense when adding dependency using git option by parenthesized call without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop')
end
RUBY
end
it 'registers an offense when adding dependency with version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'parser', '~> 3.1', '>= 3.1.1.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency by parenthesized call with version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('parser', '>= 3.1.1.0')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency with commit ref specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency by parenthesized call with commit ref specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency with tag specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency by parenthesized call with tag specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency with branch specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency by parenthesized call with branch specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
end
context 'using add_development_dependency' do
it 'does not register an offense when adding development dependency without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'parser'
end
RUBY
end
it 'does not register an offense when adding development dependency by parenthesized call without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('parser')
end
RUBY
end
it 'does not register an offense when adding development dependency using git option without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop'
end
RUBY
end
it 'does not register an offense when adding development dependency using git option by parenthesized call without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop')
end
RUBY
end
it 'registers an offense when adding development dependency with version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'parser', '~> 3.1', '>= 3.1.1.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding development dependency by parenthesized call with version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('parser', '>= 3.1.1.0')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding development dependency with commit ref specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding development dependency by parenthesized call with commit ref specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding development dependency with tag specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding development dependency by parenthesized call with tag specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding development dependency with branch specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding development dependency by parenthesized call with branch specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_development_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
end
context 'using add_runtime_dependency' do
it 'does not register an offense when adding runtime dependency without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'parser'
end
RUBY
end
it 'does not register an offense when adding runtime dependency by parenthesized call without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('parser')
end
RUBY
end
it 'does not register an offense when adding runtime dependency using git option without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop'
end
RUBY
end
it 'does not register an offense when adding runtime dependency using git option by parenthesized call without version specification' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop')
end
RUBY
end
it 'registers an offense when adding runtime dependency with version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'parser', '~> 3.1', '>= 3.1.1.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding runtime dependency by parenthesized call with version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('parser', '>= 3.1.1.0')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding runtime dependency with commit ref specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding runtime dependency by parenthesized call with commit ref specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', ref: '54f4c8228')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding runtime dependency with tag specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding runtime dependency by parenthesized call with tag specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', tag: 'v1.28.0')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding runtime dependency with branch specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency 'rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding runtime dependency by parenthesized call with branch specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_runtime_dependency('rubocop', git: 'https://github.com/rubocop/rubocop', branch: 'main')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
end
context 'with `AllowedGems`' do
let(:allowed_gems) { ['rubocop'] }
it 'registers an offense when adding dependency without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency 'parser'
spec.add_dependency 'rubocop', '~> 1.28'
spec.add_development_dependency 'rubocop-ast', '~> 0.1'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
end
RUBY
end
it 'registers an offense when adding dependency by parenthesized call without version specification' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.add_dependency('rubocop')
spec.add_dependency('parser')
spec.add_development_dependency('rubocop-ast', '~> 0.1')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dependency version specification is forbidden.
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/gemspec/development_dependencies_spec.rb | spec/rubocop/cop/gemspec/development_dependencies_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::DevelopmentDependencies, :config do
let(:cop_config) do
{
'Enabled' => true,
'EnforcedStyle' => enforced_style,
'AllowedGems' => [
'allowed'
]
}
end
shared_examples 'prefer gem file' do
it 'registers an offense when using `#add_development_dependency` in a gemspec' do
expect_offense(<<~RUBY, 'example.gemspec', preferred_file: enforced_style)
Gem::Specification.new do |spec|
spec.name = 'example'
spec.add_development_dependency 'foo'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Specify development dependencies in %{preferred_file}.
spec.add_development_dependency 'allowed'
end
RUBY
end
it 'registers an offense when using `#add_development_dependency` in a gemspec a single version argument' do
expect_offense(<<~RUBY, 'example.gemspec', preferred_file: enforced_style)
Gem::Specification.new do |spec|
spec.name = 'example'
spec.add_development_dependency 'foo', '>= 1.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Specify development dependencies in %{preferred_file}.
spec.add_development_dependency 'allowed', '>= 1.0'
end
RUBY
end
it 'registers an offense when using `#add_development_dependency` in a gemspec with two version' do
expect_offense(<<~RUBY, 'example.gemspec', preferred_file: enforced_style)
Gem::Specification.new do |spec|
spec.name = 'example'
spec.add_development_dependency 'foo', '>= 1.0', '< 2.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Specify development dependencies in %{preferred_file}.
spec.add_development_dependency 'allowed', '>= 1.0', '< 2.0'
end
RUBY
end
it 'registers no offenses when specifying dependencies in Gemfile' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'example'
RUBY
end
it 'registers no offenses when specifying dependencies in gems.rb' do
expect_no_offenses(<<~RUBY, 'gems.rb')
gem 'example'
RUBY
end
end
context 'with `EnforcedStyle: Gemfile`' do
let(:enforced_style) { 'Gemfile' }
it_behaves_like 'prefer gem file'
end
context 'with `EnforcedStyle: gems.rb`' do
let(:enforced_style) { 'gems.rb' }
it_behaves_like 'prefer gem file'
end
context 'with `EnforcedStyle: gemspec`' do
let(:enforced_style) { 'gemspec' }
it 'registers no offenses when using `#add_development_dependency`' do
expect_no_offenses(<<~RUBY, 'example.gemspec')
Gem::Specification.new do |spec|
spec.name = 'example'
spec.add_development_dependency 'foo'
end
RUBY
end
it 'registers an offense when specifying dependencies in Gemfile' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'example'
^^^^^^^^^^^^^ Specify development dependencies in gemspec.
gem 'allowed'
RUBY
end
it 'registers an offense when specifying dependencies in gems.rb' do
expect_offense(<<~RUBY, 'gems.rb')
gem 'example'
^^^^^^^^^^^^^ Specify development dependencies in gemspec.
gem 'allowed'
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/gemspec/attribute_assignment_spec.rb | spec/rubocop/cop/gemspec/attribute_assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::AttributeAssignment, :config do
it 'does not register an offense when only indexed hash assignment is used' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata['key-0'] = 'value-0'
spec.metadata['key-1'] = 'value-1'
end
RUBY
end
it 'does not register an offense when only normal hash assignment is used' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata = { 'key' => 'value' }
spec.metadata = { 'key' => 'value' }
end
RUBY
end
it 'does not register an offense when only indexed array assignment is used' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.authors[0] = 'author-0'
spec.authors[1] = 'author-1'
end
RUBY
end
it 'does not register an offense when only normal array assignment is used' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.authors = %w[author-1 author-2]
spec.authors = %w[author-1 author-2]
end
RUBY
end
it 'registers an offense for inconsistent hash assignment' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.metadata = { 'key-0' => 'value-0' }
spec.metadata['key-1'] = 'value-1'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use consistent style for Gemspec attributes assignment.
spec.metadata['key-2'] = 'value-2'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use consistent style for Gemspec attributes assignment.
end
RUBY
end
it 'registers an offense for inconsistent array assignment' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.authors = %w[author-0 author-1]
spec.authors[2] = 'author-2'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use consistent style for Gemspec attributes assignment.
end
RUBY
end
context 'when the gemspec is blank' do
it 'does not register an offense' do
expect_no_offenses('', 'my.gemspec')
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/gemspec/required_ruby_version_spec.rb | spec/rubocop/cop/gemspec/required_ruby_version_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Gemspec::RequiredRubyVersion, :config do
# rubocop:disable RSpec/RepeatedExampleGroupDescription
context 'target ruby version > 3.4', :ruby34 do
# rubocop:enable RSpec/RepeatedExampleGroupDescription
it 'registers an offense when `required_ruby_version` is specified with >= and is lower than `TargetRubyVersion`' do
expect_offense(<<~RUBY, '/path/to/foo.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 3.3.0'
^^^^^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is specified with ~> and is lower than `TargetRubyVersion`' do
expect_offense(<<~RUBY, '/path/to/foo.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = '~> 3.3.0'
^^^^^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is specified in array and is lower than `TargetRubyVersion`' do
expect_offense(<<~RUBY, '/path/to/foo.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = ['>= 3.3.0', '< 4.0.0']
^^^^^^^^^^^^^^^^^^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'recognizes Gem::Requirement and registers an offense' do
expect_offense(<<~RUBY, '/path/to/foo.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = Gem::Requirement.new(">= 3.3.0")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is specified with `Gem::Requirement.new` and is higher than `TargetRubyVersion`' do
expect_offense(<<~RUBY)
Gem::Specification.new do |spec|
spec.required_ruby_version = Gem::Requirement.new('< 3.4')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'recognizes a Gem::Requirement with multiple requirements and does not register an offense' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.required_ruby_version = Gem::Requirement.new(">= 3.4.0", "<= 3.8")
end
RUBY
end
describe 'false negatives' do
it 'does not register an offense when `required_ruby_version` ' \
'is assigned as a variable (string literal)' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
version = '>= 3.3.0'
spec.required_ruby_version = version
end
RUBY
end
it 'does not register an offense when `required_ruby_version` ' \
'is assigned as a variable (an array of string literal)' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
lowest_version = '>= 3.3.0'
highest_version = '< 3.8.0'
spec.required_ruby_version = [lowest_version, highest_version]
end
RUBY
end
end
end
context 'target ruby version > 3.3', :ruby33 do
it 'registers an offense when `required_ruby_version` is specified with >= and is higher than `TargetRubyVersion`' do
expect_offense(<<~RUBY, '/path/to/bar.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 3.4.0'
^^^^^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.3, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is specified with ~> and is higher than `TargetRubyVersion`' do
expect_offense(<<~RUBY, '/path/to/bar.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = '~> 3.4.0'
^^^^^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.3, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
end
# rubocop:disable RSpec/RepeatedExampleGroupDescription
context 'target ruby version > 3.4', :ruby34 do
# rubocop:enable RSpec/RepeatedExampleGroupDescription
it 'does not register an offense when `required_ruby_version` is specified with >= and equals `TargetRubyVersion`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 3.4.0'
end
RUBY
end
it 'does not register an offense when `required_ruby_version` is specified with ~> and equals `TargetRubyVersion`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.required_ruby_version = '~> 3.4.0'
end
RUBY
end
it 'does not register an offense when `required_ruby_version` is specified with >= without a patch version and ' \
'equals `TargetRubyVersion`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 3.4'
end
RUBY
end
it 'does not register an offense when `required_ruby_version` is specified with ~> without a patch version and ' \
'equals `TargetRubyVersion`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.required_ruby_version = '~> 3.4'
end
RUBY
end
it 'does not register an offense when lowest version of ' \
'`required_ruby_version` equals `TargetRubyVersion`' do
expect_no_offenses(<<~RUBY)
Gem::Specification.new do |spec|
spec.required_ruby_version = ['>= 3.4.0', '< 4.1.0']
end
RUBY
end
it 'registers an offense when `required_ruby_version` is specified with >= without a minor version and is lower ' \
'than `TargetRubyVersion`' do
expect_offense(<<~RUBY, 'bar.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 3'
^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is specified with ~> without a minor version and is lower ' \
'than `TargetRubyVersion`' do
expect_offense(<<~RUBY, 'bar.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = '~> 3'
^^^^^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is not specified' do
expect_offense(<<~RUBY, '/path/to/foo.gemspec')
Gem::Specification.new do |spec|
^{} `required_ruby_version` should be specified.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is blank' do
expect_offense(<<~RUBY, 'bar.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = ''
^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
it 'registers an offense when `required_ruby_version` is an empty array' do
expect_offense(<<~RUBY, 'bar.gemspec')
Gem::Specification.new do |spec|
spec.required_ruby_version = []
^^ `required_ruby_version` and `TargetRubyVersion` (3.4, which may be specified in .rubocop.yml) should be equal.
end
RUBY
end
end
it 'registers an offense when the file is empty' do
expect_offense(<<~RUBY, 'bar.gemspec')
^{} `required_ruby_version` should be specified.
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/migration/department_name_spec.rb | spec/rubocop/cop/migration/department_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Migration::DepartmentName, :config do
context 'when todo/enable comments have cop names without departments' do
let(:tip) { 'Run `rubocop -a --only Migration/DepartmentName` to fix.' }
let(:warning) do
<<~OUTPUT
file.rb: Warning: no department given for Alias. #{tip}
file.rb: Warning: no department given for LineLength. #{tip}
file.rb: Warning: no department given for Alias. #{tip}
file.rb: Warning: no department given for LineLength. #{tip}
OUTPUT
end
it 'registers offenses and corrects' do
expect do
expect_offense(<<~RUBY, 'file.rb')
# rubocop:todo Alias, LineLength
^^^^^^^^^^ Department name is missing.
^^^^^ Department name is missing.
alias :ala :bala
# rubocop:enable Alias, LineLength
^^^^^^^^^^ Department name is missing.
^^^^^ Department name is missing.
RUBY
end.to output(warning).to_stderr
expect_correction(<<~RUBY)
# rubocop:todo Style/Alias, Layout/LineLength
alias :ala :bala
# rubocop:enable Style/Alias, Layout/LineLength
RUBY
end
it 'registers offenses and corrects when there is space around `:`' do
expect do
expect_offense(<<~RUBY, 'file.rb')
# rubocop : todo Alias, LineLength
^^^^^^^^^^ Department name is missing.
^^^^^ Department name is missing.
alias :ala :bala
# rubocop : enable Alias, LineLength
^^^^^^^^^^ Department name is missing.
^^^^^ Department name is missing.
RUBY
end.to output(warning).to_stderr
expect_correction(<<~RUBY)
# rubocop : todo Style/Alias, Layout/LineLength
alias :ala :bala
# rubocop : enable Style/Alias, Layout/LineLength
RUBY
end
it 'registers offenses and corrects when using a legacy cop name' do
expect_offense(<<~RUBY, 'file.rb')
# rubocop:disable SingleSpaceBeforeFirstArg, Layout/LineLength
^^^^^^^^^^^^^^^^^^^^^^^^^ Department name is missing.
name "apache_kafka"
RUBY
# `Style/SingleSpaceBeforeFirstArg` is a legacy name that has been
# renamed to `Layout/SpaceBeforeFirstArg`. In the autocorrection,
# the department name is complemented by the legacy cop name.
# Migration to the new name is expected to be modified using Gry gem.
expect_correction(<<~RUBY)
# rubocop:disable Style/SingleSpaceBeforeFirstArg, Layout/LineLength
name "apache_kafka"
RUBY
end
end
context 'when a disable comment has cop names with departments' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
alias :ala :bala # rubocop:disable all
# rubocop:disable Style/Alias
RUBY
end
end
context 'when a disable comment contains a plain comment' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
# rubocop:disable Style/Alias # Plain code comment
alias :ala :bala
RUBY
end
end
context 'when a disable comment contains an unexpected character for department name' do
it 'accepts' do
expect_no_offenses(<<~RUBY)
# rubocop:disable Style/Alias -- because something, something, and something
alias :ala :bala
RUBY
end
end
# `Migration/DepartmentName` cop's role is to complement a department name.
# The role would be simple if another feature could detect unexpected
# disable comment format.
context 'when an unexpected disable comment format' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
# rubocop:disable Style:Alias
alias :ala :bala
RUBY
end
end
context 'when only department name has given' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
# rubocop:disable Style
alias :ala :bala
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/security/eval_spec.rb | spec/rubocop/cop/security/eval_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Security::Eval, :config do
it 'registers an offense for eval as function' do
expect_offense(<<~RUBY)
eval(something)
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'registers an offense for eval as command' do
expect_offense(<<~RUBY)
eval something
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'registers an offense `Binding#eval`' do
expect_offense(<<~RUBY)
binding.eval something
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'registers an offense for `Kernel.eval`' do
expect_offense(<<~RUBY)
Kernel.eval something
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'registers an offense for `::Kernel.eval`' do
expect_offense(<<~RUBY)
::Kernel.eval something
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'registers an offense for eval with string that has an interpolation' do
expect_offense(<<~'RUBY')
eval "something#{foo}"
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'accepts eval as variable' do
expect_no_offenses('eval = something')
end
it 'accepts eval as method' do
expect_no_offenses('something.eval')
end
it 'accepts eval on a literal string' do
expect_no_offenses('eval("puts 1")')
end
it 'accepts eval with no arguments' do
expect_no_offenses('eval')
end
it 'accepts eval with a multiline string' do
expect_no_offenses('eval "something\nsomething2"')
end
it 'accepts eval with a string that interpolates a literal' do
expect_no_offenses('eval "something#{2}"')
end
context 'with an explicit binding, filename, and line number' do
it 'registers an offense for eval as function' do
expect_offense(<<~RUBY)
eval(something, binding, "test.rb", 1)
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'registers an offense for eval as command' do
expect_offense(<<~RUBY)
eval something, binding, "test.rb", 1
^^^^ The use of `eval` is a serious security risk.
RUBY
end
it 'accepts eval on a literal string' do
expect_no_offenses('eval("puts 1", binding, "test.rb", 1)')
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/security/io_methods_spec.rb | spec/rubocop/cop/security/io_methods_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Security::IoMethods, :config do
shared_examples 'offense' do |current, preferred, method_name|
it "registers and corrects an offense when using `#{method_name}`" do
expect_offense(<<~RUBY, current: current)
#{current}
^{current} `File.#{method_name}` is safer than `IO.#{method_name}`.
RUBY
expect_correction(<<~RUBY)
#{preferred}
RUBY
end
end
shared_examples 'accepts' do |code|
it "does not register an offense when using `#{code}`" do
expect_no_offenses(<<~RUBY)
#{code}
RUBY
end
end
context 'when using `IO` receiver and variable argument' do
it_behaves_like 'offense', 'IO.read(path)', 'File.read(path)', 'read'
it_behaves_like 'offense', 'IO.write(path, "hi")', 'File.write(path, "hi")', 'write'
it_behaves_like 'offense', 'IO.binread(path)', 'File.binread(path)', 'binread'
it_behaves_like 'offense', 'IO.binwrite(path, "hi")', 'File.binwrite(path, "hi")', 'binwrite'
it_behaves_like 'offense', 'IO.readlines(path)', 'File.readlines(path)', 'readlines'
it 'registers and corrects an offense when using `foreach`' do
expect_offense(<<~RUBY)
IO.foreach(path) { |x| puts x }
^^^^^^^^^^^^^^^^ `File.foreach` is safer than `IO.foreach`.
RUBY
expect_correction(<<~RUBY)
File.foreach(path) { |x| puts x }
RUBY
end
end
context 'when using `IO` receiver and string argument' do
it_behaves_like 'offense', 'IO.read("command")', 'File.read("command")', 'read'
it_behaves_like 'offense', 'IO.write("command", "hi")', 'File.write("command", "hi")', 'write'
it_behaves_like 'offense', 'IO.binwrite("command", "hi")', 'File.binwrite("command", "hi")', 'binwrite'
it_behaves_like 'offense', 'IO.binwrite(path, "hi")', 'File.binwrite(path, "hi")', 'binwrite'
it_behaves_like 'offense', 'IO.readlines("command")', 'File.readlines("command")', 'readlines'
it 'registers and corrects an offense when using `foreach`' do
expect_offense(<<~RUBY)
IO.foreach("command") { |x| puts x }
^^^^^^^^^^^^^^^^^^^^^ `File.foreach` is safer than `IO.foreach`.
RUBY
expect_correction(<<~RUBY)
File.foreach("command") { |x| puts x }
RUBY
end
end
context 'when using `File` receiver' do
it_behaves_like 'accepts', 'File.read(path)'
it_behaves_like 'accepts', 'File.binread(path)'
it_behaves_like 'accepts', 'File.binwrite(path, "hi")'
it_behaves_like 'accepts', 'File.readlines(path)'
it_behaves_like 'accepts', 'File.foreach(path) { |x| puts x }'
end
context 'when using no receiver' do
it_behaves_like 'accepts', 'read("command")'
it_behaves_like 'accepts', 'write("command", "hi")'
it_behaves_like 'accepts', 'binwrite("command", "hi")'
it_behaves_like 'accepts', 'readlines("command")'
it_behaves_like 'accepts', 'foreach("command") { |x| puts x }'
end
context 'when using `IO` receiver and string argument that starts with a pipe character (`"| command"`)' do
it_behaves_like 'accepts', 'IO.read("| command")'
it_behaves_like 'accepts', 'IO.write("| command", "hi")'
it_behaves_like 'accepts', 'IO.binwrite("| command", "hi")'
it_behaves_like 'accepts', 'IO.readlines("| command")'
it_behaves_like 'accepts', 'IO.foreach("| command") { |x| puts x }'
end
context 'when using `IO` receiver and string argument that starts with a pipe character (`" | command"`)' do
it_behaves_like 'accepts', 'IO.read(" | command")'
it_behaves_like 'accepts', 'IO.write(" | command", "hi")'
it_behaves_like 'accepts', 'IO.binwrite(" | command", "hi")'
it_behaves_like 'accepts', 'IO.readlines(" | command")'
it_behaves_like 'accepts', 'IO.foreach(" | command") { |x| puts x }'
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/security/marshal_load_spec.rb | spec/rubocop/cop/security/marshal_load_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Security::MarshalLoad, :config do
it 'registers an offense for using Marshal.load' do
expect_offense(<<~RUBY)
Marshal.load('{}')
^^^^ Avoid using `Marshal.load`.
::Marshal.load('{}')
^^^^ Avoid using `Marshal.load`.
RUBY
end
it 'registers an offense for using Marshal.restore' do
expect_offense(<<~RUBY)
Marshal.restore('{}')
^^^^^^^ Avoid using `Marshal.restore`.
::Marshal.restore('{}')
^^^^^^^ Avoid using `Marshal.restore`.
RUBY
end
it 'does not register an offense for Marshal.dump' do
expect_no_offenses(<<~RUBY)
Marshal.dump({})
::Marshal.dump({})
RUBY
end
it 'does not register an offense Marshal methods under another namespace' do
expect_no_offenses(<<~RUBY)
SomeNamespace::Marshal.load('')
SomeNamespace::Marshal.restore('')
SomeNamespace::Marshal.dump('')
::SomeNamespace::Marshal.load('')
::SomeNamespace::Marshal.restore('')
::SomeNamespace::Marshal.dump('')
RUBY
end
it 'allows using dangerous Marshal methods for deep cloning' do
expect_no_offenses(<<~RUBY)
Marshal.load(Marshal.dump({}))
Marshal.restore(Marshal.dump({}))
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/security/compound_hash_spec.rb | spec/rubocop/cop/security/compound_hash_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Security::CompoundHash, :config do
it 'registers an offense when using XOR operator in the implementation of the hash method' do
expect_offense(<<~RUBY)
def hash
1.hash ^ 2.hash ^ 3.hash
^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using XOR operator in the implementation of the hash method, even without sub-calls to hash' do
expect_offense(<<~RUBY)
def hash
1 ^ 2 ^ 3
^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using XOR operator in the implementation of the hash singleton method' do
expect_offense(<<~RUBY)
def object.hash
1.hash ^ 2.hash ^ 3.hash
^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using XOR operator in the implementation of a dynamic hash method' do
expect_offense(<<~RUBY)
define_method(:hash) do
1.hash ^ 2.hash ^ 3.hash
^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using XOR operator in the implementation of a dynamic hash singleton method' do
expect_offense(<<~RUBY)
define_singleton_method(:hash) do
1.hash ^ 2.hash ^ 3.hash
^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when delegating to Array#hash for a single value' do
expect_offense(<<~RUBY)
def hash
[1].hash
^^^^^^^^ Delegate hash directly without wrapping in an array when only using a single value.
end
RUBY
end
it 'registers an offense if .hash is called on any elements of a hashed array' do
expect_offense(<<~RUBY)
[1, 2.hash, 3].hash
^^^^^^ Calling .hash on elements of a hashed array is redundant.
RUBY
end
it 'registers an offense if .hash is called on any elements of a hashed array with safe navigation' do
expect_offense(<<~RUBY)
def hash
[foo&.hash, bar&.hash].hash
^^^^^^^^^ Calling .hash on elements of a hashed array is redundant.
^^^^^^^^^ Calling .hash on elements of a hashed array is redundant.
end
RUBY
end
it 'does not register an offense when delegating to Array#hash' do
expect_no_offenses(<<~RUBY)
def hash
[1, 2, 3].hash
end
RUBY
end
it 'does not register an offense when delegating to a single object' do
expect_no_offenses(<<~RUBY)
def hash
1.hash
end
RUBY
end
it 'registers an offense when using XOR operator in the implementation of the hash method, even if intermediate variable is used' do
expect_offense(<<~RUBY)
def hash
value = 1.hash ^ 2.hash ^ 3.hash
^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
value
end
RUBY
end
it 'registers an offense when using XOR assignment operator in the implementation of the hash method' do
expect_offense(<<~RUBY)
def hash
h = 0
things.each do |thing|
h ^= thing.hash
^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
h
end
RUBY
end
it 'registers an offense when using addition assignment operator in the implementation of the hash method' do
expect_offense(<<~RUBY)
def hash
h = 0
things.each do |thing|
h += thing.hash
^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
h
end
RUBY
end
it 'registers an offense when using multiplication assignment operator in the implementation of the hash method' do
expect_offense(<<~RUBY)
def hash
h = 0
things.each do |thing|
h *= thing.hash
^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
h
end
RUBY
end
it 'registers an offense when using addition in the implementation of the hash method' do
expect_offense(<<~RUBY)
def hash
foo.hash + bar.hash
^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using multiplication in the implementation of the hash method' do
expect_offense(<<~RUBY)
def hash
to_s.hash * -1
^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using XOR between an array hash and a class' do
expect_offense(<<~RUBY)
def hash
[red, blue, green, alpha].hash ^ self.class.hash
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using XOR involving super' do
expect_offense(<<~RUBY)
def hash
foo.hash ^ super ^ bar.hash
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using XOR and bitshifts' do
expect_offense(<<~RUBY)
def hash
foo.hash ^ bar.hash << 1 ^ biz.hash << 2 ^ bar.hash << 3
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense when using bitshift and OR' do
expect_offense(<<~RUBY)
def hash
([@addr, @mask_addr, @zone_id].hash << 1) | (ipv4? ? 0 : 1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
RUBY
end
it 'registers an offense for complex usage' do
expect_offense(<<~RUBY)
def hash
@hash ||= begin
hash_ = [@factory, geometry_type].hash
(0...num_geometries).inject(hash_) do |h_, i_|
(1664525 * h_ + geometry_n(i_).hash).hash
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `[...].hash` instead of combining hash values manually.
end
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/security/open_spec.rb | spec/rubocop/cop/security/open_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Security::Open, :config do
it 'registers an offense for open' do
expect_offense(<<~RUBY)
open(something)
^^^^ The use of `Kernel#open` is a serious security risk.
RUBY
end
it 'registers an offense for open with mode argument' do
expect_offense(<<~RUBY)
open(something, "r")
^^^^ The use of `Kernel#open` is a serious security risk.
RUBY
end
it 'registers an offense for open with dynamic string that is not prefixed' do
expect_offense(<<~'RUBY')
open("#{foo}.txt")
^^^^ The use of `Kernel#open` is a serious security risk.
RUBY
end
it 'registers an offense for open with string that starts with a pipe' do
expect_offense(<<~'RUBY')
open("| #{foo}")
^^^^ The use of `Kernel#open` is a serious security risk.
RUBY
end
it 'registers an offense for open with a literal string starting with a pipe' do
expect_offense(<<~RUBY)
open('| foo')
^^^^ The use of `Kernel#open` is a serious security risk.
RUBY
end
it 'registers an offense for open with a block' do
expect_offense(<<~'RUBY')
open("#{foo}.txt") do |f|
^^^^ The use of `Kernel#open` is a serious security risk.
f.gets
end
RUBY
end
it 'registers an offense for `URI.open` with string that starts with a pipe' do
expect_offense(<<~'RUBY')
URI.open("| #{foo}")
^^^^ The use of `URI.open` is a serious security risk.
RUBY
end
it 'registers an offense for `::URI.open` with string that starts with a pipe' do
expect_offense(<<~'RUBY')
::URI.open("| #{foo}")
^^^^ The use of `::URI.open` is a serious security risk.
RUBY
end
it 'registers an offense for `URI.open` with a block' do
expect_offense(<<~'RUBY')
::URI.open("| #{foo}") do |f|
^^^^ The use of `::URI.open` is a serious security risk.
f.gets
end
RUBY
end
it 'accepts open as variable' do
expect_no_offenses('open = something')
end
it 'accepts File.open as method' do
expect_no_offenses('File.open(something)')
end
it 'accepts open on a literal string' do
expect_no_offenses('open("foo.txt")')
end
it 'accepts open with no arguments' do
expect_no_offenses('open')
end
it 'accepts open with string that has a prefixed interpolation' do
expect_no_offenses('open "prefix_#{foo}"')
end
it 'accepts open with prefix string literal plus something' do
expect_no_offenses('open "prefix" + foo')
end
it 'accepts open with a string that interpolates a literal' do
expect_no_offenses('open "foo#{2}.txt"')
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/security/json_load_spec.rb | spec/rubocop/cop/security/json_load_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Security::JSONLoad, :config do
it 'registers an offense and corrects JSON.load' do
expect_offense(<<~RUBY)
JSON.load(arg)
^^^^ Prefer `JSON.parse` over `JSON.load`.
::JSON.load(arg)
^^^^ Prefer `JSON.parse` over `JSON.load`.
RUBY
expect_correction(<<~RUBY)
JSON.parse(arg)
::JSON.parse(arg)
RUBY
end
it 'registers no offense when `create_additions` option is passed' do
expect_no_offenses(<<~RUBY)
JSON.load(arg, create_additions: true)
::JSON.load(arg, create_additions: false)
RUBY
end
it 'registers an offense when an unrelated option is passed' do
expect_offense(<<~RUBY)
JSON.load(arg, max_nesting: 1)
^^^^ Prefer `JSON.parse` over `JSON.load`.
::JSON.load(arg, max_nesting: 1)
^^^^ Prefer `JSON.parse` over `JSON.load`.
RUBY
expect_correction(<<~RUBY)
JSON.parse(arg, max_nesting: 1)
::JSON.parse(arg, max_nesting: 1)
RUBY
end
it 'registers an offense and corrects JSON.restore' do
expect_offense(<<~RUBY)
JSON.restore(arg)
^^^^^^^ Prefer `JSON.parse` over `JSON.restore`.
::JSON.restore(arg)
^^^^^^^ Prefer `JSON.parse` over `JSON.restore`.
RUBY
expect_correction(<<~RUBY)
JSON.parse(arg)
::JSON.parse(arg)
RUBY
end
it 'does not register an offense for JSON under another namespace' do
expect_no_offenses(<<~RUBY)
SomeModule::JSON.load(arg)
SomeModule::JSON.restore(arg)
RUBY
end
it 'allows JSON.parse' do
expect_no_offenses(<<~RUBY)
JSON.parse(arg)
::JSON.parse(arg)
RUBY
end
it 'allows JSON.dump' do
expect_no_offenses(<<~RUBY)
JSON.dump(arg)
::JSON.dump(arg)
RUBY
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/security/yaml_load_spec.rb | spec/rubocop/cop/security/yaml_load_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Security::YAMLLoad, :config do
it 'does not register an offense for YAML.dump' do
expect_no_offenses(<<~RUBY)
YAML.dump("foo")
::YAML.dump("foo")
Module::YAML.dump("foo")
RUBY
end
it 'does not register an offense for YAML.load under a different namespace' do
expect_no_offenses('Module::YAML.load("foo")')
end
context 'Ruby <= 3.0', :ruby30, unsupported_on: :prism do
it 'registers an offense and corrects load with a literal string' do
expect_offense(<<~RUBY)
YAML.load("--- !ruby/object:Foo {}")
^^^^ Prefer using `YAML.safe_load` over `YAML.load`.
RUBY
expect_correction(<<~RUBY)
YAML.safe_load("--- !ruby/object:Foo {}")
RUBY
end
it 'registers an offense and corrects a fully qualified ::YAML.load' do
expect_offense(<<~RUBY)
::YAML.load("--- foo")
^^^^ Prefer using `YAML.safe_load` over `YAML.load`.
RUBY
expect_correction(<<~RUBY)
::YAML.safe_load("--- foo")
RUBY
end
end
# Ruby 3.1+ (Psych 4) uses `Psych.load` as `Psych.safe_load` by default.
# https://github.com/ruby/psych/pull/487
context 'Ruby >= 3.1', :ruby31 do
it 'does not register an offense load with a literal string' do
expect_no_offenses(<<~RUBY)
YAML.load("--- !ruby/object:Foo {}", permitted_classes: [Foo])
RUBY
end
it 'does not register an offense a fully qualified `::YAML.load`' do
expect_no_offenses(<<~RUBY)
::YAML.load("--- !ruby/object:Foo {}", permitted_classes: [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/bundler/gem_version_spec.rb | spec/rubocop/cop/bundler/gem_version_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Bundler::GemVersion, :config do
context 'when EnforcedStyle is set to required (default)' do
let(:cop_config) do
{
'EnforcedStyle' => 'required',
'AllowedGems' => ['rspec']
}
end
it 'flags gems that do not specify a version' do
expect_offense(<<~RUBY)
gem 'rubocop'
^^^^^^^^^^^^^ Gem version specification is required.
gem 'rubocop', require: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem version specification is required.
RUBY
end
it 'does not flag gems with a specified version' do
expect_no_offenses(<<~RUBY)
gem 'rubocop', '>=1.10.0'
gem 'rubocop', '~> 1'
gem 'rubocop', '~> 1.12', require: false
gem 'rubocop', '>= 1.5.0', '< 1.10.0', git: 'https://github.com/rubocop/rubocop'
gem 'rubocop', branch: 'feature-branch'
gem 'rubocop', ref: 'b3f37bc7f'
gem 'rubocop', tag: 'v1'
RUBY
end
it 'does not flag gems included in AllowedGems metadata' do
expect_no_offenses(<<~RUBY)
gem 'rspec'
RUBY
end
end
context 'when EnforcedStyle is set to forbidden' do
let(:cop_config) do
{
'EnforcedStyle' => 'forbidden',
'AllowedGems' => ['rspec']
}
end
it 'flags gems that specify a gem version' do
expect_offense(<<~RUBY)
gem 'rubocop', '~> 1'
^^^^^^^^^^^^^^^^^^^^^ Gem version specification is forbidden.
gem 'rubocop', '>=1.10.0'
^^^^^^^^^^^^^^^^^^^^^^^^^ Gem version specification is forbidden.
gem 'rubocop', '~> 1.12', require: false
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem version specification is forbidden.
gem 'rubocop', '>= 1.5.0', '< 1.10.0', git: 'https://github.com/rubocop/rubocop'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem version specification is forbidden.
gem 'rubocop', branch: 'feature-branch'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem version specification is forbidden.
gem 'rubocop', ref: 'b3f37bc7f'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem version specification is forbidden.
gem 'rubocop', tag: 'v1'
^^^^^^^^^^^^^^^^^^^^^^^^ Gem version specification is forbidden.
RUBY
end
it 'does not flag gems without a specified version' do
expect_no_offenses(<<~RUBY)
gem 'rubocop'
gem 'rubocop', require: false
RUBY
end
it 'does not flag gems included in AllowedGems metadata' do
expect_no_offenses(<<~RUBY)
gem 'rspec', '~> 3.10'
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/bundler/duplicated_group_spec.rb | spec/rubocop/cop/bundler/duplicated_group_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Bundler::DuplicatedGroup, :config do
let(:cop_config) { { 'Include' => ['**/Gemfile'] } }
context 'when investigating Ruby files' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'foo.rb')
# cop will not read these contents
group :development
group :development
RUBY
end
end
context 'when investigating Gemfiles' do
context 'and the file is empty' do
it 'does not register any offenses' do
expect_no_offenses('', 'Gemfile')
end
end
context 'and no duplicate groups are present' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'Gemfile')
group :development do
gem 'rubocop'
end
group :test do
gem 'flog'
end
RUBY
end
end
context 'and a group is duplicated' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
group :development do
gem 'rubocop'
end
group :development do
^^^^^^^^^^^^^^^^^^ Gem group `:development` already defined on line 1 of the Gemfile.
gem 'rubocop-rails'
end
RUBY
end
end
context 'and a group is duplicated using different argument types' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
group :development do
gem 'rubocop'
end
group 'development' do
^^^^^^^^^^^^^^^^^^^ Gem group `'development'` already defined on line 1 of the Gemfile.
gem 'rubocop-rails'
end
RUBY
end
end
context 'and a group is present in different sets of groups' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'Gemfile')
group :development do
gem 'rubocop'
end
group :development, :test do
gem 'rspec'
end
group :ci, :development do
gem 'flog'
end
RUBY
end
end
context 'and same groups with different keyword names' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
group :test, foo: true do
gem 'activesupport'
end
group :test, bar: true do
gem 'rspec'
end
RUBY
end
end
context 'and same groups with different keyword values' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
group :test, foo: true do
gem 'activesupport'
end
group :test, foo: false do
gem 'rspec'
end
RUBY
end
end
context 'and same groups with same keyword option and the option order is the same' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
group :test, foo: true, bar: true do
gem 'activesupport'
end
group :test, foo: true, bar: true do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem group `:test, foo: true, bar: true` already defined on line 1 of the Gemfile.
gem 'rspec'
end
RUBY
end
end
context 'and same groups with same keyword option and the option order is different' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
group :test, foo: true, bar: true do
gem 'activesupport'
end
group :test, bar: true, foo: true do
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem group `:test, bar: true, foo: true` already defined on line 1 of the Gemfile.
gem 'rspec'
end
RUBY
end
end
context 'and a set of groups is duplicated' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
group :test, :development do
gem 'rubocop'
end
group :development, :test do
^^^^^^^^^^^^^^^^^^^^^^^^^ Gem group `:development, :test` already defined on line 1 of the Gemfile.
gem 'rubocop-rails'
end
RUBY
end
end
context 'and a set of groups is duplicated and `group` value is a splat value' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
group(*LIVE_ENVS) do
gem 'admin_ui'
end
group(*LIVE_ENVS) do
^^^^^^^^^^^^^^^^^ Gem group `*LIVE_ENVS` already defined on line 1 of the Gemfile.
gem 'public_ui'
end
RUBY
end
end
context 'and a set of groups is duplicated but `source` URLs are different' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
source 'https://rubygems.pkg.github.com/private-org' do
group :development do
gem 'rubocop'
end
end
group :development do
gem 'rubocop-rails'
end
RUBY
end
end
context 'and a set of groups is duplicated and `source` URLs are the same' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
source 'https://rubygems.pkg.github.com/private-org' do
group :development do
gem 'rubocop'
end
end
source 'https://rubygems.pkg.github.com/private-org' do
group :development do
^^^^^^^^^^^^^^^^^^ Gem group `:development` already defined on line 2 of the Gemfile.
gem 'rubocop-rails'
end
end
group :development do
gem 'rubocop-performance'
end
RUBY
end
end
context 'and a set of groups is duplicated but `git` URLs are different' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
git 'https://github.com/rubocop/rubocop.git' do
group :default do
gem 'rubocop'
end
end
git 'https://github.com/rails/rails.git' do
group :default do
gem 'activesupport'
gem 'actionpack'
end
end
RUBY
end
end
context 'and a set of groups is duplicated and `git` URLs are the same' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
git 'https://github.com/rails/rails.git' do
group :default do
gem 'activesupport'
end
end
git 'https://github.com/rails/rails.git' do
group :default do
^^^^^^^^^^^^^^ Gem group `:default` already defined on line 2 of the Gemfile.
gem 'actionpack'
end
end
RUBY
end
end
context 'and a set of groups is duplicated but `platforms` values are different' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
platforms :ruby do
group :default do
gem 'openssl'
end
end
platforms :jruby do
group :default do
gem 'jruby-openssl'
end
end
RUBY
end
end
context 'and a set of groups is duplicated and `platforms` values are the same' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
platforms :ruby do
group :default do
gem 'ruby-debug'
end
end
platforms :ruby do
group :default do
^^^^^^^^^^^^^^ Gem group `:default` already defined on line 2 of the Gemfile.
gem 'sqlite3'
end
end
RUBY
end
end
context 'and a set of groups is duplicated but `path` values are different' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
path 'components_admin' do
group :default do
gem 'admin_ui'
end
end
path 'components_public' do
group :default do
gem 'public_ui'
end
end
RUBY
end
end
context 'and a set of groups is duplicated and `path` values are the same' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
path 'components' do
group :default do
gem 'admin_ui'
end
end
path 'components' do
group :default do
^^^^^^^^^^^^^^ Gem group `:default` already defined on line 2 of the Gemfile.
gem 'public_ui'
end
end
RUBY
end
end
context 'when `source` URL argument is not given' do
it 'does not crash' do
expect_no_offenses(<<~RUBY, 'Gemfile')
source do
group :development do
gem 'rubocop'
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/bundler/gem_filename_spec.rb | spec/rubocop/cop/bundler/gem_filename_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Bundler::GemFilename, :config do
shared_examples 'invalid gem file' do |message|
it 'registers an offense' do
offenses = _investigate(cop, processed_source)
expect(offenses.size).to eq(1)
expect(offenses.first.message).to eq(message)
end
end
shared_examples 'valid gem file' do
it 'does not register an offense' do
offenses = _investigate(cop, processed_source)
expect(offenses.size).to eq(0)
end
end
context 'with default configuration (EnforcedStyle => `Gemfile`)' do
let(:source) { 'print 1' }
let(:processed_source) { parse_source(source) }
before { allow(processed_source.buffer).to receive(:name).and_return(filename) }
context 'with gems.rb file path' do
let(:filename) { 'gems.rb' }
it_behaves_like 'invalid gem file',
'`gems.rb` file was found but `Gemfile` is required ' \
'(file path: gems.rb).'
end
context 'with non-root gems.rb file path' do
let(:filename) { 'spec/gems.rb' }
it_behaves_like 'invalid gem file',
'`gems.rb` file was found but `Gemfile` is required ' \
'(file path: spec/gems.rb).'
end
context 'with gems.locked file path' do
let(:filename) { 'gems.locked' }
it_behaves_like 'invalid gem file',
'Expected a `Gemfile.lock` with `Gemfile` but found `gems.locked` file ' \
'(file path: gems.locked).'
end
context 'with non-root gems.locked file path' do
let(:filename) { 'spec/gems.locked' }
it_behaves_like 'invalid gem file',
'Expected a `Gemfile.lock` with `Gemfile` but found `gems.locked` file ' \
'(file path: spec/gems.locked).'
end
context 'with Gemfile file path' do
let(:filename) { 'Gemfile' }
it_behaves_like 'valid gem file'
end
context 'with non-root Gemfile file path' do
let(:filename) { 'spec/Gemfile' }
it_behaves_like 'valid gem file'
end
context 'with Gemfile.lock file path' do
let(:filename) { 'Gemfile.lock' }
it_behaves_like 'valid gem file'
end
context 'with non-root Gemfile.lock file path' do
let(:filename) { 'spec/Gemfile.lock' }
it_behaves_like 'valid gem file'
end
end
context 'with EnforcedStyle set to `gems.rb`' do
let(:source) { 'print 1' }
let(:processed_source) { parse_source(source) }
let(:cop_config) { { 'EnforcedStyle' => 'gems.rb' } }
before { allow(processed_source.buffer).to receive(:name).and_return(filename) }
context 'with Gemfile file path' do
let(:filename) { 'Gemfile' }
it_behaves_like 'invalid gem file', '`Gemfile` was found but `gems.rb` file is required ' \
'(file path: Gemfile).'
end
context 'with non-root Gemfile file path' do
let(:filename) { 'spec/Gemfile' }
it_behaves_like 'invalid gem file', '`Gemfile` was found but `gems.rb` file is required ' \
'(file path: spec/Gemfile).'
end
context 'with Gemfile.lock file path' do
let(:filename) { 'Gemfile.lock' }
it_behaves_like 'invalid gem file',
'Expected a `gems.locked` file with `gems.rb` but found `Gemfile.lock` ' \
'(file path: Gemfile.lock).'
end
context 'with non-root Gemfile.lock file path' do
let(:filename) { 'spec/Gemfile.lock' }
it_behaves_like 'invalid gem file',
'Expected a `gems.locked` file with `gems.rb` but found `Gemfile.lock` ' \
'(file path: spec/Gemfile.lock).'
end
context 'with gems.rb file path' do
let(:filename) { 'gems.rb' }
it_behaves_like 'valid gem file'
end
context 'with non-root gems.rb file path' do
let(:filename) { 'spec/gems.rb' }
it_behaves_like 'valid gem file'
end
context 'with non-root gems.locked file path' do
let(:filename) { 'spec/gems.locked' }
it_behaves_like 'valid gem file'
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/bundler/gem_comment_spec.rb | spec/rubocop/cop/bundler/gem_comment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Bundler::GemComment, :config do
let(:cop_config) do
{
'Include' => ['**/Gemfile'],
'IgnoredGems' => ['rake'],
'OnlyFor' => []
}
end
context 'when investigating Ruby files' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'foo.rb')
gem('rubocop')
RUBY
end
end
context 'when investigating Gemfiles' do
context 'and the file is empty' do
it 'does not register any offenses' do
expect_no_offenses('', 'Gemfile')
end
end
context 'and the gem is commented' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'Gemfile')
# Style-guide enforcer.
gem 'rubocop'
RUBY
end
end
context 'and the gem is commented on the same line' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop' # Style-guide enforcer.
RUBY
end
end
context 'and the gem is permitted' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rake'
RUBY
end
end
context 'and the file contains source and group' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'Gemfile')
source 'http://rubygems.org'
# Style-guide enforcer.
group :development do
# …
end
RUBY
end
end
context 'and a gem has no comment' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop'
^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when the "OnlyFor" option is set' do
before { cop_config['OnlyFor'] = checked_options }
context 'including "version_specifiers"' do
let(:checked_options) { ['version_specifiers'] }
context 'when a gem is commented' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
# Style-guide enforcer.
gem 'rubocop'
RUBY
end
end
context 'when a gem is uncommented and has no version specified' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop'
RUBY
end
end
context 'when a gem is uncommented and has options but no version specifiers' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop', group: development
RUBY
end
end
context 'when a gem is uncommented and has a version specifier' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '~> 12.0'
^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has multiple version specifiers' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '~> 12.0', '>= 11.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has a version specifier along with other options' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '~> 12.0', required: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
end
context 'including "restrictive_version_specifiers"' do
let(:checked_options) { ['restrictive_version_specifiers'] }
context 'when a gem is commented' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
# Style-guide enforcer.
gem 'rubocop'
RUBY
end
end
context 'when a gem is uncommented and has no version specified' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop'
RUBY
end
end
context 'when a gem is uncommented and has options but no version specifiers' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop', group: development
RUBY
end
end
context 'when a gem is uncommented and has only a minimum version specifier' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop', '>= 12.0'
RUBY
end
end
context 'when a gem is uncommented and has a non-minimum version specifier with a leading space' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', ' ~> 12.0'
^^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has a version specifier without operator' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '12.0'
^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has a frozen version specifier' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '= 12.0'
^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has a pessimistic version specifier' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '~> 12.0'
^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has both minimum and non-minimum version specifier' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '~> 12.0', '>= 11.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has a version specifier along with other options' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', '~> 12.0', required: true
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
end
context 'including one or more option names but not "version_specifiers"' do
let(:checked_options) { %w[github required] }
context 'when a gem is uncommented and has one of the specified options' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop', github: 'some_user/some_fork'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment.
RUBY
end
end
context 'when a gem is uncommented and has a version specifier but none of the specified options' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop', '~> 12.0'
RUBY
end
end
context 'when a gem is uncommented and contains only options not specified' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop', group: development
RUBY
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/bundler/duplicated_gem_spec.rb | spec/rubocop/cop/bundler/duplicated_gem_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Bundler::DuplicatedGem, :config do
let(:cop_config) { { 'Include' => ['**/Gemfile'] } }
context 'when investigating Ruby files' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'foo.rb')
# cop will not read these contents
gem('rubocop')
gem('rubocop')
RUBY
end
end
context 'when investigating Gemfiles' do
context 'and the file is empty' do
it 'does not register any offenses' do
expect_no_offenses('', 'Gemfile')
end
end
context 'and no duplicate gems are present' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY, 'Gemfile')
gem 'rubocop'
gem 'flog'
RUBY
end
end
context 'and a gem is duplicated in default group' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
source 'https://rubygems.org'
gem 'rubocop'
gem 'rubocop'
^^^^^^^^^^^^^ Gem `rubocop` requirements already given on line 2 of the Gemfile.
RUBY
end
end
context 'and a duplicated gem is in a git/path/group/platforms block' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop'
group :development do
gem 'rubocop', path: '/path/to/gem'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem `rubocop` requirements already given on line 1 of the Gemfile.
end
RUBY
end
end
it 'registers an offense when gem from default group is conditionally duplicated' do
expect_offense(<<~RUBY, 'Gemfile')
gem 'rubocop'
if Dir.exist? local
gem 'rubocop', path: local
^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem `rubocop` requirements already given on line 1 of the Gemfile.
else
gem 'rubocop', '~> 0.90.0'
^^^^^^^^^^^^^^^^^^^^^^^^^^ Gem `rubocop` requirements already given on line 1 of the Gemfile.
end
RUBY
end
it 'does not register an offense when gem is duplicated within `if-else` statement' do
expect_no_offenses(<<~RUBY, 'Gemfile')
if Dir.exist?(local)
gem 'rubocop', path: local
gem 'flog', path: local
else
gem 'rubocop', '~> 0.90.0'
end
RUBY
end
it 'does not register an offense when gem is duplicated within `if-elsif` statement' do
expect_no_offenses(<<~RUBY, 'Gemfile')
if Dir.exist?(local)
gem 'rubocop', path: local
elsif ENV['RUBOCOP_VERSION'] == 'master'
gem 'rubocop', git: 'https://github.com/rubocop/rubocop.git'
elsif (version = ENV['RUBOCOP_VERSION'])
gem 'rubocop', version
else
gem 'rubocop', '~> 0.90.0'
end
RUBY
end
it 'does not register an offense when gem is duplicated within `case` statement' do
expect_no_offenses(<<~RUBY, 'Gemfile')
case
when Dir.exist?(local)
gem 'rubocop', path: local
when ENV['RUBOCOP_VERSION'] == 'master'
gem 'rubocop', git: 'https://github.com/rubocop/rubocop.git'
else
gem 'rubocop', '~> 0.90.0'
end
RUBY
end
it 'does not register an offense when gem is duplicated within `case` statement with empty branch' do
expect_no_offenses(<<~RUBY, 'Gemfile')
case
when Dir.exist?(local)
gem 'rubocop', path: local
when ENV['RUBOCOP_VERSION'] == 'master'
# no-op, do nothing club
else
gem 'rubocop', '~> 0.90.0'
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/bundler/insecure_protocol_source_spec.rb | spec/rubocop/cop/bundler/insecure_protocol_source_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Bundler::InsecureProtocolSource, :config do
it 'registers an offense when using `source :gemcutter`' do
expect_offense(<<~RUBY)
source :gemcutter
^^^^^^^^^^ The source `:gemcutter` is deprecated [...]
RUBY
expect_correction(<<~RUBY)
source 'https://rubygems.org'
RUBY
end
it 'registers an offense when using `source :rubygems`' do
expect_offense(<<~RUBY)
source :rubygems
^^^^^^^^^ The source `:rubygems` is deprecated [...]
RUBY
expect_correction(<<~RUBY)
source 'https://rubygems.org'
RUBY
end
it 'registers an offense when using `source :rubyforge`' do
expect_offense(<<~RUBY)
source :rubyforge
^^^^^^^^^^ The source `:rubyforge` is deprecated [...]
RUBY
expect_correction(<<~RUBY)
source 'https://rubygems.org'
RUBY
end
it "does not register an offense when using `source 'https://rubygems.org'`" do
expect_no_offenses(<<~RUBY)
source 'https://rubygems.org'
RUBY
end
context 'when `AllowHttpProtocol: true`' do
let(:cop_config) { { 'AllowHttpProtocol' => true } }
it "does not register an offense when using `source 'http://rubygems.org'`" do
expect_no_offenses(<<~RUBY)
source 'http://rubygems.org'
RUBY
end
end
context 'when `AllowHttpProtocol: false`' do
let(:cop_config) { { 'AllowHttpProtocol' => false } }
it "registers an offense when using `source 'http://rubygems.org'`" do
expect_offense(<<~RUBY)
source 'http://rubygems.org'
^^^^^^^^^^^^^^^^^^^^^ Use `https://rubygems.org` instead of `http://rubygems.org`.
RUBY
expect_correction(<<~RUBY)
source 'https://rubygems.org'
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/bundler/ordered_gems_spec.rb | spec/rubocop/cop/bundler/ordered_gems_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Bundler::OrderedGems, :config do
let(:cop_config) { { 'TreatCommentsAsGroupSeparators' => treat_comments_as_group_separators } }
let(:treat_comments_as_group_separators) { false }
context 'When gems are alphabetically sorted' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY)
gem 'rspec'
gem 'rubocop'
RUBY
end
end
context 'when a gem is referenced from a variable' do
it 'ignores the line' do
expect_no_offenses(<<~RUBY)
gem 'rspec'
gem ENV['env_key_undefined'] if ENV.key?('env_key_undefined')
gem 'rubocop'
RUBY
end
it 'resets the sorting to a new block' do
expect_no_offenses(<<~RUBY)
gem 'rubocop'
gem ENV['env_key_undefined'] if ENV.key?('env_key_undefined')
gem 'ast'
RUBY
end
end
context 'When gems are not alphabetically sorted' do
it 'registers an offense' do
expect_offense(<<~RUBY)
gem 'rubocop'
gem 'rspec'
^^^^^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `rspec` should appear before `rubocop`.
RUBY
expect_correction(<<~RUBY)
gem 'rspec'
gem 'rubocop'
RUBY
end
end
context 'When each individual group of line is sorted' do
it 'does not register any offenses' do
expect_no_offenses(<<~RUBY)
gem 'rspec'
gem 'rubocop'
gem 'hello'
gem 'world'
RUBY
end
end
context 'When a gem declaration takes several lines' do
it 'registers an offense' do
expect_offense(<<~RUBY)
gem 'rubocop',
'0.1.1'
gem 'rspec'
^^^^^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `rspec` should appear before `rubocop`.
RUBY
expect_correction(<<~RUBY)
gem 'rspec'
gem 'rubocop',
'0.1.1'
RUBY
end
end
context 'When the gemfile is empty' do
it 'does not register any offenses' do
expect_no_offenses('# Gemfile')
end
end
context 'When each individual group of line is not sorted' do
it 'registers some offenses' do
expect_offense(<<~RUBY)
gem "d"
gem "b"
^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `b` should appear before `d`.
gem "e"
gem "a"
^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `a` should appear before `e`.
gem "c"
gem "h"
gem "g"
^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `g` should appear before `h`.
gem "j"
gem "f"
^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `f` should appear before `j`.
gem "i"
RUBY
expect_correction(<<~RUBY)
gem "a"
gem "b"
gem "c"
gem "d"
gem "e"
gem "f"
gem "g"
gem "h"
gem "i"
gem "j"
RUBY
end
end
context 'When gem groups is separated by multiline comment' do
context 'with TreatCommentsAsGroupSeparators: true' do
let(:treat_comments_as_group_separators) { true }
it 'accepts' do
expect_no_offenses(<<~RUBY)
# For code quality
gem 'rubocop'
# For
# test
gem 'rspec'
RUBY
end
end
context 'with TreatCommentsAsGroupSeparators: false' do
it 'registers an offense' do
expect_offense(<<~RUBY)
# For code quality
gem 'rubocop'
# For
# test
gem 'rspec'
^^^^^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `rspec` should appear before `rubocop`.
RUBY
expect_correction(<<~RUBY)
# For
# test
gem 'rspec'
# For code quality
gem 'rubocop'
RUBY
end
end
end
context 'When gems have an inline comment, and not sorted' do
it 'registers an offense' do
expect_offense(<<~RUBY)
gem 'rubocop' # For code quality
gem 'pry'
^^^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `pry` should appear before `rubocop`.
gem 'rspec' # For test
RUBY
expect_correction(<<~RUBY)
gem 'pry'
gem 'rspec' # For test
gem 'rubocop' # For code quality
RUBY
end
end
context 'When gems are asciibetically sorted irrespective of _' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
gem 'paperclip'
gem 'paper_trail'
RUBY
end
end
context 'When a gem that starts with a capital letter is sorted' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
gem 'a'
gem 'Z'
RUBY
end
end
context 'When a gem that starts with a capital letter is not sorted' do
it 'registers an offense' do
expect_offense(<<~RUBY)
gem 'Z'
gem 'a'
^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `a` should appear before `Z`.
RUBY
expect_correction(<<~RUBY)
gem 'a'
gem 'Z'
RUBY
end
end
context 'When a gem is sorted but not so when disregarding _-' do
context 'by default' do
it 'registers an offense' do
expect_offense(<<~RUBY)
gem 'active-admin-some_plugin'
gem 'active_admin_other_plugin'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `active_admin_other_plugin` should appear before `active-admin-some_plugin`.
gem 'activeadmin'
^^^^^^^^^^^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `activeadmin` should appear before `active_admin_other_plugin`.
RUBY
expect_correction(<<~RUBY)
gem 'activeadmin'
gem 'active_admin_other_plugin'
gem 'active-admin-some_plugin'
RUBY
end
end
context 'when ConsiderPunctuation is true' do
let(:cop_config) { super().merge({ 'ConsiderPunctuation' => true }) }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
gem 'active-admin-some_plugin'
gem 'active_admin_other_plugin'
gem 'activeadmin'
RUBY
end
end
end
context 'When there are duplicated gems in group' do
it 'registers an offense' do
expect_offense(<<~RUBY)
gem 'a'
group :development do
gem 'b'
gem 'c'
gem 'b'
^^^^^^^ Gems should be sorted in an alphabetical order within their section of the Gemfile. Gem `b` should appear before `c`.
end
RUBY
expect_correction(<<~RUBY)
gem 'a'
group :development do
gem 'b'
gem 'b'
gem 'c'
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/naming/constant_name_spec.rb | spec/rubocop/cop/naming/constant_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::ConstantName, :config do
it 'registers an offense for camel case in const name' do
expect_offense(<<~RUBY)
TopCase = 5
^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'registers an offense for camel case in const name when using frozen range assignment' do
expect_offense(<<~RUBY)
TopCase = (1..5).freeze
^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'registers an offense for camel case in const name when using frozen object assignment' do
expect_offense(<<~RUBY)
TopCase = 5.freeze
^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'registers an offense for non-POSIX upper case in const name' do
expect_offense(<<~RUBY)
Nö = 'no'
^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'registers offenses for camel case in multiple const assignment' do
expect_offense(<<~RUBY)
TopCase, Test2, TEST_3 = 5, 6, 7
^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
^^^^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'registers an offense for snake case in const name' do
expect_offense(<<~RUBY)
TOP_test = 5
^^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'registers 1 offense if rhs is offending const assignment' do
expect_offense(<<~RUBY)
Bar = Foo = 4
^^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'allows screaming snake case in const name' do
expect_no_offenses('TOP_TEST = 5')
end
it 'allows screaming snake case in multiple const assignment' do
expect_no_offenses('TOP_TEST, TEST_2 = 5, 6')
end
it 'allows screaming snake case with POSIX upper case characters' do
expect_no_offenses('TÖP_TEST = 5')
end
it 'does not check names if rhs is a method call' do
expect_no_offenses('AnythingGoes = test')
end
it 'does not check names if rhs is a method call with conditional assign' do
expect_no_offenses('AnythingGoes ||= test')
end
it 'does not check names if rhs is a `Class.new`' do
expect_no_offenses('Invalid = Class.new(StandardError)')
end
it 'does not check names if rhs is a `Class.new` with conditional assign' do
expect_no_offenses('Invalid ||= Class.new(StandardError)')
end
it 'does not check names if rhs is a `Struct.new`' do
expect_no_offenses('Investigation = Struct.new(:offenses, :errors)')
end
it 'does not check names if rhs is a `Struct.new` with conditional assign' do
expect_no_offenses('Investigation ||= Struct.new(:offenses, :errors)')
end
it 'does not check names if rhs is a method call with block' do
expect_no_offenses(<<~RUBY)
AnythingGoes = test do
do_something
end
RUBY
end
it 'does not check if rhs is another constant' do
expect_no_offenses('Parser::CurrentRuby = Parser::Ruby21')
end
it 'does not check if rhs is a non-offensive const assignment' do
expect_no_offenses(<<~RUBY)
Bar = Foo = Qux
RUBY
end
it 'checks qualified const names' do
expect_offense(<<~RUBY)
::AnythingGoes = 30
^^^^^^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
a::Bar_foo = 10
^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
RUBY
end
it 'does not register an offense when assigning a constant from an empty branch of `else`' do
expect_no_offenses(<<~RUBY)
CONST = if condition
foo
else
end
RUBY
end
context 'when a rhs is a conditional expression' do
context 'when conditional branches contain only constants' do
it 'does not check names' do
expect_no_offenses('Investigation = if true then Foo else Bar end')
end
end
context 'when conditional branches contain a value other than a constant' do
it 'does not check names' do
expect_no_offenses('Investigation = if true then "foo" else Bar end')
end
end
context 'when conditional branches contain only string values' do
it 'registers an offense' do
expect_offense(<<~RUBY)
TopCase = if true then 'foo' else 'bar' end
^^^^^^^ Use SCREAMING_SNAKE_CASE for constants.
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/naming/ascii_identifiers_spec.rb | spec/rubocop/cop/naming/ascii_identifiers_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::AsciiIdentifiers, :config do
shared_examples 'checks identifiers' do
it 'registers an offense for a variable name with non-ascii chars' do
expect_offense(<<~RUBY)
älg = 1
^ Use only ascii symbols in identifiers.
RUBY
end
it 'registers an offense for a variable name with mixed chars' do
expect_offense(<<~RUBY)
foo∂∂bar = baz
^^ Use only ascii symbols in identifiers.
RUBY
end
it 'accepts identifiers with only ascii chars' do
expect_no_offenses('x.empty?')
end
it 'does not get confused by a byte order mark' do
expect_no_offenses(<<~RUBY)
puts 'foo'
RUBY
end
it 'does not get confused by an empty file' do
expect_no_offenses('')
end
end
context 'when AsciiConstants is true' do
let(:cop_config) { { 'AsciiConstants' => true } }
it_behaves_like 'checks identifiers'
it 'registers an offense for a constant name with non-ascii chars' do
expect_offense(<<~RUBY)
class Foö
^ Use only ascii symbols in constants.
end
RUBY
end
end
context 'when AsciiConstants is false' do
let(:cop_config) { { 'AsciiConstants' => false } }
it_behaves_like 'checks identifiers'
it 'accepts constants with only ascii chars' do
expect_no_offenses(<<~RUBY)
class Foo
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/naming/inclusive_language_spec.rb | spec/rubocop/cop/naming/inclusive_language_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::InclusiveLanguage, :config do
context 'flagged term matching' do
let(:cop_config) do
{ 'FlaggedTerms' => { 'whitelist' => {} } }
end
it 'registers an offense when using a flagged term' do
expect_offense(<<~RUBY)
whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with another term.
RUBY
expect_no_corrections
end
it 'registers an offense when using a flagged term with mixed case' do
expect_offense(<<~RUBY)
class WhiteList
^^^^^^^^^ Consider replacing 'WhiteList' with another term.
end
RUBY
expect_no_corrections
end
it 'registers an offense for a partial word match' do
expect_offense(<<~RUBY)
class Nodewhitelist
^^^^^^^^^ Consider replacing 'whitelist' with another term.
end
RUBY
expect_no_corrections
end
context 'disable default flagged term' do
let(:cop_config) do
{ 'FlaggedTerms' => { 'whitelist' => nil, 'blacklist' => {} } }
end
it 'ignores flagged terms that are set to nil' do
expect_offense(<<~RUBY)
# working on replacing whitelist and blacklist
^^^^^^^^^ Consider replacing 'blacklist' with another term.
RUBY
expect_no_corrections
end
end
context 'multiple offenses on a line' do
let(:cop_config) do
{ 'FlaggedTerms' => {
'master' => { 'Suggestions' => %w[main primary leader] },
'slave' => { 'Suggestions' => %w[replica secondary follower] }
} }
end
it 'registers an offense for each word' do
expect_offense(<<~RUBY)
master, slave = nodes
^^^^^ Consider replacing 'slave' with 'replica', 'secondary', or 'follower'.
^^^^^^ Consider replacing 'master' with 'main', 'primary', or 'leader'.
RUBY
expect_no_corrections
end
end
context 'regex' do
let(:cop_config) do
{ 'FlaggedTerms' => { 'whitelist' => { 'Regex' => /white[-_\s]?list/ } } }
end
it 'registers an offense for a flagged term matched with a regexp' do
expect_offense(<<~RUBY)
# white-list of IPs
^^^^^^^^^^ Consider replacing 'white-list' with another term.
RUBY
expect_no_corrections
end
end
context 'WholeWord: true' do
let(:cop_config) do
{ 'CheckStrings' => true, 'FlaggedTerms' => { 'slave' => { 'WholeWord' => true } } }
end
it 'only flags when the term is a whole word' do
expect_offense(<<~RUBY)
# infix allowed
TeslaVehicle
SLAVersion
:teslavehicle
# prefix allowed
DatabaseSlave
# suffix allowed
Slave1
# not allowed
Slave
^^^^^ Consider replacing 'Slave' with another term.
:database_slave
^^^^^ Consider replacing 'slave' with another term.
'database@slave'
^^^^^ Consider replacing 'slave' with another term.
RUBY
expect_no_corrections
end
end
end
context 'allowed use' do
let(:cop_config) do
{ 'FlaggedTerms' => {
'master' => { 'AllowedRegex' => 'master\'s degree' }
} }
end
it 'does not register an offense for an allowed use' do
expect_no_offenses(<<~RUBY)
# They had a Master's Degree
RUBY
end
context 'offense after an allowed use' do
let(:cop_config) do
{ 'FlaggedTerms' => {
'foo' => {},
'bar' => { 'AllowedRegex' => 'barx' }
} }
end
it 'registers an offense at the correct location' do
expect_offense(<<~RUBY)
barx, foo = method_call
^^^ Consider replacing 'foo' with another term.
RUBY
expect_no_corrections
end
end
end
context 'suggestions' do
context 'flagged term with one suggestion' do
let(:cop_config) do
{ 'FlaggedTerms' => {
'whitelist' => { 'Suggestions' => 'allowlist' }
} }
end
it 'includes the suggestion in the offense message' do
expect_offense(<<~RUBY)
whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with 'allowlist'.
RUBY
expect_correction(<<~RUBY)
allowlist = %w(user1 user2)
RUBY
end
end
context 'flagged term with one suggestion in array' do
let(:cop_config) do
{ 'FlaggedTerms' => {
'whitelist' => { 'Suggestions' => %w[allowlist] }
} }
end
it 'includes both suggestions in the offense message' do
expect_offense(<<~RUBY)
whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with 'allowlist'.
RUBY
expect_correction(<<~RUBY)
allowlist = %w(user1 user2)
RUBY
end
end
context 'flagged term with two suggestions' do
let(:cop_config) do
{ 'FlaggedTerms' => {
'whitelist' => { 'Suggestions' => %w[allowlist permit] }
} }
end
it 'includes both suggestions in the offense message' do
expect_offense(<<~RUBY)
whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with 'allowlist' or 'permit'.
RUBY
expect_no_corrections
end
end
context 'flagged term with three or more suggestions' do
let(:cop_config) do
{
'CheckStrings' => true,
'FlaggedTerms' => {
'master' => { 'Suggestions' => %w[main primary leader] }
}
}
end
it 'includes all suggestions in the message' do
expect_offense(<<~RUBY)
default_branch = 'master'
^^^^^^ Consider replacing 'master' with 'main', 'primary', or 'leader'.
RUBY
expect_no_corrections
end
end
end
context 'identifiers' do
let(:cop_config) do
{ 'CheckIdentifiers' => check_identifiers, 'FlaggedTerms' => { 'whitelist' => {} } }
end
context 'when CheckIdentifiers config is true' do
let(:check_identifiers) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with another term.
RUBY
expect_no_corrections
end
end
context 'when CheckIdentifiers config is false' do
let(:check_identifiers) { false }
it 'does not register offenses for identifiers' do
expect_no_offenses(<<~RUBY)
whitelist = %w(user1 user2)
RUBY
end
end
end
context 'variables' do
let(:cop_config) do
{ 'CheckVariables' => check_variables, 'FlaggedTerms' => { 'whitelist' => {} } }
end
context 'when CheckVariables config is true' do
let(:check_variables) { true }
it 'registers offenses for instance variables' do
expect_offense(<<~RUBY)
@whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with another term.
RUBY
expect_no_corrections
end
it 'registers offenses for class variables' do
expect_offense(<<~RUBY)
@@whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with another term.
RUBY
expect_no_corrections
end
it 'registers offenses for global variables' do
expect_offense(<<~RUBY)
$whitelist = %w(user1 user2)
^^^^^^^^^ Consider replacing 'whitelist' with another term.
RUBY
expect_no_corrections
end
end
context 'when CheckVariables config is false' do
let(:check_variables) { false }
it 'does not register offenses for variables' do
expect_no_offenses(<<~RUBY)
@whitelist = %w(user1 user2)
RUBY
end
end
end
context 'constants' do
let(:cop_config) do
{ 'CheckConstants' => check_constants, 'FlaggedTerms' => { 'whitelist' => {} } }
end
context 'when CheckConstants config is true' do
let(:check_constants) { true }
it 'registers offenses for constants' do
expect_offense(<<~RUBY)
WHITELIST = %w(user1 user2)
^^^^^^^^^ Consider replacing 'WHITELIST' with another term.
RUBY
expect_no_corrections
end
end
context 'when CheckConstants config is false' do
let(:check_constants) { false }
it 'does not register offenses for constants' do
expect_no_offenses(<<~RUBY)
WHITELIST = %w(user1 user2)
RUBY
end
end
end
context 'strings' do
let(:check_strings) { true }
let(:cop_config) do
{ 'CheckStrings' => check_strings, 'FlaggedTerms' => { 'master' => {}, 'slave' => {} } }
end
it 'registers an offense for an interpolated string' do
expect_offense(<<~RUBY)
puts "master node \#{node}"
^^^^^^ Consider replacing 'master' with another term.
RUBY
end
it 'registers an offense for a multiline string' do
expect_offense(<<~RUBY)
node_types = "master
^^^^^^ Consider replacing 'master' with another term.
slave
^^^^^ Consider replacing 'slave' with another term.
primary
secondary"
RUBY
expect_no_corrections
end
it 'registers an offense in a heredoc' do
expect_offense(<<~RUBY)
node_text = <<~TEXT
master
^^^^^^ Consider replacing 'master' with another term.
primary
slave
^^^^^ Consider replacing 'slave' with another term.
secondary
TEXT
RUBY
expect_no_corrections
end
it 'does not register offenses and not raise `ArgumentError` for invalid byte sequence in UTF-8' do
expect_no_offenses(<<~RUBY)
%W("a\\255\\255")
RUBY
end
context 'when CheckStrings config is false' do
let(:check_strings) { false }
it 'does not register offenses for strings' do
expect_no_offenses(<<~RUBY)
puts "master node \#{node}"
RUBY
end
end
end
context 'symbols' do
let(:cop_config) do
{ 'CheckSymbols' => check_symbols, 'FlaggedTerms' => { 'master' => {} } }
end
context 'when CheckSymbols is true' do
let(:check_symbols) { true }
it 'registers an offense' do
expect_offense(<<~RUBY)
config[:master] = {}
^^^^^^ Consider replacing 'master' with another term.
RUBY
expect_no_corrections
end
end
context 'when CheckSymbols is false' do
let(:check_symbols) { false }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
config[:master] = {}
RUBY
end
end
end
context 'comments' do
let(:check_comments) { true }
let(:cop_config) do
{ 'CheckComments' => check_comments, 'FlaggedTerms' => { 'foo' => {} } }
end
it 'registers an offense in a single line comment' do
expect_offense(<<~RUBY)
# is it a foo?
^^^ Consider replacing 'foo' with another term.
bar = baz # it's a foo!
^^^ Consider replacing 'foo' with another term.
RUBY
expect_no_corrections
end
it 'registers an offense in a block comment' do
expect_offense(<<~RUBY)
=begin
foo
^^^ Consider replacing 'foo' with another term.
bar
=end
RUBY
expect_no_corrections
end
context 'when CheckComments is false' do
let(:check_comments) { false }
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
# is it a foo?
RUBY
end
end
end
context 'filepath' do
context 'one offense in filename' do
let(:cop_config) do
{ 'FlaggedTerms' => { 'master' => { 'Suggestions' => 'main' } } }
end
it 'registers an offense' do
expect_offense(<<~RUBY, '/some/dir/master.rb')
^{} Consider replacing 'master' in file path with 'main'.
RUBY
end
end
context 'multiple offenses in filename' do
let(:cop_config) do
{ 'FlaggedTerms' => { 'master' => {}, 'slave' => {} } }
end
let(:filename) { '/some/config/master-slave.rb' }
it 'registers an offense with all problematic words' do
expect_offense(<<~RUBY, '/some/config/master-slave.rb')
^{} Consider replacing 'master', 'slave' in file path with other terms.
RUBY
end
end
context 'offense in directory name' do
let(:cop_config) do
{ 'FlaggedTerms' => { 'master' => {} } }
end
it 'registers an offense for a director' do
expect_offense(<<~RUBY, '/db/master/config.yml')
^{} Consider replacing 'master' in file path with another term.
RUBY
end
end
context 'CheckFilepaths is false' do
let(:cop_config) do
{ 'CheckFilepaths' => false, 'FlaggedTerms' => { 'master' => {} } }
end
it 'does not register an offense' do
expect_no_offenses('', '/some/dir/master.rb')
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/naming/method_name_spec.rb | spec/rubocop/cop/naming/method_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::MethodName, :config do
shared_examples 'never accepted' do |enforced_style|
it 'registers an offense for mixed snake case and camel case in attr.' do
expect_offense(<<~RUBY)
attr :visit_Arel_Nodes_SelectStatement
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr_reader :visit_Arel_Nodes_SelectStatement
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr_accessor :visit_Arel_Nodes_SelectStatement
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr_writer :visit_Arel_Nodes_SelectStatement
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr 'visit_Arel_Nodes_SelectStatement'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
RUBY
end
it 'registers an offense for mixed snake case and camel case in attr.' do
expect_offense(<<~RUBY)
attr_reader :visit_Arel_Nodes_SelectStatement
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr_reader 'visit_Arel_Nodes_SelectStatement'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
RUBY
end
it 'registers an offense for mixed snake case and camel case' do
expect_offense(<<~RUBY)
def visit_Arel_Nodes_SelectStatement
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
end
RUBY
end
it 'registers an offense for capitalized camel case name in attr.' do
expect_offense(<<~RUBY)
attr :MyMethod
^^^^^^^^^ Use #{enforced_style} for method names.
attr_reader :MyMethod
^^^^^^^^^ Use #{enforced_style} for method names.
attr_accessor :MyMethod
^^^^^^^^^ Use #{enforced_style} for method names.
attr_writer :MyMethod
^^^^^^^^^ Use #{enforced_style} for method names.
RUBY
end
it 'registers an offense for capitalized camel case' do
expect_offense(<<~RUBY)
class MyClass
def MyMethod
^^^^^^^^ Use #{enforced_style} for method names.
end
end
RUBY
end
it 'registers an offense for singleton upper case method without corresponding class' do
expect_offense(<<~RUBY)
module Sequel
def self.Model(source)
^^^^^ Use #{enforced_style} for method names.
end
end
RUBY
end
end
shared_examples 'always accepted' do |enforced_style|
it 'accepts one line methods' do
expect_no_offenses("def body; '' end")
end
it 'accepts operator definitions' do
expect_no_offenses(<<~RUBY)
def +(other)
# ...
end
RUBY
end
it 'accepts unary operator definitions' do
expect_no_offenses(<<~RUBY)
def ~@; end
RUBY
expect_no_offenses(<<~RUBY)
def !@; end
RUBY
end
it 'accepts `alias_method` with non-intern first argument' do
expect_no_offenses(<<~RUBY)
alias_method foo, :bar
alias_method fooBar, :bar
RUBY
end
it 'accepts `alias_method` with array splat' do
expect_no_offenses(<<~RUBY)
alias_method *ary
RUBY
end
it 'accepts `alias_method` with unexpected arity' do
expect_no_offenses(<<~RUBY)
alias_method :foo, :bar, :baz
alias_method :fooBar, :bar, :baz
RUBY
end
%w[class module].each do |kind|
it "accepts class emitter method in a #{kind}" do
expect_no_offenses(<<~RUBY)
#{kind} Sequel
def self.Model(source)
end
class Model
end
end
RUBY
end
it "accepts class emitter method in a #{kind}, even when it is " \
'defined inside another method' do
expect_no_offenses(<<~RUBY)
module DPN
module Flow
module BaseFlow
class Start
end
def self.included(base)
def base.Start(aws_env, *args)
end
end
end
end
end
RUBY
end
end
%w[Struct ::Struct].each do |class_name|
it "does not register an offense for member-less #{class_name}" do
expect_no_offenses(<<~RUBY)
#{class_name}.new()
RUBY
end
end
%i[define_method define_singleton_method].each do |name|
%w[== >= <= > < =~ ! [] []= gärten].each do |method_name|
it "does not register an offense when `#{name}` is called with a `#{method_name}` method name" do
expect_no_offenses(<<~RUBY)
#{name} :#{method_name} do
end
RUBY
end
end
end
context 'when specifying `AllowedPatterns`' do
let(:cop_config) do
{
'EnforcedStyle' => enforced_style,
'AllowedPatterns' => [
'\AonSelectionBulkChange\z',
'\Aon_selection_cleared\z'
]
}
end
it 'does not register an offense for camel case method name in attr.' do
expect_no_offenses(<<~RUBY)
attr_reader :onSelectionBulkChange
attr_accessor :onSelectionBulkChange
attr_writer :onSelectionBulkChange
RUBY
end
it 'does not register an offense for camel case method name matching `AllowedPatterns`' do
expect_no_offenses(<<~RUBY)
def onSelectionBulkChange(arg)
end
RUBY
end
it 'does not register an offense for snake case method name in attr.' do
expect_no_offenses(<<~RUBY)
attr_reader :on_selection_cleared
attr_accessor :on_selection_cleared
attr_writer :on_selection_cleared
RUBY
end
it 'does not register an offense for snake case method name matching `AllowedPatterns`' do
expect_no_offenses(<<~RUBY)
def on_selection_cleared(arg)
end
RUBY
end
end
end
shared_examples 'multiple attr methods' do |enforced_style|
it 'registers an offense for camel case methods names in attr.' do
expect_offense(<<~RUBY)
attr :my_method, :myMethod
^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr_reader :my_method, :myMethod
^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr_accessor :myMethod, :my_method
^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
attr_accessor 'myMethod', 'my_method'
^^^^^^^^^^^^^^^^^^^^^^^ Use #{enforced_style} for method names.
RUBY
end
end
shared_examples 'forbidden identifiers' do |identifier|
context 'when ForbiddenIdentifiers is set' do
let(:cop_config) { super().merge('ForbiddenIdentifiers' => [identifier]) }
context 'for multi-line method definition' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
def %{identifier}
^{identifier} `%{identifier}` is forbidden, use another method name instead.
true
end
RUBY
expect_no_corrections
end
end
context 'for single-line method definition' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
def %{identifier}; true; end
^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for class method definition' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
def self.%{identifier}
^{identifier} `%{identifier}` is forbidden, use another method name instead.
end
RUBY
expect_no_corrections
end
end
context 'for singleton method definition' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
def foo.%{identifier}
^{identifier} `%{identifier}` is forbidden, use another method name instead.
end
RUBY
expect_no_corrections
end
end
context 'for attr methods' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
attr_reader :#{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
attr_writer :#{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
attr_accessor :#{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for define_method' do
it 'registers an offense when method with forbidden name is defined using `define_method`' do
expect_offense(<<~RUBY, identifier: identifier)
define_method :%{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
end
it 'registers an offense when method with forbidden name is defined using `define_singleton_method`' do
expect_offense(<<~RUBY, identifier: identifier)
define_singleton_method :%{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
end
end
context 'for `Struct` members' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
Struct.new(:%{identifier})
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for `Data` members' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
Data.define(:%{identifier})
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for `alias` arguments' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
alias %{identifier} foo
^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for `alias_method` arguments' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
alias_method :%{identifier}, :foo
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
end
end
shared_examples 'forbidden patterns' do |pattern, identifier|
context 'when ForbiddenIdentifiers is set' do
let(:cop_config) { super().merge('ForbiddenPatterns' => [pattern]) }
context 'for multi-line method definition' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
def %{identifier}
^{identifier} `%{identifier}` is forbidden, use another method name instead.
true
end
RUBY
expect_no_corrections
end
end
context 'for single-line method definition' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
def %{identifier}; true; end
^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for attr methods' do
it 'registers an offense when method with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
attr_reader :#{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
attr_writer :#{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
attr_accessor :#{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for define_method' do
it 'registers an offense when method with forbidden name is defined using `define_method`' do
expect_offense(<<~RUBY, identifier: identifier)
define_method :%{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
end
it 'registers an offense when method with forbidden name is defined using `define_singleton_method`' do
expect_offense(<<~RUBY, identifier: identifier)
define_singleton_method :%{identifier}
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
end
end
context 'for `Struct` members' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
Struct.new(:%{identifier})
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for `Data` members' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
Data.define(:%{identifier})
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for `alias` arguments' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
alias %{identifier} foo
^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
context 'for `alias_method` arguments' do
it 'registers an offense when member with forbidden name is defined' do
expect_offense(<<~RUBY, identifier: identifier)
alias_method :%{identifier}, :foo
^^{identifier} `%{identifier}` is forbidden, use another method name instead.
RUBY
expect_no_corrections
end
end
end
end
shared_examples 'define_method method call' do |enforced_style, identifier|
%i[define_method define_singleton_method].each do |name|
it 'registers an offense when method name is passed as a symbol' do
expect_offense(<<~RUBY, name: name, enforced_style: enforced_style, identifier: identifier)
%{name} :%{identifier} do
_{name} ^^{identifier} Use %{enforced_style} for method names.
end
RUBY
end
it 'registers an offense when method name is passed as a string' do
expect_offense(<<~RUBY, name: name, enforced_style: enforced_style, identifier: identifier)
%{name} '%{identifier}' do
_{name} ^^{identifier}^ Use %{enforced_style} for method names.
end
RUBY
end
it 'does not register an offense when `define_method` is called without any arguments`' do
expect_no_offenses(<<~RUBY)
#{name} do
end
RUBY
end
it 'does not register an offense when `define_method` is called with a variable`' do
expect_no_offenses(<<~RUBY)
#{name} foo do
end
RUBY
end
it 'does not register an offense when an operator method is defined using a string' do
expect_no_offenses(<<~RUBY)
#{name} '`' do
end
RUBY
end
end
end
context 'when configured for snake_case' do
let(:cop_config) { { 'EnforcedStyle' => 'snake_case' } }
it 'registers an offense for camel case method names in attr.' do
expect_offense(<<~RUBY)
attr_reader :myMethod
^^^^^^^^^ Use snake_case for method names.
attr_accessor :myMethod
^^^^^^^^^ Use snake_case for method names.
attr_writer :myMethod
^^^^^^^^^ Use snake_case for method names.
RUBY
end
it 'registers an offense for camel case in instance method name' do
expect_offense(<<~RUBY)
def myMethod
^^^^^^^^ Use snake_case for method names.
# ...
end
RUBY
end
it 'registers an offense for opposite + correct' do
expect_offense(<<~RUBY)
def my_method
end
def myMethod
^^^^^^^^ Use snake_case for method names.
end
RUBY
end
it 'registers an offense for camel case in singleton method name' do
expect_offense(<<~RUBY)
def self.myMethod
^^^^^^^^ Use snake_case for method names.
# ...
end
RUBY
end
it 'accepts snake case in attr.' do
expect_no_offenses(<<~RUBY)
attr_reader :my_method
attr_accessor :my_method
attr_writer :my_method
RUBY
end
it 'accepts snake case in names' do
expect_no_offenses(<<~RUBY)
def my_method
end
RUBY
end
it 'registers an offense for singleton camelCase method within class' do
expect_offense(<<~RUBY)
class Sequel
def self.fooBar
^^^^^^ Use snake_case for method names.
end
end
RUBY
end
it 'registers an offense for `Struct` camelCase member' do
expect_offense(<<~RUBY)
Struct.new("camelCase", :snake_case, var, *args, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^ Use snake_case for method names.
^^^^^^^^^^^^ Use snake_case for method names.
RUBY
end
it 'registers an offense for `::Struct` camelCase member' do
expect_offense(<<~RUBY)
::Struct.new("camelCase", :snake_case, var, *args, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^ Use snake_case for method names.
^^^^^^^^^^^^ Use snake_case for method names.
RUBY
end
it 'registers an offense for `Data` camelCase member' do
expect_offense(<<~RUBY)
Data.define(:snake_case, var, *args, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^ Use snake_case for method names.
^^^^^^^^^^^^ Use snake_case for method names.
RUBY
end
it 'registers an offense for `::Data` camelCase member' do
expect_offense(<<~RUBY)
::Data.define(:snake_case, var, *args, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^ Use snake_case for method names.
^^^^^^^^^^^^ Use snake_case for method names.
RUBY
end
it 'registers an offense for `alias` camelCase argument' do
expect_offense(<<~RUBY)
alias fooBar foo
^^^^^^ Use snake_case for method names.
RUBY
end
it 'registers an offense for `alias_method` camelCase argument' do
expect_offense(<<~RUBY)
alias_method :fooBar, :foo
^^^^^^^ Use snake_case for method names.
RUBY
end
it 'accepts `alias` with interpolated symbol argument' do
expect_no_offenses(<<~'RUBY')
alias :"foo#{bar}" :baz
RUBY
end
it 'registers an offense for `alias_method` snake_case string argument' do
expect_offense(<<~RUBY)
alias_method "fooBar", "foo"
^^^^^^^^ Use snake_case for method names.
RUBY
end
it 'accepts `alias_method` with interpolated string argument' do
expect_no_offenses(<<~'RUBY')
alias_method "foo#{bar}", "baz"
RUBY
end
it_behaves_like 'never accepted', 'snake_case'
it_behaves_like 'always accepted', 'snake_case'
it_behaves_like 'multiple attr methods', 'snake_case'
it_behaves_like 'forbidden identifiers', 'super'
it_behaves_like 'forbidden patterns', '_v1\z', 'api_v1'
it_behaves_like 'define_method method call', 'snake_case', 'fooBar'
it_behaves_like 'define_method method call', 'snake_case', 'fooBar?'
it_behaves_like 'define_method method call', 'snake_case', 'fooBar!'
it_behaves_like 'define_method method call', 'snake_case', 'fooBar='
end
context 'when configured for camelCase' do
let(:cop_config) { { 'EnforcedStyle' => 'camelCase' } }
it 'accepts camel case names in attr.' do
expect_no_offenses(<<~RUBY)
attr_reader :myMethod
attr_accessor :myMethod
attr_writer :myMethod
RUBY
end
it 'accepts camel case in instance method name' do
expect_no_offenses(<<~RUBY)
def myMethod
# ...
end
RUBY
end
it 'accepts camel case in singleton method name' do
expect_no_offenses(<<~RUBY)
def self.myMethod
# ...
end
RUBY
end
it 'registers an offense for snake case name in attr.' do
expect_offense(<<~RUBY)
attr_reader :my_method
^^^^^^^^^^ Use camelCase for method names.
attr_accessor :my_method
^^^^^^^^^^ Use camelCase for method names.
attr_writer :my_method
^^^^^^^^^^ Use camelCase for method names.
attr_writer 'my_method'
^^^^^^^^^^^ Use camelCase for method names.
RUBY
end
it 'registers an offense for snake case in names' do
expect_offense(<<~RUBY)
def my_method
^^^^^^^^^ Use camelCase for method names.
end
RUBY
end
it 'registers an offense for correct + opposite' do
expect_offense(<<~RUBY)
def myMethod
end
def my_method
^^^^^^^^^ Use camelCase for method names.
end
RUBY
end
it 'registers an offense for singleton snake_case method within class' do
expect_offense(<<~RUBY)
class Sequel
def self.foo_bar
^^^^^^^ Use camelCase for method names.
end
end
RUBY
end
it 'registers an offense for `Struct` snake_case member' do
expect_offense(<<~RUBY)
Struct.new("foo_bar", var, *args, :snake_case, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^^ Use camelCase for method names.
^^^^^^^^^^^^^ Use camelCase for method names.
RUBY
end
it 'registers an offense for `::Struct` snake_case member' do
expect_offense(<<~RUBY)
::Struct.new("foo_bar", var, *args, :snake_case, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^^ Use camelCase for method names.
^^^^^^^^^^^^^ Use camelCase for method names.
RUBY
end
it 'registers an offense for `Data` snake_case member' do
expect_offense(<<~RUBY)
Data.define(var, *args, :snake_case, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^^ Use camelCase for method names.
^^^^^^^^^^^^^ Use camelCase for method names.
RUBY
end
it 'registers an offense for `::Data` snake_case member' do
expect_offense(<<~RUBY)
::Data.define(var, *args, :snake_case, :camelCase, :snake_case_2, "camelCase2")
^^^^^^^^^^^ Use camelCase for method names.
^^^^^^^^^^^^^ Use camelCase for method names.
RUBY
end
it 'registers an offense for `alias` snake_case argument' do
expect_offense(<<~RUBY)
alias foo_bar foo
^^^^^^^ Use camelCase for method names.
RUBY
end
it 'registers an offense for `alias_method` snake_case symbol argument' do
expect_offense(<<~RUBY)
alias_method :foo_bar, :foo
^^^^^^^^ Use camelCase for method names.
RUBY
end
it 'registers an offense for `alias_method` snake_case string argument' do
expect_offense(<<~RUBY)
alias_method "foo_bar", "foo"
^^^^^^^^^ Use camelCase for method names.
RUBY
end
it_behaves_like 'always accepted', 'camelCase'
it_behaves_like 'never accepted', 'camelCase'
it_behaves_like 'multiple attr methods', 'camelCase'
it_behaves_like 'forbidden identifiers', 'super'
it_behaves_like 'forbidden patterns', '_gen\d+\z', 'user_gen1'
it_behaves_like 'define_method method call', 'camelCase', 'foo_bar'
it_behaves_like 'define_method method call', 'camelCase', 'foo_bar?'
it_behaves_like 'define_method method call', 'camelCase', 'foo_bar!'
it_behaves_like 'define_method method call', 'camelCase', 'foo_bar='
end
it 'accepts for non-ascii characters' do
expect_no_offenses(<<~RUBY)
def última_vista; 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/naming/variable_number_spec.rb | spec/rubocop/cop/naming/variable_number_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::VariableNumber, :config do
shared_examples 'offense' do |style, variable, style_to_allow_offenses|
it "registers an offense for #{variable} in #{style}" do
expect_offense(<<~RUBY, variable: variable)
#{variable} = 1
^{variable} Use #{style} for variable numbers.
RUBY
expect(cop.config_to_allow_offenses).to eq(
{ 'EnforcedStyle' => style_to_allow_offenses.to_s }
)
end
end
shared_examples 'offense_array' do |style, variables|
it "registers an offense for #{variables} in #{style}" do
lines = variables.map { |v| "#{v} = 1" }
lines.insert(1, "^{first_variable} Use #{style} for variable numbers.")
expect_offense(lines.join("\n"), first_variable: variables.first)
expect(cop.config_to_allow_offenses).to eq({ 'Enabled' => false })
end
end
shared_examples 'accepts' do |style, variable|
# `_1 = 1` is a deprecated valid syntax in Ruby 2.7, but an invalid syntax in Ruby 3.0+.
it "accepts #{variable} in #{style}", :ruby27, unsupported_on: :prism do
expect_no_offenses("#{variable} = 1")
end
end
shared_examples 'accepts integer symbols' do
it 'accepts integer symbol' do
expect_no_offenses(':"42"')
end
it 'accepts integer symbol array literal' do
expect_no_offenses('%i[1 2 3]')
end
end
context 'when configured for snake_case' do
let(:cop_config) { { 'EnforcedStyle' => 'snake_case' } }
it_behaves_like 'offense', 'snake_case', 'local1', :normalcase
it_behaves_like 'offense', 'snake_case', '@local1', :normalcase
it_behaves_like 'offense', 'snake_case', '@@local1', :normalcase
it_behaves_like 'offense', 'snake_case', 'camelCase1', :normalcase
it_behaves_like 'offense', 'snake_case', '@camelCase1', :normalcase
it_behaves_like 'offense', 'snake_case', '_unused1', :normalcase
it_behaves_like 'offense', 'snake_case', 'aB1', :normalcase
it_behaves_like 'offense_array', 'snake_case', %w[a1 a_2]
it_behaves_like 'accepts', 'snake_case', 'local_1'
it_behaves_like 'accepts', 'snake_case', 'local_12'
it_behaves_like 'accepts', 'snake_case', 'local_123'
it_behaves_like 'accepts', 'snake_case', 'local_'
it_behaves_like 'accepts', 'snake_case', 'aB_1'
it_behaves_like 'accepts', 'snake_case', 'a_1_b'
it_behaves_like 'accepts', 'snake_case', 'a_1_b_1'
it_behaves_like 'accepts', 'snake_case', '_'
it_behaves_like 'accepts', 'snake_case', '_foo'
it_behaves_like 'accepts', 'snake_case', '@foo'
it_behaves_like 'accepts', 'snake_case', '@__foo__'
it_behaves_like 'accepts', 'snake_case', 'emparejó'
it_behaves_like 'accepts', 'snake_case', '_1'
it_behaves_like 'accepts integer symbols'
it 'registers an offense for normal case numbering in symbol' do
expect_offense(<<~RUBY)
:sym1
^^^^^ Use snake_case for symbol numbers.
RUBY
end
it 'does not register an offense for snake case numbering in symbol' do
expect_no_offenses(<<~RUBY)
:sym_1
RUBY
end
it 'registers an offense for normal case numbering in method parameter' do
expect_offense(<<~RUBY)
def method(arg1); end
^^^^ Use snake_case for variable numbers.
RUBY
end
it 'registers an offense for normal case numbering in method camel case parameter' do
expect_offense(<<~RUBY)
def method(funnyArg1); end
^^^^^^^^^ Use snake_case for variable numbers.
RUBY
end
it 'registers an offense for normal case numbering in method name' do
expect_offense(<<~RUBY)
def method1; end
^^^^^^^ Use snake_case for method name numbers.
RUBY
end
it 'registers an offense for normal case numbering in a global variable name' do
expect_offense(<<~RUBY)
$arg1 = :foo
^^^^^ Use snake_case for variable numbers.
RUBY
end
end
context 'when configured for normal' do
let(:cop_config) { { 'EnforcedStyle' => 'normalcase' } }
it_behaves_like 'offense', 'normalcase', 'local_1', :snake_case
it_behaves_like 'offense', 'normalcase', 'sha_256', :snake_case
it_behaves_like 'offense', 'normalcase', '@local_1', :snake_case
it_behaves_like 'offense', 'normalcase', '@@local_1', :snake_case
it_behaves_like 'offense', 'normalcase', 'myAttribute_1', :snake_case
it_behaves_like 'offense', 'normalcase', '@myAttribute_1', :snake_case
it_behaves_like 'offense', 'normalcase', '_myLocal_1', :snake_case
it_behaves_like 'offense', 'normalcase', 'localFOO_1', :snake_case
it_behaves_like 'offense', 'normalcase', 'local_FOO_1', :snake_case
it_behaves_like 'offense_array', 'normalcase', %w[a_1 a2]
it_behaves_like 'accepts', 'normalcase', 'local1'
it_behaves_like 'accepts', 'normalcase', 'local_'
it_behaves_like 'accepts', 'normalcase', 'user1_id'
it_behaves_like 'accepts', 'normalcase', 'sha256'
it_behaves_like 'accepts', 'normalcase', 'foo10_bar'
it_behaves_like 'accepts', 'normalcase', 'target_u2f_device'
it_behaves_like 'accepts', 'normalcase', 'localFOO1'
it_behaves_like 'accepts', 'normalcase', 'snake_case'
it_behaves_like 'accepts', 'normalcase', 'user_1_id'
it_behaves_like 'accepts', 'normalcase', '_'
it_behaves_like 'accepts', 'normalcase', '_foo'
it_behaves_like 'accepts', 'normalcase', '@foo'
it_behaves_like 'accepts', 'normalcase', '@__foo__'
it_behaves_like 'accepts', 'normalcase', 'emparejó'
it_behaves_like 'accepts', 'normalcase', '_1'
it_behaves_like 'accepts integer symbols'
it 'registers an offense for snake case numbering in symbol' do
expect_offense(<<~RUBY)
:sym_1
^^^^^^ Use normalcase for symbol numbers.
RUBY
end
it 'does not register an offense for normal case numbering in symbol' do
expect_no_offenses(':sym1')
end
it 'registers an offense for snake case numbering in method parameter' do
expect_offense(<<~RUBY)
def method(arg_1); end
^^^^^ Use normalcase for variable numbers.
RUBY
end
it 'registers an offense for snake case numbering in method camel case parameter' do
expect_offense(<<~RUBY)
def method(funnyArg_1); end
^^^^^^^^^^ Use normalcase for variable numbers.
RUBY
end
it 'registers an offense for snake case numbering in method name' do
expect_offense(<<~RUBY)
def method_1; end
^^^^^^^^ Use normalcase for method name numbers.
RUBY
end
it 'registers an offense for snake case numbering in a global variable name' do
expect_offense(<<~RUBY)
$arg_1 = :foo
^^^^^^ Use normalcase for variable numbers.
RUBY
end
end
context 'when configured for non integer' do
let(:cop_config) { { 'EnforcedStyle' => 'non_integer' } }
it_behaves_like 'offense', 'non_integer', 'local_1', :snake_case
it_behaves_like 'offense', 'non_integer', 'local1', :normalcase
it_behaves_like 'offense', 'non_integer', '@local_1', :snake_case
it_behaves_like 'offense', 'non_integer', '@local1', :normalcase
it_behaves_like 'offense', 'non_integer', 'myAttribute_1', :snake_case
it_behaves_like 'offense', 'non_integer', 'myAttribute1', :normalcase
it_behaves_like 'offense', 'non_integer', '@myAttribute_1', :snake_case
it_behaves_like 'offense', 'non_integer', '@myAttribute1', :normalcase
it_behaves_like 'offense', 'non_integer', '_myLocal_1', :snake_case
it_behaves_like 'offense', 'non_integer', '_myLocal1', :normalcase
it_behaves_like 'offense_array', 'non_integer', %w[a_1 aone]
it_behaves_like 'accepts', 'non_integer', 'localone'
it_behaves_like 'accepts', 'non_integer', 'local_one'
it_behaves_like 'accepts', 'non_integer', 'local_'
it_behaves_like 'accepts', 'non_integer', '@foo'
it_behaves_like 'accepts', 'non_integer', '@@foo'
it_behaves_like 'accepts', 'non_integer', 'fooBar'
it_behaves_like 'accepts', 'non_integer', '_'
it_behaves_like 'accepts', 'non_integer', '_foo'
it_behaves_like 'accepts', 'non_integer', '@__foo__'
it_behaves_like 'accepts', 'non_integer', 'emparejó'
it_behaves_like 'accepts', 'non_integer', '_1'
it_behaves_like 'accepts integer symbols'
it 'registers an offense for snake case numbering in symbol' do
expect_offense(<<~RUBY)
:sym_1
^^^^^^ Use non_integer for symbol numbers.
RUBY
end
it 'registers an offense for normal case numbering in symbol' do
expect_offense(<<~RUBY)
:sym1
^^^^^ Use non_integer for symbol numbers.
RUBY
end
it 'registers an offense for snake case numbering in method parameter' do
expect_offense(<<~RUBY)
def method(arg_1); end
^^^^^ Use non_integer for variable numbers.
RUBY
end
it 'registers an offense for normal case numbering in method parameter' do
expect_offense(<<~RUBY)
def method(arg1); end
^^^^ Use non_integer for variable numbers.
RUBY
end
it 'registers an offense for snake case numbering in method camel case parameter' do
expect_offense(<<~RUBY)
def method(myArg_1); end
^^^^^^^ Use non_integer for variable numbers.
RUBY
end
it 'registers an offense for normal case numbering in method camel case parameter' do
expect_offense(<<~RUBY)
def method(myArg1); end
^^^^^^ Use non_integer for variable numbers.
RUBY
end
it 'registers an offense for snake case numbering in method name' do
expect_offense(<<~RUBY)
def method_1; end
^^^^^^^^ Use non_integer for method name numbers.
RUBY
end
it 'registers an offense for normal case numbering in method name' do
expect_offense(<<~RUBY)
def method1; end
^^^^^^^ Use non_integer for method name numbers.
RUBY
end
end
context 'when CheckMethodNames is false' do
let(:cop_config) { { 'CheckMethodNames' => false, 'EnforcedStyle' => 'normalcase' } }
it 'does not register an offense for snake case numbering in method name' do
expect_no_offenses('def method_1; end')
end
end
context 'when CheckSymbols is false' do
let(:cop_config) { { 'CheckSymbols' => false, 'EnforcedStyle' => 'normalcase' } }
it 'does not register an offense for snake case numbering in symbol' do
expect_no_offenses(':sym_1')
end
end
context 'when AllowedIdentifiers is set' do
let(:cop_config) do
{
'AllowedIdentifiers' => %w[capture3],
'CheckSymbols' => true,
'CheckMethodNames' => true,
'EnforcedStyle' => 'snake_case'
}
end
it 'does not register an offense for a local variable name that is allowed' do
expect_no_offenses(<<~RUBY)
capture3 = :foo
RUBY
end
it 'does not register an offense for an instance variable name that is allowed' do
expect_no_offenses(<<~RUBY)
@capture3 = :foo
RUBY
end
it 'does not register an offense for a class variable name that is allowed' do
expect_no_offenses(<<~RUBY)
@@capture3 = :foo
RUBY
end
it 'does not register an offense for a global variable name that is allowed' do
expect_no_offenses(<<~RUBY)
$capture3 = :foo
RUBY
end
it 'does not register an offense for a method name that is allowed' do
expect_no_offenses(<<~RUBY)
def capture3
end
RUBY
end
it 'does not register an offense for a symbol that is allowed' do
expect_no_offenses(':capture3')
end
end
context 'when AllowedPatterns is set' do
let(:cop_config) do
{
'AllowedIdentifiers' => [],
'AllowedPatterns' => [
'_v\d+\z',
'allow_me'
],
'CheckSymbols' => true,
'CheckMethodNames' => true,
'EnforcedStyle' => 'snake_case'
}
end
it 'registers an offense for a local variable name that does not match an allowed pattern' do
expect_offense(<<~RUBY)
foo_a1 = :foo
^^^^^^ Use snake_case for variable numbers.
RUBY
end
it 'does not register an offense for a local variable name that matches an allowed pattern' do
expect_no_offenses(<<~RUBY)
foo_v1 = :foo
foo_allow_me_a1 = :allowed
RUBY
end
it 'registers an offense for an instance variable name that does not match an allowed pattern' do
expect_offense(<<~RUBY)
@foo_a1 = :foo
^^^^^^^ Use snake_case for variable numbers.
RUBY
end
it 'does not register an offense for an instance variable name that matches an allowed pattern' do
expect_no_offenses(<<~RUBY)
@foo_v1 = :foo
@foo_allow_me_a1 = :allowed
RUBY
end
it 'registers an offense for a class variable name that does not match an allowed pattern' do
expect_offense(<<~RUBY)
@@foo_a1 = :foo
^^^^^^^^ Use snake_case for variable numbers.
RUBY
end
it 'does not register an offense for a class variable name that matches an allowed pattern' do
expect_no_offenses(<<~RUBY)
@@foo_v1 = :foo
@@foo_allow_me_a1 = :allowed
RUBY
end
it 'registers an offense for a global variable name that does not match an allowed pattern' do
expect_offense(<<~RUBY)
$foo_a1 = :foo
^^^^^^^ Use snake_case for variable numbers.
RUBY
end
it 'does not register an offense for a global variable name that matches an allowed pattern' do
expect_no_offenses(<<~RUBY)
$foo_v1 = :foo
$foo_allow_me_a1 = :allowed
RUBY
end
it 'registers an offense for a method name that does not match an allowed pattern' do
expect_offense(<<~RUBY)
def foo_a1
^^^^^^ Use snake_case for method name numbers.
end
RUBY
end
it 'does not register an offense for a method name that matches an allowed pattern' do
expect_no_offenses(<<~RUBY)
def foo_v1
end
def foo_allow_me_a1
end
RUBY
end
it 'registers an offense for a symbol that does not match an allowed pattern' do
expect_offense(<<~RUBY)
:foo_a1
^^^^^^^ Use snake_case for symbol numbers.
RUBY
end
it 'does not register an offense for a symbol that matches an allowed pattern' do
expect_no_offenses(':foo_v1')
expect_no_offenses(':foo_allow_me_a1')
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/naming/memoized_instance_variable_name_spec.rb | spec/rubocop/cop/naming/memoized_instance_variable_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::MemoizedInstanceVariableName, :config do
it 'does not register an offense when or-assignment-based memoization is used outside a method definition' do
expect_no_offenses(<<~RUBY)
@x ||= y
RUBY
end
context 'with default EnforcedStyleForLeadingUnderscores => disallowed' do
let(:cop_config) { { 'EnforcedStyleForLeadingUnderscores' => 'disallowed' } }
context 'when or-assignment-based memoization is used' do
context 'memoized variable does not match method name' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def x
@my_var ||= :foo
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
end
RUBY
expect_correction(<<~RUBY)
def x
@x ||= :foo
end
RUBY
end
end
context 'memoized variable does not match class method name' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.x
@my_var ||= :foo
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
end
RUBY
expect_correction(<<~RUBY)
def self.x
@x ||= :foo
end
RUBY
end
end
context 'memoized variable does not match method name during assignment' do
it 'registers an offense' do
expect_offense(<<~RUBY)
foo = def x
@y ||= :foo
^^ Memoized variable `@y` does not match method name `x`. Use `@x` instead.
end
RUBY
expect_correction(<<~RUBY)
foo = def x
@x ||= :foo
end
RUBY
end
end
context 'memoized variable does not match method name for block' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def x
@y ||= begin
^^ Memoized variable `@y` does not match method name `x`. Use `@x` instead.
:foo
end
end
RUBY
expect_correction(<<~RUBY)
def x
@x ||= begin
:foo
end
end
RUBY
end
end
context 'memoized variable after other code does not match method name' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def foo
helper_variable = something_we_need_to_calculate_foo
@bar ||= calculate_expensive_thing(helper_variable)
^^^^ Memoized variable `@bar` does not match method name `foo`. Use `@foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo
helper_variable = something_we_need_to_calculate_foo
@foo ||= calculate_expensive_thing(helper_variable)
end
RUBY
end
it 'registers an offense for a predicate method' do
expect_offense(<<~RUBY)
def foo?
helper_variable = something_we_need_to_calculate_foo
@bar ||= calculate_expensive_thing(helper_variable)
^^^^ Memoized variable `@bar` does not match method name `foo?`. Use `@foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo?
helper_variable = something_we_need_to_calculate_foo
@foo ||= calculate_expensive_thing(helper_variable)
end
RUBY
end
it 'registers an offense for a bang method' do
expect_offense(<<~RUBY)
def foo!
helper_variable = something_we_need_to_calculate_foo
@bar ||= calculate_expensive_thing(helper_variable)
^^^^ Memoized variable `@bar` does not match method name `foo!`. Use `@foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo!
helper_variable = something_we_need_to_calculate_foo
@foo ||= calculate_expensive_thing(helper_variable)
end
RUBY
end
it 'registers an offense for a assignment method' do
expect_offense(<<~RUBY)
def foo=(bar)
helper_variable = something_we_need_to_calculate(foo)
@bar ||= calculate_expensive_thing(helper_variable)
^^^^ Memoized variable `@bar` does not match method name `foo=`. Use `@foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo=(bar)
helper_variable = something_we_need_to_calculate(foo)
@foo ||= calculate_expensive_thing(helper_variable)
end
RUBY
end
end
context 'memoized variable matches method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def x
@x ||= :foo
end
RUBY
end
it 'does not register an offense when method has leading `_`' do
expect_no_offenses(<<~RUBY)
def _foo
@foo ||= :foo
end
RUBY
end
it 'does not register an offense with a leading `_` for both names' do
expect_no_offenses(<<~RUBY)
def _foo
@_foo ||= :foo
end
RUBY
end
context 'memoized variable matches method name during assignment' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
foo = def y
@y ||= :foo
end
RUBY
end
end
context 'memoized variable matches method name for block' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def z
@z ||= begin
:foo
end
end
RUBY
end
end
context 'non-memoized variable does not match method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def a
x ||= :foo
end
RUBY
end
end
context 'memoized variable matches predicate method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def a?
@a ||= :foo
end
RUBY
end
end
context 'memoized variable matches bang method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def a!
@a ||= :foo
end
RUBY
end
end
context 'code follows memoized variable assignment' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def a
@b ||= :foo
call_something_else
end
RUBY
end
context 'memoized variable after other code' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo
helper_variable = something_we_need_to_calculate_foo
@foo ||= calculate_expensive_thing(helper_variable)
end
RUBY
end
end
context 'instance variables in initialize methods' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def initialize
@files_with_offenses ||= {}
end
RUBY
end
end
context 'instance variables in `initialize_clone` method' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def initialize_clone(obj)
@files_with_offenses ||= {}
end
RUBY
end
end
context 'instance variables in `initialize_copy` method' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def initialize_copy(obj)
@files_with_offenses ||= {}
end
RUBY
end
end
context 'instance variables in `initialize_dup` method' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def initialize_dup(obj)
@files_with_offenses ||= {}
end
RUBY
end
end
end
end
context 'with dynamically defined methods' do
context 'when the variable name matches the method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
define_method(:values) do
@values ||= do_something
end
RUBY
end
end
context 'when the variable name does not match the method name' do
it 'registers an offense' do
expect_offense(<<~RUBY)
define_method(:values) do
@foo ||= do_something
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
end
RUBY
expect_correction(<<~RUBY)
define_method(:values) do
@values ||= do_something
end
RUBY
end
end
context 'when a method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
@values ||= do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
@foo ||= do_something
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
@values ||= do_something
end
end
RUBY
end
end
end
context 'when a singleton method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
@values ||= do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
@foo ||= do_something
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
@values ||= do_something
end
end
RUBY
end
end
end
end
end
context 'when defined?-based memoization is used' do
it 'registers an offense when memoized variable does not match method name' do
expect_offense(<<~RUBY)
def x
return @my_var if defined?(@my_var)
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
@my_var = false
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
end
RUBY
expect_correction(<<~RUBY)
def x
return @x if defined?(@x)
@x = false
end
RUBY
end
it 'registers an offense when memoized variable does not match class method name' do
expect_offense(<<~RUBY)
def self.x
return @my_var if defined?(@my_var)
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
@my_var = false
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
end
RUBY
expect_correction(<<~RUBY)
def self.x
return @x if defined?(@x)
@x = false
end
RUBY
end
context 'memoized variable matches method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def x
return @x if defined?(@x)
@x = false
end
RUBY
end
it 'does not register an offense when method has leading `_`' do
expect_no_offenses(<<~RUBY)
def _foo
return @foo if defined?(@foo)
@foo = false
end
RUBY
end
it 'does not register an offense with a leading `_` for both names' do
expect_no_offenses(<<~RUBY)
def _foo
return @_foo if defined?(@_foo)
@_foo = false
end
RUBY
end
context 'non-memoized variable does not match method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def a
return x if defined?(x)
x = 1
end
RUBY
end
end
it 'does not register an offense when memoized variable matches predicate method name' do
expect_no_offenses(<<~RUBY)
def a?
return @a if defined?(@a)
@a = false
end
RUBY
end
it 'does not register an offense when memoized variable matches bang method name' do
expect_no_offenses(<<~RUBY)
def a!
return @a if defined?(@a)
@a = false
end
RUBY
end
end
it 'does not register an offense when some code before defined' do
expect_no_offenses(<<~RUBY)
def x
do_something
return @x if defined?(@x)
@x = false
end
RUBY
end
it 'does not register an offense when some code after assignment' do
expect_no_offenses(<<~RUBY)
def x
return @x if defined?(@x)
@x = false
do_something
end
RUBY
end
it 'does not register an offense when there is no assignment' do
expect_no_offenses(<<~RUBY)
def x
return @x if defined?(@x)
end
RUBY
end
context 'with dynamically defined methods' do
context 'when the variable name matches the method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
define_method(:values) do
return @values if defined?(@values)
@values = do_something
end
RUBY
end
end
context 'when the variable name does not match the method name' do
it 'registers an offense' do
expect_offense(<<~RUBY)
define_method(:values) do
return @foo if defined?(@foo)
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
@foo = do_something
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
end
RUBY
expect_correction(<<~RUBY)
define_method(:values) do
return @values if defined?(@values)
@values = do_something
end
RUBY
end
end
context 'when a method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
return @values if defined?(@values)
@values = do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
return @foo if defined?(@foo)
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
@foo = do_something
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
return @values if defined?(@values)
@values = do_something
end
end
RUBY
end
end
end
context 'when a singleton method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
return @values if defined?(@values)
@values = do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
return @foo if defined?(@foo)
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
@foo = do_something
^^^^ Memoized variable `@foo` does not match method name `values`. Use `@values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
return @values if defined?(@values)
@values = do_something
end
end
RUBY
end
end
end
end
end
end
context 'EnforcedStyleForLeadingUnderscores: required' do
let(:cop_config) { { 'EnforcedStyleForLeadingUnderscores' => 'required' } }
context 'when or-assignment-based memoization is used' do
it 'registers an offense when names match but missing a leading _' do
expect_offense(<<~RUBY)
def foo
@foo ||= :foo
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo
@_foo ||= :foo
end
RUBY
end
it 'registers an offense when it has leading `_` but names do not match' do
expect_offense(<<~RUBY)
def foo
@_my_var ||= :foo
^^^^^^^^ Memoized variable `@_my_var` does not match method name `foo`. Use `@_foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo
@_foo ||= :foo
end
RUBY
end
it 'does not register an offense with a leading `_` for both names' do
expect_no_offenses(<<~RUBY)
def _foo
@_foo ||= :foo
end
RUBY
end
context 'with dynamically defined methods' do
context 'when the variable name matches the method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
define_method(:values) do
@_values ||= do_something
end
RUBY
end
end
context 'when the variable name does not match the method name' do
it 'registers an offense' do
expect_offense(<<~RUBY)
define_method(:values) do
@foo ||= do_something
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
end
RUBY
expect_correction(<<~RUBY)
define_method(:values) do
@_values ||= do_something
end
RUBY
end
end
context 'when a method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
@_values ||= do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
@foo ||= do_something
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
@_values ||= do_something
end
end
RUBY
end
end
end
context 'when a singleton method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
@_values ||= do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
@foo ||= do_something
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
@_values ||= do_something
end
end
RUBY
end
end
end
end
end
context 'when defined?-based memoization is used' do
it 'registers an offense when names match but missing a leading _' do
expect_offense(<<~RUBY)
def foo
return @foo if defined?(@foo)
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_foo` instead.
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_foo` instead.
@foo = false
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo
return @_foo if defined?(@_foo)
@_foo = false
end
RUBY
end
it 'registers an offense when it has leading `_` but names do not match' do
expect_offense(<<~RUBY)
def foo
return @_my_var if defined?(@_my_var)
^^^^^^^^ Memoized variable `@_my_var` does not match method name `foo`. Use `@_foo` instead.
^^^^^^^^ Memoized variable `@_my_var` does not match method name `foo`. Use `@_foo` instead.
@_my_var = false
^^^^^^^^ Memoized variable `@_my_var` does not match method name `foo`. Use `@_foo` instead.
end
RUBY
expect_correction(<<~RUBY)
def foo
return @_foo if defined?(@_foo)
@_foo = false
end
RUBY
end
it 'does not register an offense with a leading `_` for both names' do
expect_no_offenses(<<~RUBY)
def _foo
return @_foo if defined?(@_foo)
@_foo = false
end
RUBY
end
context 'with dynamically defined methods' do
context 'when the variable name matches the method name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
define_method(:values) do
return @_values if defined?(@_values)
@_values = do_something
end
RUBY
end
end
context 'when the variable name does not match the method name' do
it 'registers an offense' do
expect_offense(<<~RUBY)
define_method(:values) do
return @foo if defined?(@foo)
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
@foo = do_something
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
end
RUBY
expect_correction(<<~RUBY)
define_method(:values) do
return @_values if defined?(@_values)
@_values = do_something
end
RUBY
end
end
context 'when a method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
return @_values if defined?(@_values)
@_values = do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
return @foo if defined?(@foo)
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
@foo = do_something
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_method(:values) do
return @_values if defined?(@_values)
@_values = do_something
end
end
RUBY
end
end
end
context 'when a singleton method is defined inside a module callback' do
context 'when the method matches' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
return @_values if defined?(@_values)
@_values = do_something
end
end
RUBY
end
end
context 'when the method does not match' do
it 'registers an offense' do
expect_offense(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
return @foo if defined?(@foo)
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
@foo = do_something
^^^^ Memoized variable `@foo` does not start with `_`. Use `@_values` instead.
end
end
RUBY
expect_correction(<<~RUBY)
def self.inherited(klass)
klass.define_singleton_method(:values) do
return @_values if defined?(@_values)
@_values = do_something
end
end
RUBY
end
end
end
end
end
end
context 'EnforcedStyleForLeadingUnderscores: optional' do
let(:cop_config) { { 'EnforcedStyleForLeadingUnderscores' => 'optional' } }
context 'when or-assignment-based memoization is used' do
context 'memoized variable matches method name' do
it 'does not register an offense with a leading underscore' do
expect_no_offenses(<<~RUBY)
def x
@_x ||= :foo
end
RUBY
end
it 'does not register an offense without a leading underscore' do
expect_no_offenses(<<~RUBY)
def x
@x ||= :foo
end
RUBY
end
it 'does not register an offense with a leading `_` for both names' do
expect_no_offenses(<<~RUBY)
def _x
@_x ||= :foo
end
RUBY
end
it 'does not register an offense with a leading `_` for method name' do
expect_no_offenses(<<~RUBY)
def _x
@x ||= :foo
end
RUBY
end
end
context 'when defined?-based memoization is used' do
context 'memoized variable matches method name' do
it 'does not register an offense with a leading underscore' do
expect_no_offenses(<<~RUBY)
def x
return @_x if defined?(@_x)
@_x = false
end
RUBY
end
it 'does not register an offense without a leading underscore' do
expect_no_offenses(<<~RUBY)
def x
return @x if defined?(@x)
@x = false
end
RUBY
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/naming/heredoc_delimiter_naming_spec.rb | spec/rubocop/cop/naming/heredoc_delimiter_naming_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::HeredocDelimiterNaming, :config do
let(:cop_config) { { 'ForbiddenDelimiters' => %w[END] } }
context 'with an interpolated heredoc' do
it 'registers an offense with a non-meaningful delimiter' do
expect_offense(<<~RUBY)
<<-END
foo
END
^^^ Use meaningful heredoc delimiters.
RUBY
end
it 'does not register an offense with a meaningful delimiter' do
expect_no_offenses(<<~RUBY)
<<-SQL
foo
SQL
RUBY
end
end
context 'with a non-interpolated heredoc' do
context 'when using single quoted delimiters' do
it 'registers an offense with a non-meaningful delimiter' do
expect_offense(<<~RUBY)
<<-'END'
foo
END
^^^ Use meaningful heredoc delimiters.
RUBY
end
it 'does not register an offense with a meaningful delimiter' do
expect_no_offenses(<<~RUBY)
<<-'SQL'
foo
SQL
RUBY
end
end
context 'when using double quoted delimiters' do
it 'registers an offense with a non-meaningful delimiter' do
expect_offense(<<~RUBY)
<<-"END"
foo
END
^^^ Use meaningful heredoc delimiters.
RUBY
end
it 'does not register an offense with a meaningful delimiter' do
expect_no_offenses(<<~RUBY)
<<-'SQL'
foo
SQL
RUBY
end
end
context 'when using back tick delimiters' do
it 'registers an offense with a non-meaningful delimiter' do
expect_offense(<<~RUBY)
<<-`END`
foo
END
^^^ Use meaningful heredoc delimiters.
RUBY
end
it 'does not register an offense with a meaningful delimiter' do
expect_no_offenses(<<~RUBY)
<<-`SQL`
foo
SQL
RUBY
end
end
context 'when using non-word delimiters' do
it 'registers an offense' do
expect_offense(<<~RUBY)
<<-'+'
foo
+
^ Use meaningful heredoc delimiters.
RUBY
end
end
# FIXME: `<<~''` is a syntax error in Ruby. This test was added because Parser gem can parse it,
# but this will be removed after https://github.com/whitequark/parser/issues/996 is resolved.
context 'when using blank heredoc delimiters', unsupported_on: :prism do
it 'registers an offense with a non-meaningful delimiter' do
expect_offense(<<~RUBY)
<<~''
^^^^^ Use meaningful heredoc delimiters.
RUBY
end
end
end
context 'with a squiggly heredoc' do
it 'registers an offense with a non-meaningful delimiter' do
expect_offense(<<~RUBY)
<<~END
foo
END
^^^ Use meaningful heredoc delimiters.
RUBY
end
it 'does not register an offense with a meaningful delimiter' do
expect_no_offenses(<<~RUBY)
<<~SQL
foo
SQL
RUBY
end
end
context 'with a naked heredoc' do
it 'registers an offense with a non-meaningful delimiter' do
expect_offense(<<~RUBY)
<<END
foo
END
^^^ Use meaningful heredoc delimiters.
RUBY
end
it 'does not register an offense with a meaningful delimiter' do
expect_no_offenses(<<~RUBY)
<<SQL
foo
SQL
RUBY
end
end
context 'when the delimiter contains non-letter characters' do
it 'does not register an offense when delimiter contains an underscore' do
expect_no_offenses(<<~RUBY)
<<-SQL_CODE
foo
SQL_CODE
RUBY
end
it 'does not register an offense when delimiter contains a number' do
expect_no_offenses(<<~RUBY)
<<-BASE64
foo
BASE64
RUBY
end
end
context 'with multiple heredocs starting on the same line' do
it 'registers an offense with a leading non-meaningful delimiter' do
expect_offense(<<~RUBY)
foo(<<-END, <<-SQL)
foo
END
^^^ Use meaningful heredoc delimiters.
bar
SQL
RUBY
end
it 'registers an offense with a trailing non-meaningful delimiter' do
expect_offense(<<~RUBY)
foo(<<-SQL, <<-END)
foo
SQL
bar
END
^^^ Use meaningful heredoc delimiters.
RUBY
end
it 'does not register an offense with meaningful delimiters' do
expect_no_offenses(<<~RUBY)
foo(<<-SQL, <<-JS)
foo
SQL
bar
JS
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/naming/binary_operator_parameter_name_spec.rb | spec/rubocop/cop/naming/binary_operator_parameter_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::BinaryOperatorParameterName, :config do
it 'registers an offense and corrects for `#+` when argument is not named other' do
expect_offense(<<~RUBY)
def +(foo); end
^^^ When defining the `+` operator, name its argument `other`.
RUBY
expect_correction(<<~RUBY)
def +(other); end
RUBY
end
it 'registers an offense and corrects for `#eql?` when argument is not named other' do
expect_offense(<<~RUBY)
def eql?(foo); end
^^^ When defining the `eql?` operator, name its argument `other`.
RUBY
expect_correction(<<~RUBY)
def eql?(other); end
RUBY
end
it 'registers an offense and corrects for `#equal?` when argument is not named other' do
expect_offense(<<~RUBY)
def equal?(foo); end
^^^ When defining the `equal?` operator, name its argument `other`.
RUBY
expect_correction(<<~RUBY)
def equal?(other); end
RUBY
end
it 'works properly even if the argument not surrounded with braces' do
expect_offense(<<~RUBY)
def + another
^^^^^^^ When defining the `+` operator, name its argument `other`.
another
end
RUBY
expect_correction(<<~RUBY)
def + other
other
end
RUBY
end
it 'registers an offense and corrects when argument is referenced in method body' do
expect_offense(<<~RUBY)
def +(arg)
^^^ When defining the `+` operator, name its argument `other`.
lvar = 'lvar'
do_something(arg, lvar)
end
RUBY
expect_correction(<<~RUBY)
def +(other)
lvar = 'lvar'
do_something(other, lvar)
end
RUBY
end
it 'registers an offense and corrects when assigned to argument in method body' do
expect_offense(<<~RUBY)
def +(arg)
^^^ When defining the `+` operator, name its argument `other`.
arg = do_something
end
RUBY
expect_correction(<<~RUBY)
def +(other)
other = do_something
end
RUBY
end
it 'does not register an offense for arg named other' do
expect_no_offenses(<<~RUBY)
def +(other)
other
end
RUBY
end
it 'does not register an offense for arg named _other' do
expect_no_offenses(<<~RUBY)
def <=>(_other)
0
end
RUBY
end
it 'does not register an offense for []' do
expect_no_offenses(<<~RUBY)
def [](index)
other
end
RUBY
end
it 'does not register an offense for []=' do
expect_no_offenses(<<~RUBY)
def []=(index, value)
other
end
RUBY
end
it 'does not register an offense for <<' do
expect_no_offenses(<<~RUBY)
def <<(cop)
other
end
RUBY
end
it 'does not register an offense for ===' do
expect_no_offenses(<<~RUBY)
def ===(string)
string
end
RUBY
end
it 'does not register an offense for multibyte character method name' do
expect_no_offenses(<<~RUBY)
def do_something(string)
string
end
RUBY
end
it 'does not register an offense for non binary operators' do
expect_no_offenses(<<~RUBY)
def -@; end
# This + is not a unary operator. It can only be
# called with dot notation.
def +; end
def *(a, b); end # Quite strange, but legal ruby.
def `(cmd); end
RUBY
end
it 'does not register an offense for the match operator' do
expect_no_offenses(<<~RUBY)
def =~(regexp); 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/naming/accessor_method_name_spec.rb | spec/rubocop/cop/naming/accessor_method_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::AccessorMethodName, :config do
it 'registers an offense for method get_something with no args' do
expect_offense(<<~RUBY)
def get_something
^^^^^^^^^^^^^ Do not prefix reader method names with `get_`.
# ...
end
RUBY
end
it 'registers an offense for singleton method get_something with no args' do
expect_offense(<<~RUBY)
def self.get_something
^^^^^^^^^^^^^ Do not prefix reader method names with `get_`.
# ...
end
RUBY
end
it 'accepts method get_something with args' do
expect_no_offenses(<<~RUBY)
def get_something(arg)
# ...
end
RUBY
end
it 'accepts singleton method get_something with args' do
expect_no_offenses(<<~RUBY)
def self.get_something(arg)
# ...
end
RUBY
end
it 'registers an offense for method set_something with one arg' do
expect_offense(<<~RUBY)
def set_something(arg)
^^^^^^^^^^^^^ Do not prefix writer method names with `set_`.
# ...
end
RUBY
end
it 'accepts method set_something with optarg' do
expect_no_offenses(<<~RUBY)
def set_something(arg = :default)
# ...
end
RUBY
end
it 'accepts method set_something with restarg' do
expect_no_offenses(<<~RUBY)
def set_something(*args)
# ...
end
RUBY
end
it 'accepts method set_something with kwoptarg' do
expect_no_offenses(<<~RUBY)
def set_something(k: v)
# ...
end
RUBY
end
it 'accepts method set_something with kwarg' do
expect_no_offenses(<<~RUBY)
def set_something(k:)
# ...
end
RUBY
end
it 'accepts method set_something with kwrestarg' do
expect_no_offenses(<<~RUBY)
def set_something(**options)
# ...
end
RUBY
end
it 'accepts method set_something with blockarg' do
expect_no_offenses(<<~RUBY)
def set_something(&block)
# ...
end
RUBY
end
context '>= Ruby 2.7', :ruby27 do
it 'accepts method set_something with arguments forwarding' do
expect_no_offenses(<<~RUBY)
def set_something(...)
# ...
end
RUBY
end
end
it 'registers an offense for singleton method set_something with one args' do
expect_offense(<<~RUBY)
def self.set_something(arg)
^^^^^^^^^^^^^ Do not prefix writer method names with `set_`.
# ...
end
RUBY
end
it 'accepts method set_something with no args' do
expect_no_offenses(<<~RUBY)
def set_something
# ...
end
RUBY
end
it 'accepts singleton method set_something with no args' do
expect_no_offenses(<<~RUBY)
def self.set_something
# ...
end
RUBY
end
it 'accepts method set_something with two args' do
expect_no_offenses(<<~RUBY)
def set_something(arg1, arg2)
# ...
end
RUBY
end
it 'accepts singleton method set_something with two args' do
expect_no_offenses(<<~RUBY)
def self.get_something(arg1, arg2)
# ...
end
RUBY
end
it 'does not register an offense for no args method name starts with `get_` and ends with `!`' do
expect_no_offenses(<<~RUBY)
def get_attribute!
end
RUBY
end
it 'does not register an offense for no args method name starts with `get_` and ends with `?`' do
expect_no_offenses(<<~RUBY)
def get_attribute?
end
RUBY
end
it 'does not register an offense for no args method name starts with `get_` and ends with `=`' do
expect_no_offenses(<<~RUBY)
def get_attribute=
end
RUBY
end
it 'does not register an offense for one arg method name starts with `set_` and ends with `!`' do
expect_no_offenses(<<~RUBY)
def set_attribute!(attribute)
end
RUBY
end
it 'does not register an offense for one arg method name starts with `set_` and ends with `?`' do
expect_no_offenses(<<~RUBY)
def set_attribute?(attribute)
end
RUBY
end
it 'does not register an offense for one arg method name starts with `set_` and ends with `=`' do
expect_no_offenses(<<~RUBY)
def set_attribute=(attribute)
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/naming/class_and_module_camel_case_spec.rb | spec/rubocop/cop/naming/class_and_module_camel_case_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::ClassAndModuleCamelCase, :config do
it 'registers an offense for underscore in class and module name' do
expect_offense(<<~RUBY)
class My_Class
^^^^^^^^ Use CamelCase for classes and modules.
end
module My_Module
^^^^^^^^^ Use CamelCase for classes and modules.
end
RUBY
end
it 'is not fooled by qualified names' do
expect_offense(<<~RUBY)
class Top::My_Class
^^^^^^^^^^^^^ Use CamelCase for classes and modules.
end
module My_Module::Ala
^^^^^^^^^^^^^^ Use CamelCase for classes and modules.
end
RUBY
end
it 'accepts CamelCase names' do
expect_no_offenses(<<~RUBY)
class MyClass
end
module Mine
end
RUBY
end
it 'allows module_parent method' do
expect_no_offenses(<<~RUBY)
class module_parent::MyClass
end
RUBY
end
context 'custom allowed names' do
let(:cop_config) { { 'AllowedNames' => %w[getter_class setter_class] } }
it 'does not register offense for multiple allowed names' do
expect_no_offenses(<<~RUBY)
class getter_class::MyClass
end
class setter_class::MyClass
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/naming/predicate_method_spec.rb | spec/rubocop/cop/naming/predicate_method_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::PredicateMethod, :config do
let(:allowed_methods) { [] }
let(:allowed_patterns) { [] }
let(:allow_bang_methods) { false }
let(:wayward_predicates) { [] }
let(:cop_config) do
{
'Mode' => mode,
'AllowedMethods' => allowed_methods,
'AllowedPatterns' => allowed_patterns,
'AllowBangMethods' => allow_bang_methods,
'WaywardPredicates' => wayward_predicates
}
end
shared_examples 'predicate' do |return_statement, implicit: true, explicit: true|
if implicit
context 'implicit return' do
it 'registers an offense when the method name does not end with `?`' do
expect_offense(<<~RUBY)
def foo
^^^ Predicate method names should end with `?`.
#{return_statement}
end
RUBY
end
it 'does not register an offense when the method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def foo?
#{return_statement}
end
RUBY
end
it 'registers an offense when a `defs` method name does not end with `?`' do
expect_offense(<<~RUBY)
def self.foo
^^^ Predicate method names should end with `?`.
#{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo?
#{return_statement}
end
RUBY
end
end
end
if explicit
context 'explicit return' do
it 'registers an offense when the method name does not end with `?`' do
expect_offense(<<~RUBY)
def foo
^^^ Predicate method names should end with `?`.
return #{return_statement}
end
RUBY
end
it 'does not register an offense when the method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def foo?
return #{return_statement}
end
RUBY
end
it 'registers an offense when a `defs` method name does not end with `?`' do
expect_offense(<<~RUBY)
def self.foo
^^^ Predicate method names should end with `?`.
return #{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo?
return #{return_statement}
end
RUBY
end
end
end
end
shared_examples 'non-predicate' do |return_statement, implicit: true, explicit: true|
if implicit
context 'implicit return' do
it 'registers an offense when the method name ends with `?`' do
expect_offense(<<~RUBY)
def foo?
^^^^ Non-predicate method names should not end with `?`.
#{return_statement}
end
RUBY
end
it 'does not register an offense when the method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def foo
#{return_statement}
end
RUBY
end
it 'registers an offense when a `defs` method name ends with `?`' do
expect_offense(<<~RUBY)
def self.foo?
^^^^ Non-predicate method names should not end with `?`.
#{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo
#{return_statement}
end
RUBY
end
end
end
if explicit
context 'explicit return' do
it 'registers an offense when the method name ends with `?`' do
expect_offense(<<~RUBY)
def foo?
^^^^ Non-predicate method names should not end with `?`.
return #{return_statement}
end
RUBY
end
it 'does not register an offense when the method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def foo
return #{return_statement}
end
RUBY
end
it 'registers an offense when a `defs` method name ends with `?`' do
expect_offense(<<~RUBY)
def self.foo?
^^^^ Non-predicate method names should not end with `?`.
return #{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo
return #{return_statement}
end
RUBY
end
end
end
end
shared_examples 'acceptable' do |return_statement, implicit: true, explicit: true|
if implicit
context 'implicit return' do
it 'does not register an offense when the method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def foo?
#{return_statement}
end
RUBY
end
it 'does not register an offense when the method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def foo
#{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo?
#{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo
#{return_statement}
end
RUBY
end
end
end
if explicit
context 'explicit return' do
it 'does not register an offense when the method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def foo?
return #{return_statement}
end
RUBY
end
it 'does not register an offense when the method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def foo
return #{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo?
return #{return_statement}
end
RUBY
end
it 'does not register an offense when a `defs` method name does not end with `?`' do
expect_no_offenses(<<~RUBY)
def self.foo
return #{return_statement}
end
RUBY
end
end
end
end
shared_examples 'common functionality' do
it 'does not register an offense for a `def` without a body' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
it 'does not register an offense for a `defs` without a body' do
expect_no_offenses(<<~RUBY)
def self.foo
end
RUBY
end
it 'does not register an offense for a `def` with empty parentheses body' do
expect_no_offenses(<<~RUBY)
def foo
()
end
RUBY
end
it 'does not register an offense for a `defs` with empty parentheses body' do
expect_no_offenses(<<~RUBY)
def self.foo
()
end
RUBY
end
it 'does not register an offense for an `in` pattern with empty parentheses body' do
expect_no_offenses(<<~RUBY)
def foo
case expr
in pattern
()
end
end
RUBY
end
context 'bare return' do
it_behaves_like 'non-predicate', '', implicit: false
it 'does not register an offense for a method that has a bare return and an implicit return value' do
expect_no_offenses(<<~RUBY)
def foo
return if bar
false
end
RUBY
end
end
context 'methods returning comparisons' do
%i[== === != <= >= > <].each do |method|
context "when returning a `#{method}` comparison" do
it_behaves_like 'predicate', "bar #{method} baz"
end
end
context 'compound comparisons' do
it_behaves_like 'predicate', 'a > b && c < d'
it_behaves_like 'predicate', 'a > b && c < d && e != f'
it_behaves_like 'predicate', 'a > b || c < d'
it_behaves_like 'predicate', 'a > b || c < d || e != f'
it_behaves_like 'predicate', 'a > b && c < d || e != f'
end
end
context 'methods returning negations' do
['5', 'true', 'false', 'nil', '[]', 'a', 'a?', '(a == b)'].each do |value|
it_behaves_like 'predicate', "!#{value}"
it_behaves_like 'predicate', "(not #{value})"
end
end
context 'methods returning boolean literals' do
it_behaves_like 'predicate', 'true'
it_behaves_like 'predicate', 'false'
end
context 'methods returning non-boolean literals' do
it_behaves_like 'non-predicate', 'nil'
it_behaves_like 'non-predicate', '5'
it_behaves_like 'non-predicate', '5.0'
it_behaves_like 'non-predicate', '5r'
it_behaves_like 'non-predicate', '5i'
it_behaves_like 'non-predicate', '"string"'
it_behaves_like 'non-predicate', '"#{string}"'
it_behaves_like 'non-predicate', '`string`'
it_behaves_like 'non-predicate', ':sym'
it_behaves_like 'non-predicate', ':"#{sym}"'
it_behaves_like 'non-predicate', '[]'
it_behaves_like 'non-predicate', '{}'
it_behaves_like 'non-predicate', '/regexp/'
it_behaves_like 'non-predicate', '(1..2)'
it_behaves_like 'non-predicate', '(1...2)'
end
context 'conditionals' do
it_behaves_like 'predicate', <<~RUBY, explicit: false
if x
true
elsif y
true
else
false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
if x
return true
elsif y
return true
else
return false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
unless x
true
else
false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
unless x
return true
else
return false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
case x
when y
true
when z
true
else
false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
case x
when y
return true
when z
return true
else
return false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
case x
in y then true
else false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
case x
in y then return true
else return false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
while x
false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
while x
return false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
until x
false
end
RUBY
it_behaves_like 'predicate', <<~RUBY, explicit: false
until x
return false
end
RUBY
context 'conditional containing compound comparison' do
it_behaves_like 'predicate', <<~RUBY, explicit: false
if x
a > b && c < d
else
false
end
RUBY
end
it_behaves_like 'acceptable', <<~RUBY, explicit: false
if foo?
return bar
else
return baz
end
RUBY
it_behaves_like 'acceptable', <<~RUBY, explicit: false
if x
bar
else
baz
end
RUBY
end
context 'super' do
it_behaves_like 'predicate', 'super == bar'
it_behaves_like 'acceptable', 'super'
it_behaves_like 'acceptable', 'super()'
it_behaves_like 'acceptable', 'super(var)'
end
context 'method calls' do
it_behaves_like 'acceptable', 'bar'
it_behaves_like 'acceptable', 'bar()'
it_behaves_like 'acceptable', 'bar(baz)'
end
context 'methods returning other predicates' do
it_behaves_like 'predicate', 'bar?'
it_behaves_like 'predicate', 'bar?()'
it_behaves_like 'predicate', 'bar?(baz)'
it_behaves_like 'predicate', 'bar.baz?'
it_behaves_like 'predicate', <<~RUBY, explicit: false
if bar
baz?
else
false
end
RUBY
end
context 'variables' do
it_behaves_like 'acceptable', 'bar = x; bar'
it_behaves_like 'acceptable', '@bar'
it_behaves_like 'acceptable', '@@bar'
it_behaves_like 'acceptable', '$bar'
end
context 'multiple return' do
it_behaves_like 'non-predicate', '1, 2', implicit: false
it_behaves_like 'non-predicate', '[1, 2]'
end
context '`initialize` method' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def initialize
foo?
end
RUBY
end
end
context 'operator methods' do
it 'does not register an offense if it would otherwise be treated as a predicate' do
expect_no_offenses(<<~RUBY)
def ==(other)
hash == other.hash
end
RUBY
end
end
context 'endless methods', :ruby30 do
it 'registers an offense for predicates without a `?`' do
expect_offense(<<~RUBY)
def foo = true
^^^ Predicate method names should end with `?`.
RUBY
end
it 'registers an offense for non-predicates with a `?`' do
expect_offense(<<~RUBY)
def foo? = 5
^^^^ Non-predicate method names should not end with `?`.
RUBY
end
end
context 'with AllowedMethods' do
let(:allowed_methods) { %w[on_defined?] }
it 'does not register an offense for an allowed method name' do
expect_no_offenses(<<~RUBY)
def on_defined?(node)
add_offense(node)
end
RUBY
end
end
context 'with AllowedPatterns' do
let(:allowed_patterns) { %w[\Afoo] }
it 'does not register an offense for a method name that matches the pattern' do
expect_no_offenses(<<~RUBY)
def foo?
'foo'
end
RUBY
end
it 'registers an offense for a method name that does not match the pattern' do
expect_offense(<<~RUBY)
def barfoo?
^^^^^^^ Non-predicate method names should not end with `?`.
'bar'
end
RUBY
end
end
context 'with AllowBangMethods: true' do
let(:allow_bang_methods) { true }
it 'does not register an offense for a bang method that returns a boolean' do
expect_no_offenses(<<~RUBY)
def save!
true
end
RUBY
end
end
context 'with AllowBangMethods: false' do
let(:allow_bang_methods) { false }
it 'registers an offense for a bang method that returns a boolean' do
expect_offense(<<~RUBY)
def save!
^^^^^ Predicate method names should end with `?`.
true
end
RUBY
end
end
context 'with WaywardPredicates' do
let(:wayward_predicates) { %w[nonzero?] }
it_behaves_like 'acceptable', 'nonzero?'
end
end
context 'with Mode: conservative' do
let(:mode) { :conservative }
it_behaves_like 'common functionality'
context 'methods returning mixed values' do
context 'when the implicit return is boolean' do
it 'does not register an offense when the method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def foo?
return 5 if bar?
true
end
RUBY
end
end
context 'when the implicit return is not boolean' do
it 'does not register an offense when the method name ends with `?`' do
expect_no_offenses(<<~RUBY)
def foo?
return true if bar?
5
end
RUBY
end
end
end
context 'conditionals' do
it_behaves_like 'acceptable', <<~RUBY, explicit: false
if bar?
baz
else
nil
end
RUBY
end
context 'conditionals with empty branches' do
it_behaves_like 'acceptable', <<~RUBY, explicit: false
if x
else
false
end
RUBY
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
while x
end
RUBY
end
context 'conditionals without else' do
it_behaves_like 'acceptable', <<~RUBY, explicit: false
true if x
RUBY
it_behaves_like 'acceptable', <<~RUBY, explicit: false
if x
true
end
RUBY
it_behaves_like 'acceptable', <<~RUBY, explicit: false
case x
when y then true
end
RUBY
it_behaves_like 'acceptable', <<~RUBY, explicit: false
case x
in y then true
end
RUBY
end
context 'super' do
it_behaves_like 'acceptable', <<~RUBY, explicit: false
return if something
super
RUBY
it_behaves_like 'acceptable', <<~RUBY, explicit: false
return if something
super()
RUBY
end
context 'method calls' do
it_behaves_like 'acceptable', <<~RUBY, explicit: false
return if something
true
RUBY
it_behaves_like 'acceptable', <<~RUBY, explicit: false
return if something
bar?
RUBY
end
end
context 'with Mode: aggressive' do
let(:mode) { :aggressive }
it_behaves_like 'common functionality'
context 'when the implicit return is boolean' do
it 'registers an offense when the method name ends with `?`' do
expect_offense(<<~RUBY)
def foo?
^^^^ Non-predicate method names should not end with `?`.
return 5 if bar?
true
end
RUBY
end
end
context 'when the implicit return is not boolean' do
it 'registers an offense when the method name ends with `?`' do
expect_offense(<<~RUBY)
def foo?
^^^^ Non-predicate method names should not end with `?`.
return true if bar?
5
end
RUBY
end
end
context 'conditionals' do
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
if bar?
baz
else
nil
end
RUBY
end
context 'conditionals with empty branches' do
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
if x
else
false
end
RUBY
end
context 'conditionals without else' do
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
true if x
RUBY
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
if x
true
end
RUBY
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
case x
when y then true
end
RUBY
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
case x
in y then true
end
RUBY
end
context 'mixed comparisons' do
it_behaves_like 'non-predicate', 'a > b && "yes"'
end
context 'super' do
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
return if something
super
RUBY
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
return if something
super()
RUBY
end
context 'method calls' do
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
return if something
true
RUBY
it_behaves_like 'non-predicate', <<~RUBY, explicit: false
return if something
bar?
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/naming/block_forwarding_spec.rb | spec/rubocop/cop/naming/block_forwarding_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::BlockForwarding, :config do
context 'when `EnforcedStyle: anonymous' do
let(:cop_config) { { 'EnforcedStyle' => 'anonymous' } }
context 'Ruby >= 3.1', :ruby31 do
it 'registers and corrects an offense when using explicit block forwarding' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
bar(&block)
^^^^^^ Use anonymous block forwarding.
baz(qux, &block)
^^^^^^ Use anonymous block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
bar(&)
baz(qux, &)
end
RUBY
end
it 'registers and corrects an offense when using explicit block forwarding in singleton method' do
expect_offense(<<~RUBY)
def self.foo(&block)
^^^^^^ Use anonymous block forwarding.
self.bar(&block)
^^^^^^ Use anonymous block forwarding.
self.baz(qux, &block)
^^^^^^ Use anonymous block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def self.foo(&)
self.bar(&)
self.baz(qux, &)
end
RUBY
end
it 'registers and corrects an offense when using symbol proc argument in method body' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
bar(&:do_something)
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
bar(&:do_something)
end
RUBY
end
it 'registers and corrects an offense when using `yield` in method body' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
yield
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
yield
end
RUBY
end
it 'registers and corrects an offense when using explicit block forwarding without method body' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
end
RUBY
end
it 'registers and corrects an offense when using explicit block forwarding without method definition parentheses' do
expect_offense(<<~RUBY)
def foo arg, &block
^^^^^^ Use anonymous block forwarding.
bar &block
^^^^^^ Use anonymous block forwarding.
baz qux, &block
^^^^^^ Use anonymous block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(arg, &)
bar(&)
baz(qux, &)
end
RUBY
end
it 'registers and corrects an only explicit block forwarding when using multiple proc arguments' do
expect_offense(<<~RUBY)
def foo(bar, &block)
^^^^^^ Use anonymous block forwarding.
delegator.foo(&bar).each(&block)
^^^^^^ Use anonymous block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(bar, &)
delegator.foo(&bar).each(&)
end
RUBY
end
it 'does not register an offense when using anonymous block forwarding' do
expect_no_offenses(<<~RUBY)
def foo(&)
bar(&)
end
RUBY
end
it 'does not register an offense when using anonymous block forwarding without method body' do
expect_no_offenses(<<~RUBY)
def foo(&)
end
RUBY
end
it 'does not register an offense when using block argument as a variable' do
expect_no_offenses(<<~RUBY)
def foo(&block)
bar(&block) if block
end
def foo(&block)
block.call
end
RUBY
end
it 'does not register an offense when method just returns the block argument' do
expect_no_offenses(<<~RUBY)
def foo(&block)
block
end
RUBY
end
it 'does not register an offense when defining without block argument method' do
expect_no_offenses(<<~RUBY)
def foo(arg1, arg2)
end
RUBY
end
it 'does not register an offense when defining kwarg with block args method' do
# Prevents the following syntax error:
#
# $ ruby -cve 'def foo(k:, &); bar(&); end'
# ruby 3.1.0dev (2021-12-05T10:23:42Z master 19f037e452) [x86_64-darwin19]
# -e:1: no anonymous block parameter
#
expect_no_offenses(<<~RUBY)
def foo(k:, &block)
bar(&block)
end
RUBY
end
it 'does not register an offense when defining kwoptarg with block args method' do
# Prevents the following syntax error:
#
# $ ruby -cve 'def foo(k: v, &); bar(&); end'
# ruby 3.1.0dev (2021-12-05T10:23:42Z master 19f037e452) [x86_64-darwin19]
# -e:1: no anonymous block parameter
#
expect_no_offenses(<<~RUBY)
def foo(k: v, &block)
bar(&block)
end
RUBY
end
# Ruby 3.3.0 had a bug where accessing an anonymous block argument inside of a block itself
# was a syntax error: https://bugs.ruby-lang.org/issues/20090
context 'when accessing the block inside of a block' do
it 'does not register an offense when using explicit block forwarding in block method' do
expect_no_offenses(<<~RUBY)
def foo(&block)
block_method do
bar(&block)
end
end
RUBY
end
it 'does not register an offense when using explicit block forwarding in numbered block method' do
expect_no_offenses(<<~RUBY)
def foo(&block)
block_method do
bar(&block)
baz(_1)
end
end
RUBY
end
it 'does not register an offense when using explicit block forwarding in block method and after' do
expect_no_offenses(<<~RUBY)
def foo(&block)
block_method do
bar(&block)
end
baz(&block)
end
RUBY
end
it 'does not register an offense when using explicit block forwarding in block method and before' do
expect_no_offenses(<<~RUBY)
def foo(&block)
bar(&block)
block_method do
baz(&block)
end
end
RUBY
end
end
it 'does not register an offense when defining no arguments method' do
expect_no_offenses(<<~RUBY)
def foo
end
RUBY
end
it 'does not register an offense when assigning the block arg' do
expect_no_offenses(<<~RUBY)
def example(&block)
block ||= -> { :foo }
bar(&block)
end
def example(&block)
block = proc {} unless block_given?
bar(&block)
end
RUBY
end
end
context 'Ruby >= 3.4', :ruby34 do
it 'registers an offense when using explicit block forwarding in block method' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
block_method do
bar(&block)
^^^^^^ Use anonymous block forwarding.
end
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
block_method do
bar(&)
end
end
RUBY
end
it 'registers an offense when using explicit block forwarding in numbered block method' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
block_method do
bar(&block)
^^^^^^ Use anonymous block forwarding.
baz(_1)
end
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
block_method do
bar(&)
baz(_1)
end
end
RUBY
end
it 'registers an offense when using explicit block forwarding in block method and after' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
block_method do
bar(&block)
^^^^^^ Use anonymous block forwarding.
end
baz(&block)
^^^^^^ Use anonymous block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
block_method do
bar(&)
end
baz(&)
end
RUBY
end
it 'registers an offense when using explicit block forwarding in block method and before' do
expect_offense(<<~RUBY)
def foo(&block)
^^^^^^ Use anonymous block forwarding.
bar(&block)
^^^^^^ Use anonymous block forwarding.
block_method do
baz(&block)
^^^^^^ Use anonymous block forwarding.
end
end
RUBY
expect_correction(<<~RUBY)
def foo(&)
bar(&)
block_method do
baz(&)
end
end
RUBY
end
end
context 'Ruby < 3.0', :ruby30, unsupported_on: :prism do
it 'does not register an offense when not using anonymous block forwarding' do
expect_no_offenses(<<~RUBY)
def foo(&block)
bar(&block)
end
RUBY
end
end
end
context 'when `EnforcedStyle: explicit' do
let(:cop_config) do
{ 'EnforcedStyle' => 'explicit', 'BlockForwardingName' => block_forwarding_name }
end
let(:block_forwarding_name) { 'block' }
context 'Ruby >= 3.1', :ruby31 do
it 'registers and corrects an offense when using anonymous block forwarding' do
expect_offense(<<~RUBY)
def foo(&)
^ Use explicit block forwarding.
bar(&)
^ Use explicit block forwarding.
baz(qux, &)
^ Use explicit block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(&block)
bar(&block)
baz(qux, &block)
end
RUBY
end
it 'registers and corrects an offense when using anonymous block forwarding in singleton method' do
expect_offense(<<~RUBY)
def self.foo(&)
^ Use explicit block forwarding.
self.bar(&)
^ Use explicit block forwarding.
self.baz(qux, &)
^ Use explicit block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def self.foo(&block)
self.bar(&block)
self.baz(qux, &block)
end
RUBY
end
it 'registers and corrects an offense when using symbol proc argument in method body' do
expect_offense(<<~RUBY)
def foo(&)
^ Use explicit block forwarding.
bar(&:do_something)
end
RUBY
expect_correction(<<~RUBY)
def foo(&block)
bar(&:do_something)
end
RUBY
end
it 'registers and corrects an offense when using `yield` in method body' do
expect_offense(<<~RUBY)
def foo(&)
^ Use explicit block forwarding.
yield
end
RUBY
expect_correction(<<~RUBY)
def foo(&block)
yield
end
RUBY
end
it 'registers and corrects and corrects an offense when using anonymous block forwarding without method body' do
expect_offense(<<~RUBY)
def foo(&)
^ Use explicit block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(&block)
end
RUBY
end
it 'does not register an offense when using explicit block forwarding' do
expect_no_offenses(<<~RUBY)
def foo(&block)
bar(&block)
end
RUBY
end
it 'does not register an offense when using explicit block forwarding without method body' do
expect_no_offenses(<<~RUBY)
def foo(&block)
end
RUBY
end
it 'does not register an offense when defining without block argument method' do
expect_no_offenses(<<~RUBY)
def foo(arg1, arg2)
end
RUBY
end
it 'does not register an offense when assigning the block arg' do
expect_no_offenses(<<~RUBY)
def example(&block)
block ||= -> { :foo }
bar(&block)
end
RUBY
end
context 'when `BlockForwardingName: block` is already in use' do
it 'registers and no corrects an offense when using anonymous block forwarding' do
expect_offense(<<~RUBY)
def foo(block, &)
^ Use explicit block forwarding.
bar(block, &)
^ Use explicit block forwarding.
baz(block, qux, &)
^ Use explicit block forwarding.
end
RUBY
expect_no_corrections
end
end
context 'when `BlockForwardingName: proc' do
let(:block_forwarding_name) { 'proc' }
it 'registers and corrects an offense when using anonymous block forwarding' do
expect_offense(<<~RUBY)
def foo(&)
^ Use explicit block forwarding.
bar(&)
^ Use explicit block forwarding.
baz(qux, &)
^ Use explicit block forwarding.
end
RUBY
expect_correction(<<~RUBY)
def foo(&proc)
bar(&proc)
baz(qux, &proc)
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/naming/variable_name_spec.rb | spec/rubocop/cop/naming/variable_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::VariableName, :config do
shared_examples 'always accepted' do
it 'accepts screaming snake case globals' do
expect_no_offenses('$MY_GLOBAL = 0')
end
it 'accepts screaming snake case constants' do
expect_no_offenses('MY_CONSTANT = 0')
end
it 'accepts assigning to camel case constant' do
expect_no_offenses('Paren = Struct.new :left, :right, :kind')
end
it 'accepts assignment with indexing of self' do
expect_no_offenses('self[:a] = b')
end
it 'accepts local variables marked as unused' do
expect_no_offenses('_ = 1')
end
it 'accepts one symbol size local variables' do
expect_no_offenses('i = 1')
end
end
shared_examples 'allowed identifiers' do |identifier|
context 'when AllowedIdentifiers is set' do
let(:cop_config) { super().merge('AllowedIdentifiers' => [identifier]) }
it 'does not register an offense for a local variable name that is allowed' do
expect_no_offenses(<<~RUBY)
#{identifier} = :foo
RUBY
end
it 'does not register an offense for an instance variable name that is allowed' do
expect_no_offenses(<<~RUBY)
@#{identifier} = :foo
RUBY
end
it 'does not register an offense for a class variable name that is allowed' do
expect_no_offenses(<<~RUBY)
@@#{identifier} = :foo
RUBY
end
it 'does not register an offense for a global variable name that is allowed' do
expect_no_offenses(<<~RUBY)
$#{identifier} = :foo
RUBY
end
it 'does not register an offense for a method name that is allowed' do
expect_no_offenses(<<~RUBY)
def #{identifier}
end
RUBY
end
it 'does not register an offense for a symbol that is allowed' do
expect_no_offenses(":#{identifier}")
end
end
end
shared_examples 'allowed patterns' do |pattern, identifier|
context 'when AllowedPatterns is set' do
let(:cop_config) { super().merge('AllowedPatterns' => [pattern]) }
it 'does not register an offense for a local variable name that matches the allowed pattern' do
expect_no_offenses(<<~RUBY)
#{identifier} = :foo
RUBY
end
it 'does not register an offense for an instance variable name that matches the allowed pattern' do
expect_no_offenses(<<~RUBY)
@#{identifier} = :foo
RUBY
end
it 'does not register an offense for a class variable name that matches the allowed pattern' do
expect_no_offenses(<<~RUBY)
@@#{identifier} = :foo
RUBY
end
it 'does not register an offense for a global variable name that matches the allowed pattern' do
expect_no_offenses(<<~RUBY)
$#{identifier} = :foo
RUBY
end
it 'does not register an offense for a method name that matches the allowed pattern' do
expect_no_offenses(<<~RUBY)
def #{identifier}
end
RUBY
end
it 'does not register an offense for a symbol that matches the allowed pattern' do
expect_no_offenses(":#{identifier}")
end
end
end
shared_examples 'forbidden identifiers' do |identifier|
context 'when ForbiddenIdentifiers is set' do
let(:cop_config) { super().merge('ForbiddenIdentifiers' => [identifier]) }
context 'with `lvasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
%{identifier} = true
^{identifier} `%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `ivasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
@%{identifier} = true
^^{identifier} `@%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `cvasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
@@%{identifier} = true
^^^{identifier} `@@%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `gvasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
$%{identifier} = true
^^{identifier} `$%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `arg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `optarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier} = false)
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `restarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(*%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
end
end
context 'with `kwarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier}:)
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `kwargopt`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier}: true)
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
end
end
context 'with `kwrestarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(**%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `blockarg` in `def`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(&%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `blockarg` in `block`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
foo do |%{identifier}|
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
it 'does not register an offense for a method definition' do
expect_no_offenses(<<~RUBY)
def #{identifier}
end
RUBY
end
it 'does not register an offense for a method identifier' do
expect_no_offenses(<<~RUBY)
#{identifier}()
RUBY
end
end
end
shared_examples 'forbidden patterns' do |pattern, identifier|
context 'when ForbiddenPatterns is set' do
let(:cop_config) { super().merge('ForbiddenPatterns' => [pattern]) }
context 'with `lvasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
%{identifier} = true
^{identifier} `%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `ivasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
@%{identifier} = true
^^{identifier} `@%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `cvasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
@@%{identifier} = true
^^^{identifier} `@@%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `gvasgn`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
$%{identifier} = true
^^{identifier} `$%{identifier}` is forbidden, use another name instead.
RUBY
expect_no_corrections
end
end
context 'with `arg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `optarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier} = false)
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `restarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(*%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
end
end
context 'with `kwarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier}:)
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `kwargopt`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(%{identifier}: true)
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
end
end
context 'with `kwrestarg`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(**%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `blockarg` in `def`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
def foo(&%{identifier})
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
context 'with `blockarg` in `block`' do
it 'registers an offense when given a forbidden identifier' do
expect_offense(<<~RUBY, identifier: identifier)
foo do |%{identifier}|
^{identifier} `%{identifier}` is forbidden, use another name instead.
end
RUBY
expect_no_corrections
end
end
it 'does not register an offense for a method definition' do
expect_no_offenses(<<~RUBY)
def #{identifier}
end
RUBY
end
it 'does not register an offense for a method identifier' do
expect_no_offenses(<<~RUBY)
#{identifier}()
RUBY
end
end
end
context 'when configured for snake_case' do
let(:cop_config) { { 'EnforcedStyle' => 'snake_case' } }
it 'registers an offense for camel case in local variable name' do
expect_offense(<<~RUBY)
myLocal = 1
^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for correct + opposite' do
expect_offense(<<~RUBY)
my_local = 1
myLocal = 1
^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for camel case in instance variable name' do
expect_offense(<<~RUBY)
@myAttribute = 3
^^^^^^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for camel case in class variable name' do
expect_offense(<<~RUBY)
@@myAttr = 2
^^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for camel case local variables marked as unused' do
expect_offense(<<~RUBY)
_myLocal = 1
^^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for method arguments' do
expect_offense(<<~RUBY)
def method(funnyArg); end
^^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for default method arguments' do
expect_offense(<<~RUBY)
def foo(optArg = 1); end
^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for rest arguments' do
expect_offense(<<~RUBY)
def foo(*restArg); end
^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for keyword arguments' do
expect_offense(<<~RUBY)
def foo(kwArg: 1); end
^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for keyword rest arguments' do
expect_offense(<<~RUBY)
def foo(**kwRest); end
^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for block arguments' do
expect_offense(<<~RUBY)
def foo(&blockArg); end
^^^^^^^^ Use snake_case for variable names.
RUBY
end
it 'registers an offense for camel case when invoking method args' do
expect_offense(<<~RUBY)
firstArg = 'foo'
^^^^^^^^ Use snake_case for variable names.
secondArg = 'foo'
^^^^^^^^^ Use snake_case for variable names.
do_something(firstArg, secondArg)
^^^^^^^^ Use snake_case for variable names.
^^^^^^^^^ Use snake_case for variable names.
RUBY
end
it_behaves_like 'always accepted'
it_behaves_like 'allowed identifiers', 'firstArg'
it_behaves_like 'allowed patterns', 'st[A-Z]', 'firstArg'
it_behaves_like 'forbidden identifiers', 'first_arg'
it_behaves_like 'forbidden patterns', 'st_[a-z]', 'first_arg'
end
context 'when configured for camelCase' do
let(:cop_config) { { 'EnforcedStyle' => 'camelCase' } }
it 'registers an offense for snake case in local variable name' do
expect_offense(<<~RUBY)
my_local = 1
^^^^^^^^ Use camelCase for variable names.
RUBY
end
it 'registers an offense for opposite + correct' do
expect_offense(<<~RUBY)
my_local = 1
^^^^^^^^ Use camelCase for variable names.
myLocal = 1
RUBY
end
it 'accepts camel case in local variable name' do
expect_no_offenses('myLocal = 1')
end
it 'accepts camel case in instance variable name' do
expect_no_offenses('@myAttribute = 3')
end
it 'accepts camel case in class variable name' do
expect_no_offenses('@@myAttr = 2')
end
it 'registers an offense for snake case in method parameter' do
expect_offense(<<~RUBY)
def method(funny_arg); end
^^^^^^^^^ Use camelCase for variable names.
RUBY
end
it 'accepts camel case local variables marked as unused' do
expect_no_offenses('_myLocal = 1')
end
it 'registers an offense for default method arguments' do
expect_offense(<<~RUBY)
def foo(opt_arg = 1); end
^^^^^^^ Use camelCase for variable names.
RUBY
end
it 'registers an offense for rest arguments' do
expect_offense(<<~RUBY)
def foo(*rest_arg); end
^^^^^^^^ Use camelCase for variable names.
RUBY
end
it 'registers an offense for keyword arguments' do
expect_offense(<<~RUBY)
def foo(kw_arg: 1); end
^^^^^^ Use camelCase for variable names.
RUBY
end
it 'registers an offense for keyword rest arguments' do
expect_offense(<<~RUBY)
def foo(**kw_rest); end
^^^^^^^ Use camelCase for variable names.
RUBY
end
it 'registers an offense for block arguments' do
expect_offense(<<~RUBY)
def foo(&block_arg); end
^^^^^^^^^ Use camelCase for variable names.
RUBY
end
it 'registers an offense for camel case when invoking method args' do
expect_offense(<<~RUBY)
first_arg = 'foo'
^^^^^^^^^ Use camelCase for variable names.
second_arg = 'foo'
^^^^^^^^^^ Use camelCase for variable names.
do_something(first_arg, second_arg)
^^^^^^^^^ Use camelCase for variable names.
^^^^^^^^^^ Use camelCase for variable names.
RUBY
end
it 'accepts with non-ascii characters' do
expect_no_offenses('léo = 1')
end
it_behaves_like 'always accepted'
it_behaves_like 'allowed identifiers', 'first_arg'
it_behaves_like 'allowed patterns', 'st_[a-z]', 'first_arg'
it_behaves_like 'forbidden identifiers', 'first_arg'
it_behaves_like 'forbidden patterns', 'st_[a-z]', 'first_arg'
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/naming/block_parameter_name_spec.rb | spec/rubocop/cop/naming/block_parameter_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::BlockParameterName, :config do
let(:cop_config) { { 'MinNameLength' => 2, 'AllowNamesEndingInNumbers' => false } }
it 'does not register for block without parameters' do
expect_no_offenses(<<~RUBY)
something do
do_stuff
end
RUBY
end
it 'does not register for brace block without parameters' do
expect_no_offenses(<<~RUBY)
something { do_stuff }
RUBY
end
it 'does not register offense for valid parameter names' do
expect_no_offenses(<<~RUBY)
something { |foo, bar| do_stuff }
RUBY
end
it 'registers an offense when param ends in number' do
expect_offense(<<~RUBY)
something { |foo1, bar| do_stuff }
^^^^ Do not end block parameter with a number.
RUBY
end
it 'registers an offense when param is less than minimum length' do
expect_offense(<<~RUBY)
something do |x|
^ Block parameter must be at least 2 characters long.
do_stuff
end
RUBY
end
it 'registers an offense when param with prefix is less than minimum length' do
expect_offense(<<~RUBY)
something do |_a, __b, *c, **__d|
^^ Block parameter must be at least 2 characters long.
^^^ Block parameter must be at least 2 characters long.
^^ Block parameter must be at least 2 characters long.
^^^^^ Block parameter must be at least 2 characters long.
do_stuff
end
RUBY
end
it 'registers an offense when param contains uppercase characters' do
expect_offense(<<~RUBY)
something { |number_One| do_stuff }
^^^^^^^^^^ Only use lowercase characters for block parameter.
RUBY
end
it 'can register multiple offenses in one block' do
expect_offense(<<~RUBY)
something do |y, num1, oFo|
^ Block parameter must be at least 2 characters long.
^^^^ Do not end block parameter with a number.
^^^ Only use lowercase characters for block parameter.
do_stuff
end
RUBY
end
context 'with AllowedNames' do
let(:cop_config) do
{
'AllowedNames' => %w[foo1 foo2],
'AllowNamesEndingInNumbers' => false
}
end
it 'accepts specified block param names' do
expect_no_offenses(<<~RUBY)
something { |foo1, foo2| do_things }
RUBY
end
it 'registers unlisted offensive names' do
expect_offense(<<~RUBY)
something { |bar, bar1| do_things }
^^^^ Do not end block parameter with a number.
RUBY
end
end
context 'with ForbiddenNames' do
let(:cop_config) { { 'ForbiddenNames' => %w[arg] } }
it 'registers an offense for param listed as forbidden' do
expect_offense(<<~RUBY)
something { |arg| do_stuff }
^^^ Do not use arg as a name for a block parameter.
RUBY
end
it "accepts param that uses a forbidden name's letters" do
expect_no_offenses(<<~RUBY)
something { |foo_arg| do_stuff }
RUBY
end
end
context 'with AllowNamesEndingInNumbers' do
let(:cop_config) { { 'AllowNamesEndingInNumbers' => true } }
it 'accepts params that end in numbers' do
expect_no_offenses(<<~RUBY)
something { |foo1, bar2, qux3| do_that_stuff }
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/naming/rescued_exceptions_variable_name_spec.rb | spec/rubocop/cop/naming/rescued_exceptions_variable_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::RescuedExceptionsVariableName, :config do
context 'with default config' do
context 'with explicit rescue' do
context 'with `Exception` variable' do
it 'registers an offense when using `exc`' do
expect_offense(<<~RUBY)
begin
something
rescue MyException => exc
^^^ Use `e` instead of `exc`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue MyException => e
# do something
end
RUBY
end
it 'registers an offense when using `_exc`' do
expect_offense(<<~RUBY)
begin
something
rescue MyException => _exc
^^^^ Use `_e` instead of `_exc`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue MyException => _e
# do something
end
RUBY
end
it 'registers an offense when using `exc` and renames its usage' do
expect_offense(<<~RUBY)
begin
something
rescue MyException => exc
^^^ Use `e` instead of `exc`.
exc
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue MyException => e
e
end
RUBY
end
it 'registers offenses when using `foo` and `bar` in multiple rescues' do
expect_offense(<<~RUBY)
begin
something
rescue FooException => foo
^^^ Use `e` instead of `foo`.
# do something
rescue BarException => bar
^^^ Use `e` instead of `bar`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue FooException => e
# do something
rescue BarException => e
# do something
end
RUBY
end
it 'registers an offense when using `error` for an explicit hash value' do
expect_offense(<<~RUBY)
begin
rescue => error
^^^^^ Use `e` instead of `error`.
do_something(error: error)
end
RUBY
expect_correction(<<~RUBY)
begin
rescue => e
do_something(error: e)
end
RUBY
end
it 'registers an offense when using `error` for an omitted hash value', :ruby31 do
expect_offense(<<~RUBY)
begin
rescue => error
^^^^^ Use `e` instead of `error`.
do_something(error:)
end
RUBY
expect_correction(<<~RUBY)
begin
rescue => e
do_something(error: e)
end
RUBY
end
it 'does not register an offense when using `e`' do
expect_no_offenses(<<~RUBY)
begin
something
rescue MyException => e
# do something
end
RUBY
end
it 'does not register an offense when using `_e`' do
expect_no_offenses(<<~RUBY)
begin
something
rescue MyException => _e
# do something
end
RUBY
end
it 'does not register an offense when using _e followed by e' do
expect_no_offenses(<<~RUBY)
begin
something
rescue MyException => _e
# do something
rescue AnotherException => e
# do something
end
RUBY
end
end
context 'without `Exception` variable' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
begin
something
rescue MyException
# do something
end
RUBY
end
end
context 'shadowing an external variable' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
e = 'error message'
begin
something
rescue StandardError => e1
log(e, e1)
end
RUBY
end
end
context 'with lower letters class name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
begin
something
rescue my_exception
# do something
end
RUBY
end
end
context 'with method as `Exception`' do
it 'does not register an offense without variable name' do
expect_no_offenses(<<~RUBY)
begin
something
rescue ActiveSupport::JSON.my_method
# do something
end
RUBY
end
it 'does not register an offense with expected variable name' do
expect_no_offenses(<<~RUBY)
begin
something
rescue ActiveSupport::JSON.my_method => e
# do something
end
RUBY
end
it 'registers an offense with unexpected variable name' do
expect_offense(<<~RUBY)
begin
something
rescue ActiveSupport::JSON.my_method => exc
^^^ Use `e` instead of `exc`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue ActiveSupport::JSON.my_method => e
# do something
end
RUBY
end
end
context 'with splat operator as `Exception` list' do
it 'does not register an offense without variable name' do
expect_no_offenses(<<~RUBY)
begin
something
rescue *handled
# do something
end
RUBY
end
it 'does not register an offense with expected variable name' do
expect_no_offenses(<<~RUBY)
begin
something
rescue *handled => e
# do something
end
RUBY
end
it 'registers an offense with unexpected variable name' do
expect_offense(<<~RUBY)
begin
something
rescue *handled => exc
^^^ Use `e` instead of `exc`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue *handled => e
# do something
end
RUBY
end
end
end
context 'with implicit rescue' do
context 'with `Exception` variable' do
it 'registers an offense when using `exc`' do
expect_offense(<<~RUBY)
begin
something
rescue => exc
^^^ Use `e` instead of `exc`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue => e
# do something
end
RUBY
end
it 'registers an offense when using `_exc`' do
expect_offense(<<~RUBY)
begin
something
rescue => _exc
^^^^ Use `_e` instead of `_exc`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue => _e
# do something
end
RUBY
end
it 'does not register an offense when using `e`' do
expect_no_offenses(<<~RUBY)
begin
something
rescue => e
# do something
end
RUBY
end
it 'does not register an offense when using `_e`' do
expect_no_offenses(<<~RUBY)
begin
something
rescue => _e
# do something
end
RUBY
end
end
context 'without `Exception` variable' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
begin
something
rescue
# do something
end
RUBY
end
end
end
context 'with variable being referenced' do
it 'renames the variable references when autocorrecting' do
expect_offense(<<~RUBY)
begin
get something
rescue ActiveResource::Redirection => redirection
^^^^^^^^^^^ Use `e` instead of `redirection`.
redirect_to redirection.response['Location']
end
RUBY
expect_correction(<<~RUBY)
begin
get something
rescue ActiveResource::Redirection => e
redirect_to e.response['Location']
end
RUBY
end
end
context 'when the variable is reassigned' do
it 'only corrects uses of the exception' do
expect_offense(<<~RUBY)
def main
raise
rescue StandardError => error
^^^^^ Use `e` instead of `error`.
error = {
error_message: error.message
}
puts error
end
RUBY
expect_correction(<<~RUBY)
def main
raise
rescue StandardError => e
error = {
error_message: e.message
}
puts error
end
RUBY
end
it 'only corrects the exception variable' do
expect_offense(<<~RUBY)
def main
raise
rescue StandardError => error
^^^^^ Use `e` instead of `error`.
message = error.message
puts message
end
RUBY
expect_correction(<<~RUBY)
def main
raise
rescue StandardError => e
message = e.message
puts message
end
RUBY
end
end
context 'when the variable is reassigned using multiple assignment' do
it 'only corrects uses of the exception' do
expect_offense(<<~RUBY)
def main
raise
rescue StandardError => error
^^^^^ Use `e` instead of `error`.
error, foo = 1, error
puts error
end
RUBY
expect_correction(<<~RUBY)
def main
raise
rescue StandardError => e
error, foo = 1, e
puts error
end
RUBY
end
end
context 'with multiple branches' do
it 'registers and corrects each offense' do
expect_offense(<<~RUBY)
begin
something
rescue MyException => exc
^^^ Use `e` instead of `exc`.
# do something
rescue OtherException => exc
^^^ Use `e` instead of `exc`.
# do something else
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue MyException => e
# do something
rescue OtherException => e
# do something else
end
RUBY
end
end
context 'with nested rescues' do
it 'handles it' do
expect_offense(<<~RUBY)
begin
rescue StandardError => e1
^^ Use `e` instead of `e1`.
begin
log(e1)
rescue StandardError => e2
log(e1, e2)
end
end
RUBY
expect_correction(<<~RUBY)
begin
rescue StandardError => e
begin
log(e)
rescue StandardError => e2
log(e, e2)
end
end
RUBY
end
end
context 'when the variable is referenced after `rescue` statement' do
it 'handles it' do
expect_offense(<<~RUBY)
begin
something
rescue StandardError => e1
^^ Use `e` instead of `e1`.
end
foo(e1)
RUBY
expect_correction(<<~RUBY)
begin
something
rescue StandardError => e
end
foo(e)
RUBY
end
end
context 'when exception is assigned with writer method' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
begin
something
rescue => storage.exception
# do something
end
RUBY
end
end
end
context 'with the `PreferredName` setup' do
let(:cop_config) { { 'PreferredName' => 'exception' } }
it 'registers an offense when using `e`' do
expect_offense(<<~RUBY)
begin
something
rescue MyException => e
^ Use `exception` instead of `e`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue MyException => exception
# do something
end
RUBY
end
it 'registers an offense when using `_e`' do
expect_offense(<<~RUBY)
begin
something
rescue MyException => _e
^^ Use `_exception` instead of `_e`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue MyException => _exception
# do something
end
RUBY
end
it 'registers offenses when using `foo` and `bar` in multiple rescues' do
expect_offense(<<~RUBY)
begin
something
rescue FooException => foo
^^^ Use `exception` instead of `foo`.
# do something
rescue BarException => bar
^^^ Use `exception` instead of `bar`.
# do something
end
RUBY
expect_correction(<<~RUBY)
begin
something
rescue FooException => exception
# do something
rescue BarException => exception
# do something
end
RUBY
end
it 'does not register an offense when using `exception`' do
expect_no_offenses(<<~RUBY)
begin
something
rescue MyException => exception
# do something
end
RUBY
end
it 'does not register an offense when using `_exception`' do
expect_no_offenses(<<~RUBY)
begin
something
rescue MyException => _exception
# do something
end
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/naming/file_name_spec.rb | spec/rubocop/cop/naming/file_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::FileName, :config do
let(:config) do
RuboCop::Config.new(
{ 'AllCops' => { 'Include' => includes },
described_class.badge.to_s => cop_config },
'/some/.rubocop.yml'
)
end
let(:cop_config) do # matches default.yml
{
'IgnoreExecutableScripts' => true,
'ExpectMatchingDefinition' => false,
'Regex' => nil,
'CheckDefinitionPathHierarchy' => true,
'CheckDefinitionPathHierarchyRoots' => %w[lib spec test src]
}
end
let(:includes) { ['**/*.rb'] }
context 'with camelCase file names ending in .rb' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/some/dir/testCase.rb')
print 1
^{} The name of this source file (`testCase.rb`) should use snake_case.
RUBY
end
end
context 'with camelCase file names without file extension' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/some/dir/testCase')
print 1
^{} The name of this source file (`testCase`) should use snake_case.
RUBY
end
end
context 'with snake_case file names ending in .rb' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/some/dir/test_case.rb')
print 1
RUBY
end
end
context 'with snake_case file names without file extension' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/some/dir/test_case')
print 1
RUBY
end
end
context 'with snake_case file names with non-rb extension' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/some/dir/test_case.rake')
print 1
RUBY
end
end
context 'with snake_case file names with multiple extensions' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'some/dir/some_view.html.slim_spec.rb')
print 1
RUBY
end
end
context 'with snake_case names which use ? and !' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'some/dir/file?!.rb')
print 1
RUBY
end
end
context 'with snake_case names which use +' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'some/dir/some_file.xlsx+mobile.axlsx')
print 1
RUBY
end
end
context 'with non-snake-case file names with a shebang' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/some/dir/test-case')
#!/usr/bin/env ruby
print 1
RUBY
end
context 'when IgnoreExecutableScripts is disabled' do
let(:cop_config) { super().merge('IgnoreExecutableScripts' => false) }
it 'registers an offense' do
expect_offense(<<~RUBY, '/some/dir/test-case')
#!/usr/bin/env ruby
^{} The name of this source file (`test-case`) should use snake_case.
print 1
RUBY
end
end
end
context 'when the file is specified in AllCops/Include' do
let(:includes) { ['**/Gemfile'] }
context 'with a non-snake_case file name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/some/dir/Gemfile')
print 1
RUBY
end
end
end
context 'when ExpectMatchingDefinition is true' do
let(:cop_config) { super().merge('ExpectMatchingDefinition' => true) }
context 'on a file which defines no class or module at all' do
%w[lib src test spec].each do |dir|
context "under #{dir}" do
it 'registers an offense' do
expect_offense(<<~RUBY, "/some/dir/#{dir}/file/test_case.rb")
print 1
^{} `test_case.rb` should define a class or module called `File::TestCase`.
RUBY
end
end
end
context 'under lib when not added to root' do
let(:cop_config) { super().merge('CheckDefinitionPathHierarchyRoots' => ['foo']) }
it 'registers an offense' do
expect_offense(<<~RUBY, '/some/other/dir/test_case.rb')
print 1
^{} `test_case.rb` should define a class or module called `TestCase`.
RUBY
end
end
context 'under some other random directory' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/some/other/dir/test_case.rb')
print 1
^{} `test_case.rb` should define a class or module called `TestCase`.
RUBY
end
end
end
context 'on an empty file' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/lib/rubocop/blah.rb')
^{} `blah.rb` should define a class or module called `Rubocop::Blah`.
RUBY
end
end
context 'on an empty file with a space in its filename' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'a file.rb')
^{} The name of this source file (`a file.rb`) should use snake_case.
RUBY
end
end
shared_examples 'matching module or class' do |source|
%w[lib src test spec].each do |dir|
context "in a matching directory under #{dir}" do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, "/some/dir/#{dir}/a/b.rb")
#{source}
RUBY
end
end
context "in a non-matching directory under #{dir}" do
it 'registers an offense' do
expect_offense(<<~RUBY, "/some/dir/#{dir}/c/b.rb")
# b.rb
^{} `b.rb` should define a class or module called `C::B`.
#{source}
RUBY
end
end
context "in a directory with multiple instances of #{dir}" do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, "/some/dir/#{dir}/project/#{dir}/a/b.rb")
#{source}
RUBY
end
end
end
context 'in a directory elsewhere which only matches the module name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/some/dir/b.rb')
#{source}
RUBY
end
end
context 'in a directory elsewhere which does not match the module name' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/some/dir/e.rb')
# start of file
^{} `e.rb` should define a class or module called `E`.
#{source}
RUBY
end
end
end
context 'on a file which defines a nested module' do
it_behaves_like 'matching module or class', <<~RUBY
module A
module B
end
end
RUBY
end
context 'on a file which defines a nested class' do
it_behaves_like 'matching module or class', <<~RUBY
module A
class B
end
end
RUBY
end
context 'on a file which uses Name::Spaced::Module syntax' do
it_behaves_like 'matching module or class', <<~RUBY
begin
module A::B
end
end
RUBY
end
context 'on a file which defines multiple classes' do
it_behaves_like 'matching module or class', <<~RUBY
class X
end
module M
end
class A
class B
end
end
RUBY
end
context 'on a file which defines a Struct without a block' do
it_behaves_like 'matching module or class', <<~RUBY
module A
B = Struct.new(:foo, :bar)
end
RUBY
end
context 'on a file which defines a Struct with a block' do
it_behaves_like 'matching module or class', <<~RUBY
module A
B = Struct.new(:foo, :bar) do
end
end
RUBY
end
end
context 'when CheckDefinitionPathHierarchy is false' do
let(:cop_config) do
super().merge('ExpectMatchingDefinition' => true, 'CheckDefinitionPathHierarchy' => false)
end
context 'on a file with a matching class' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/lib/image_collection.rb')
begin
class ImageCollection
end
end
RUBY
end
end
context 'on a file with a non-matching class' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/lib/image_collection.rb')
begin
^{} `image_collection.rb` should define a class or module called `ImageCollection`.
class PictureCollection
end
end
RUBY
end
end
context 'on a file with a matching struct' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/lib/image_collection.rb')
ImageCollection = Struct.new
RUBY
end
end
context 'on a file with a non-matching struct' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/lib/image_collection.rb')
PictureCollection = Struct.new
^{} `image_collection.rb` should define a class or module called `ImageCollection`.
RUBY
end
end
context 'on an empty file' do
it 'registers an offense' do
expect_offense(<<~RUBY, '/lib/rubocop/foo.rb')
^{} `foo.rb` should define a class or module called `Foo`.
RUBY
end
end
context 'in a non-matching directory, but with a matching class' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/lib/some/path/foo.rb')
begin
module Foo
end
end
RUBY
end
end
context 'with a non-matching module containing a matching class' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'lib/foo.rb')
begin
module NonMatching
class Foo
end
end
end
RUBY
end
end
context 'with a matching module containing a non-matching class' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'lib/foo.rb')
begin
module Foo
class NonMatching
end
end
end
RUBY
end
end
context 'with a non-matching module containing a matching struct' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'lib/foo.rb')
begin
module NonMatching
Foo = Struct.new
end
end
RUBY
end
end
context 'with a matching module containing a non-matching struct' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'lib/foo.rb')
begin
module Foo
NonMatching = Struct.new
end
end
RUBY
end
end
end
context 'when Regex is set' do
let(:cop_config) { { 'Regex' => /\A[aeiou]\z/i } }
context 'with a matching name' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, 'a.rb')
print 1
RUBY
end
end
context 'with a non-matching name' do
it 'registers an offense' do
expect_offense(<<~RUBY, 'z.rb')
print 1
^{} `z.rb` should match `(?i-mx:\\A[aeiou]\\z)`.
RUBY
end
end
end
context 'with acronym namespace' do
let(:cop_config) do
super().merge('ExpectMatchingDefinition' => true, 'AllowedAcronyms' => ['CLI'])
end
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/lib/my/cli/admin_user.rb')
module My
module CLI
class AdminUser
end
end
end
RUBY
end
end
context 'with acronym class name' do
let(:cop_config) do
super().merge('ExpectMatchingDefinition' => true, 'AllowedAcronyms' => ['CLI'])
end
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/lib/my/cli.rb')
module My
class CLI
end
end
RUBY
end
end
context 'with include acronym name' do
let(:cop_config) do
super().merge('ExpectMatchingDefinition' => true, 'AllowedAcronyms' => ['HTTP'])
end
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/lib/my/http_server.rb')
module My
class HTTPServer
end
end
RUBY
end
end
context 'with dotfiles' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '.pryrc')
print 1
RUBY
end
end
context 'with non-ascii characters in filename' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY, '/some/dir/ünbound_sérvér.rb')
print 1
RUBY
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/naming/predicate_prefix_spec.rb | spec/rubocop/cop/naming/predicate_prefix_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::PredicatePrefix, :config do
context 'with restricted prefixes' do
let(:cop_config) { { 'NamePrefix' => %w[has_ is_], 'ForbiddenPrefixes' => %w[has_ is_] } }
it 'registers an offense when method name starts with "is"' do
expect_offense(<<~RUBY)
def is_attr; end
^^^^^^^ Rename `is_attr` to `attr?`.
RUBY
end
it 'registers an offense when method name starts with "has"' do
expect_offense(<<~RUBY)
def has_attr; end
^^^^^^^^ Rename `has_attr` to `attr?`.
RUBY
end
it 'accepts method name that starts with unknown prefix' do
expect_no_offenses(<<~RUBY)
def have_attr; end
RUBY
end
it 'accepts method name that is an assignment' do
expect_no_offenses(<<~RUBY)
def is_hello=; end
RUBY
end
it 'accepts method name when corrected name is invalid identifier' do
expect_no_offenses(<<~RUBY)
def is_2d?; end
RUBY
end
end
context 'without restricted prefixes' do
let(:cop_config) { { 'NamePrefix' => %w[has_ is_], 'ForbiddenPrefixes' => [] } }
it 'registers an offense when method name starts with "is"' do
expect_offense(<<~RUBY)
def is_attr; end
^^^^^^^ Rename `is_attr` to `is_attr?`.
RUBY
end
it 'registers an offense when method name starts with "has"' do
expect_offense(<<~RUBY)
def has_attr; end
^^^^^^^^ Rename `has_attr` to `has_attr?`.
RUBY
end
it 'accepts method name that starts with unknown prefix' do
expect_no_offenses(<<~RUBY)
def have_attr; end
RUBY
end
it 'accepts method name when corrected name is invalid identifier' do
expect_no_offenses(<<~RUBY)
def is_2d?; end
RUBY
end
end
context 'with permitted predicate names' do
let(:cop_config) do
{ 'NamePrefix' => %w[is_], 'ForbiddenPrefixes' => %w[is_],
'AllowedMethods' => %w[is_a?] }
end
it 'accepts method name which is in permitted list' do
expect_no_offenses(<<~RUBY)
def is_a?; end
RUBY
end
end
context 'with method definition macros' do
let(:cop_config) do
{ 'NamePrefix' => %w[is_], 'ForbiddenPrefixes' => %w[is_],
'MethodDefinitionMacros' => %w[define_method def_node_matcher] }
end
it 'registers an offense when using `define_method`' do
expect_offense(<<~RUBY)
define_method(:is_hello) do |method_name|
^^^^^^^^^ Rename `is_hello` to `hello?`.
method_name == 'hello'
end
RUBY
end
it 'registers an offense when using an internal affair macro' do
expect_offense(<<~RUBY)
def_node_matcher :is_hello, <<~PATTERN
^^^^^^^^^ Rename `is_hello` to `hello?`.
(send
(send nil? :method_name) :==
(str 'hello'))
PATTERN
RUBY
end
it 'accepts method name when corrected name is invalid identifier' do
expect_no_offenses(<<~RUBY)
define_method(:is_2d?) do |method_name|
method_name == 'hello'
end
RUBY
end
end
context 'without method definition macros' do
let(:cop_config) { { 'NamePrefix' => %w[is_], 'ForbiddenPrefixes' => %w[is_] } }
it 'registers an offense when using `define_method`' do
expect_offense(<<~RUBY)
define_method(:is_hello) do |method_name|
^^^^^^^^^ Rename `is_hello` to `hello?`.
method_name == 'hello'
end
RUBY
end
it 'does not register any offenses when using an internal affair macro' do
expect_no_offenses(<<~RUBY)
def_node_matcher :is_hello, <<~PATTERN
(send
(send nil? :method_name) :==
(str 'hello'))
PATTERN
RUBY
end
it 'accepts method name when corrected name is invalid identifier' do
expect_no_offenses(<<~RUBY)
define_method(:is_2d?) do |method_name|
method_name == 'hello'
end
RUBY
end
end
context 'using Sorbet sigs' do
let(:cop_config) do
{
'NamePrefix' => %w[is_ has_],
'ForbiddenPrefixes' => [],
'UseSorbetSigs' => 'true'
}
end
it 'registers an offense if no ? when `sig { returns(T::Boolean) }` and variants' do
expect_offense(<<~RUBY)
sig { returns(T::Boolean) }
def is_attr; end
^^^^^^^ Rename `is_attr` to `is_attr?`.
RUBY
expect_offense(<<~RUBY)
sig { returns(T::Boolean) }
# Comment here.
def is_attr; end
^^^^^^^ Rename `is_attr` to `is_attr?`.
RUBY
expect_offense(<<~RUBY)
sig { returns(T::Boolean) }
def is_attr; end
^^^^^^^ Rename `is_attr` to `is_attr?`.
RUBY
expect_offense(<<~RUBY)
sig do
returns(T::Boolean)
end
def is_attr; end
^^^^^^^ Rename `is_attr` to `is_attr?`.
RUBY
end
it 'does not register an offense if no ? when `sig { returns(T::Array[String]) }`' do
expect_no_offenses(<<~RUBY)
sig { returns(T::Array[String]) }
def has_caused_error
errors.add(:base, 'This has caused an error')
end
RUBY
end
it 'picks the correct sig when there are multiple' do
expect_no_offenses(<<~RUBY)
sig { returns(T::Boolean) }
def is_attr?; end
sig { returns(String) }
def has_caused_error
errors.add(:base, 'This has caused an error')
end
RUBY
end
it 'works correctly when returns is chained on params' do
expect_offense(<<~RUBY)
sig { params(x: Integer).returns(T::Boolean) }
def is_even(x); end
^^^^^^^ Rename `is_even` to `is_even?`.
RUBY
end
it 'does not register an offense if no ? when no sigs but the config is enabled' do
expect_no_offenses(<<~RUBY)
def is_attr; 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/naming/method_parameter_name_spec.rb | spec/rubocop/cop/naming/method_parameter_name_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::MethodParameterName, :config do
let(:cop_config) { { 'MinNameLength' => 3, 'AllowNamesEndingInNumbers' => false } }
context 'when using argument forwarding', :ruby27 do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
def foo(...); end
RUBY
end
end
it 'does not register for method without parameters' do
expect_no_offenses(<<~RUBY)
def something
do_stuff
end
RUBY
end
it 'does not register offense for valid parameter names' do
expect_no_offenses(<<~RUBY)
def something(foo, bar)
do_stuff
end
RUBY
end
it 'does not register offense for valid parameter names on self.method' do
expect_no_offenses(<<~RUBY)
def self.something(foo, bar)
do_stuff
end
RUBY
end
it 'does not register offense for valid default parameters' do
expect_no_offenses(<<~RUBY)
def self.something(foo = Pwd.dir, bar = 1)
do_stuff
end
RUBY
end
it 'does not register offense for valid keyword parameters' do
expect_no_offenses(<<~RUBY)
def self.something(foo: Pwd.dir, bar: 1)
do_stuff
end
RUBY
end
it 'does not register offense for empty restarg' do
expect_no_offenses(<<~RUBY)
def qux(*)
stuff!
end
RUBY
end
it 'does not register offense for empty kwrestarg' do
expect_no_offenses(<<~RUBY)
def qux(**)
stuff!
end
RUBY
end
it 'registers an offense when parameter ends in number' do
expect_offense(<<~RUBY)
def something(foo1, bar)
^^^^ Do not end method parameter with a number.
do_stuff
end
RUBY
end
it 'registers an offense when parameter ends in number on class method' do
expect_offense(<<~RUBY)
def self.something(foo, bar1)
^^^^ Do not end method parameter with a number.
do_stuff
end
RUBY
end
it 'registers an offense when parameter is less than minimum length' do
expect_offense(<<~RUBY)
def something(ab)
^^ Method parameter must be at least 3 characters long.
do_stuff
end
RUBY
end
it 'registers an offense when parameter with prefix is less than minimum length' do
expect_offense(<<~RUBY)
def something(_a, __b, *c, **__d)
^^ Method parameter must be at least 3 characters long.
^^^ Method parameter must be at least 3 characters long.
^^ Method parameter must be at least 3 characters long.
^^^^^ Method parameter must be at least 3 characters long.
do_stuff
end
RUBY
end
it 'registers an offense when parameter contains uppercase characters' do
expect_offense(<<~RUBY)
def something(number_One)
^^^^^^^^^^ Only use lowercase characters for method parameter.
do_stuff
end
RUBY
end
it 'registers an offense for offensive default parameter' do
expect_offense(<<~RUBY)
def self.something(foo1 = Pwd.dir)
^^^^ Do not end method parameter with a number.
do_stuff
end
RUBY
end
it 'registers an offense for offensive keyword parameters' do
expect_offense(<<~RUBY)
def something(fooBar:)
^^^^^^ Only use lowercase characters for method parameter.
do_stuff
end
RUBY
end
it 'can register multiple offenses in one method definition' do
expect_offense(<<~RUBY)
def self.something(y, num1, oFo)
^ Method parameter must be at least 3 characters long.
^^^^ Do not end method parameter with a number.
^^^ Only use lowercase characters for method parameter.
do_stuff
end
RUBY
end
context 'with AllowedNames' do
let(:cop_config) do
{
'AllowedNames' => %w[foo1 foo2],
'AllowNamesEndingInNumbers' => false
}
end
it 'accepts specified block param names' do
expect_no_offenses(<<~RUBY)
def quux(foo1, foo2)
do_stuff
end
RUBY
end
it 'accepts param names prefixed with underscore' do
expect_no_offenses(<<~RUBY)
def quux(_foo1, _foo2)
do_stuff
end
RUBY
end
it 'accepts underscore param names' do
expect_no_offenses(<<~RUBY)
def quux(_)
do_stuff
end
RUBY
end
it 'registers unlisted offensive names' do
expect_offense(<<~RUBY)
def quux(bar, bar1)
^^^^ Do not end method parameter with a number.
do_stuff
end
RUBY
end
end
context 'with ForbiddenNames' do
let(:cop_config) { { 'ForbiddenNames' => %w[arg] } }
it 'registers an offense for parameter listed as forbidden' do
expect_offense(<<~RUBY)
def baz(arg)
^^^ Do not use arg as a name for a method parameter.
arg.do_things
end
RUBY
end
it "accepts parameter that uses a forbidden name's letters" do
expect_no_offenses(<<~RUBY)
def baz(foo_parameter)
foo_parameter.do_things
end
RUBY
end
end
context 'with AllowNamesEndingInNumbers' do
let(:cop_config) { { 'AllowNamesEndingInNumbers' => true } }
it 'accepts parameters that end in numbers' do
expect_no_offenses(<<~RUBY)
def something(foo1, bar2, qux3)
do_stuff
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/naming/heredoc_delimiter_case_spec.rb | spec/rubocop/cop/naming/heredoc_delimiter_case_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Naming::HeredocDelimiterCase, :config do
context 'when enforced style is uppercase' do
let(:cop_config) do
{
'SupportedStyles' => %w[uppercase lowercase],
'EnforcedStyle' => 'uppercase'
}
end
context 'with an interpolated heredoc' do
it 'registers an offense and corrects with a lowercase delimiter' do
expect_offense(<<~RUBY)
<<-sql
foo
sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-SQL
foo
SQL
RUBY
end
it 'registers an offense with a camel case delimiter' do
expect_offense(<<~RUBY)
<<-Sql
foo
Sql
^^^ Use uppercase heredoc delimiters.
RUBY
end
it 'does not register an offense with an uppercase delimiter' do
expect_no_offenses(<<~RUBY)
<<-SQL
foo
SQL
RUBY
end
end
context 'with a non-interpolated heredoc' do
context 'when using single quoted delimiters' do
it 'registers an offense and corrects with a lowercase delimiter' do
expect_offense(<<~RUBY)
<<-'sql'
foo
sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-'SQL'
foo
SQL
RUBY
end
it 'registers an offense and corrects with a camel case delimiter' do
expect_offense(<<~RUBY)
<<-'Sql'
foo
Sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-'SQL'
foo
SQL
RUBY
end
it 'does not register an offense with an uppercase delimiter' do
expect_no_offenses(<<~RUBY)
<<-'SQL'
foo
SQL
RUBY
end
end
context 'when using double quoted delimiters' do
it 'registers an offense and corrects with a lowercase delimiter' do
expect_offense(<<~RUBY)
<<-"sql"
foo
sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-"SQL"
foo
SQL
RUBY
end
it 'registers an offense and corrects with a camel case delimiter' do
expect_offense(<<~RUBY)
<<-"Sql"
foo
Sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-"SQL"
foo
SQL
RUBY
end
it 'does not register an offense with an uppercase delimiter' do
expect_no_offenses(<<~RUBY)
<<-"SQL"
foo
SQL
RUBY
end
end
context 'when using back tick delimiters' do
it 'registers an offense and corrects with a lowercase delimiter' do
expect_offense(<<~RUBY)
<<-`sql`
foo
sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-`SQL`
foo
SQL
RUBY
end
it 'registers an offense and corrects with a camel case delimiter' do
expect_offense(<<~RUBY)
<<-`Sql`
foo
Sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-`SQL`
foo
SQL
RUBY
end
it 'does not register an offense with an uppercase delimiter' do
expect_no_offenses(<<~RUBY)
<<-`SQL`
foo
SQL
RUBY
end
end
context 'when using non-word delimiters' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
<<-'+'
foo
+
RUBY
end
end
# FIXME: `<<''` is a syntax error. This test was added because Parser gem can parse it,
# but this will be removed after https://github.com/whitequark/parser/issues/996 is resolved.
context 'when using blank heredoc delimiters', unsupported_on: :prism do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
<<''
RUBY
end
end
end
context 'with a squiggly heredoc' do
it 'registers an offense and corrects with a lowercase delimiter' do
expect_offense(<<~RUBY)
<<~sql
foo
sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<~SQL
foo
SQL
RUBY
end
it 'registers an offense and corrects with a camel case delimiter' do
expect_offense(<<~RUBY)
<<~Sql
foo
Sql
^^^ Use uppercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<~SQL
foo
SQL
RUBY
end
it 'does not register an offense with an uppercase delimiter' do
expect_no_offenses(<<~RUBY)
<<~SQL
foo
SQL
RUBY
end
end
end
context 'when enforced style is lowercase' do
let(:cop_config) do
{
'SupportedStyles' => %w[uppercase lowercase],
'EnforcedStyle' => 'lowercase'
}
end
context 'with an interpolated heredoc' do
it 'does not register an offense with a lowercase delimiter' do
expect_no_offenses(<<~RUBY)
<<-sql
foo
sql
RUBY
end
it 'registers an offense and corrects with a camel case delimiter' do
expect_offense(<<~RUBY)
<<-Sql
foo
Sql
^^^ Use lowercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-sql
foo
sql
RUBY
end
it 'registers an offense and corrects with an uppercase delimiter' do
expect_offense(<<~RUBY)
<<-SQL
foo
SQL
^^^ Use lowercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-sql
foo
sql
RUBY
end
end
context 'with a non-interpolated heredoc' do
it 'does not register an offense with a lowercase delimiter' do
expect_no_offenses(<<~RUBY)
<<-'sql'
foo
sql
RUBY
end
it 'registers an offense and corrects with a camel case delimiter' do
expect_offense(<<~RUBY)
<<-'Sql'
foo
Sql
^^^ Use lowercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-'sql'
foo
sql
RUBY
end
it 'registers an offense and corrects with an uppercase delimiter' do
expect_offense(<<~RUBY)
<<-'SQL'
foo
SQL
^^^ Use lowercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<-'sql'
foo
sql
RUBY
end
end
context 'with a squiggly heredoc' do
it 'does not register an offense with a lowercase delimiter' do
expect_no_offenses(<<~RUBY)
<<~sql
foo
sql
RUBY
end
it 'registers an offense and corrects with a camel case delimiter' do
expect_offense(<<~RUBY)
<<~Sql
foo
Sql
^^^ Use lowercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<~sql
foo
sql
RUBY
end
it 'registers an offense and corrects with an uppercase delimiter' do
expect_offense(<<~RUBY)
<<~SQL
foo
SQL
^^^ Use lowercase heredoc delimiters.
RUBY
expect_correction(<<~RUBY)
<<~sql
foo
sql
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/variable_force/reference_spec.rb | spec/rubocop/cop/variable_force/reference_spec.rb | # frozen_string_literal: true
require 'rubocop/ast/sexp'
RSpec.describe RuboCop::Cop::VariableForce::Reference do
include RuboCop::AST::Sexp
describe '.new' do
context 'when non variable reference node is passed' do
it 'raises error' do
node = s(:def)
scope = RuboCop::Cop::VariableForce::Scope.new(s(:class))
expect { described_class.new(node, scope) }.to raise_error(ArgumentError)
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/variable_force/scope_spec.rb | spec/rubocop/cop/variable_force/scope_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::VariableForce::Scope do
include RuboCop::AST::Sexp
subject(:scope) { described_class.new(scope_node) }
let(:ast) { RuboCop::ProcessedSource.new(source, ruby_version, parser_engine: parser_engine).ast }
let(:scope_node) { ast.each_node(scope_node_type).first }
describe '.new' do
context 'when lvasgn node is passed' do
it 'accepts that as top level scope' do
node = s(:lvasgn)
expect { described_class.new(node) }.not_to raise_error
end
end
context 'when begin node is passed' do
it 'accepts that as top level scope' do
node = s(:begin)
expect { described_class.new(node) }.not_to raise_error
end
end
end
describe '#name' do
context 'when the scope is instance method definition' do
let(:source) { <<~RUBY }
def some_method
end
RUBY
let(:scope_node_type) { :def }
it 'returns the method name' do
expect(scope.name).to eq(:some_method)
end
end
context 'when the scope is singleton method definition' do
let(:source) { <<~RUBY }
def self.some_method
end
RUBY
let(:scope_node_type) { :defs }
it 'returns the method name' do
expect(scope.name).to eq(:some_method)
end
end
end
describe '#body_node' do
shared_examples 'returns the body node' do
it 'returns the body node' do
expect(scope.body_node.children[1]).to eq(:this_is_target)
end
end
context 'when the scope is instance method' do
let(:source) do
<<~RUBY
def some_method
this_is_target
end
RUBY
end
let(:scope_node_type) { :def }
it_behaves_like 'returns the body node'
end
context 'when the scope is singleton method' do
let(:source) do
<<~RUBY
def self.some_method
this_is_target
end
RUBY
end
let(:scope_node_type) { :defs }
it_behaves_like 'returns the body node'
end
context 'when the scope is module' do
let(:source) do
<<~RUBY
module SomeModule
this_is_target
end
RUBY
end
let(:scope_node_type) { :module }
it_behaves_like 'returns the body node'
end
context 'when the scope is class' do
let(:source) do
<<~RUBY
class SomeClass
this_is_target
end
RUBY
end
let(:scope_node_type) { :class }
it_behaves_like 'returns the body node'
end
context 'when the scope is singleton class' do
let(:source) do
<<~RUBY
class << self
this_is_target
end
RUBY
end
let(:scope_node_type) { :sclass }
it_behaves_like 'returns the body node'
end
context 'when the scope is block' do
let(:source) do
<<~RUBY
1.times do
this_is_target
end
RUBY
end
let(:scope_node_type) { :block }
it_behaves_like 'returns the body node'
end
context 'when the scope is top level' do
let(:source) do
<<~RUBY
this_is_target
RUBY
end
let(:scope_node_type) { :send }
it_behaves_like 'returns the body node'
end
end
describe '#include?' do
subject { scope.include?(target_node) }
let(:source) { <<~RUBY }
class SomeClass
def self.some_method(arg1, arg2)
do_something
1.times do
foo = 1
end
end
end
RUBY
let(:scope_node_type) { :defs }
context 'with ancestor node the scope does not include' do
let(:target_node) { ast }
it { is_expected.to be false }
end
context 'with node of the scope itself' do
let(:target_node) { ast.each_node.find(&:defs_type?) }
it { is_expected.to be false }
end
context 'with child node the scope does not include' do
let(:target_node) { ast.each_node.find(&:self_type?) }
it { is_expected.to be false }
end
context 'with child node the scope includes' do
let(:target_node) { ast.each_node.find(&:send_type?) }
it { is_expected.to be true }
end
context 'with descendant node the scope does not include' do
let(:target_node) { ast.each_node.find(&:lvasgn_type?) }
it { is_expected.to be false }
end
end
describe '#each_node' do
shared_examples 'yields' do |description|
it "yields #{description}" do
yielded_types = []
scope.each_node { |node| yielded_types << node.type }
expect(yielded_types).to eq(expected_types.map(&:to_sym))
end
end
describe 'outer scope boundary handling' do
context 'when the scope is instance method' do
let(:source) { <<~RUBY }
def some_method(arg1, arg2)
:body
end
RUBY
let(:scope_node_type) { :def }
let(:expected_types) { %w[args arg arg sym] }
it_behaves_like 'yields', 'the argument and the body nodes'
end
context 'when the scope is singleton method' do
let(:source) { <<~RUBY }
def self.some_method(arg1, arg2)
:body
end
RUBY
let(:scope_node_type) { :defs }
let(:expected_types) { %w[args arg arg sym] }
it_behaves_like 'yields', 'the argument and the body nodes'
end
context 'when the scope is module' do
let(:source) { <<~RUBY }
module SomeModule
:body
end
RUBY
let(:scope_node_type) { :module }
let(:expected_types) { %w[sym] }
it_behaves_like 'yields', 'the body nodes'
end
context 'when the scope is class' do
let(:source) { <<~RUBY }
some_super_class = Class.new
class SomeClass < some_super_class
:body
end
RUBY
let(:scope_node_type) { :class }
let(:expected_types) { %w[sym] }
it_behaves_like 'yields', 'the body nodes'
end
context 'when the scope is singleton class' do
let(:source) { <<~RUBY }
some_object = Object.new
class << some_object
:body
end
RUBY
let(:scope_node_type) { :sclass }
let(:expected_types) { %w[sym] }
it_behaves_like 'yields', 'the body nodes'
end
context 'when the scope is block' do
let(:source) { <<~RUBY }
1.times do |arg1, arg2|
:body
end
RUBY
let(:scope_node_type) { :block }
let(:expected_types) { %w[args arg arg sym] }
it_behaves_like 'yields', 'the argument and the body nodes'
end
context 'when the scope is top level' do
let(:source) { <<~RUBY }
:body
RUBY
let(:scope_node_type) { :sym }
let(:expected_types) { %w[sym] }
it_behaves_like 'yields', 'the body nodes'
end
end
describe 'inner scope boundary handling' do
context "when there's a method invocation with block" do
let(:source) { <<~RUBY }
foo = 1
do_something(1, 2) do |arg|
:body
end
foo
RUBY
let(:scope_node_type) { :begin }
let(:expected_types) { %w[begin lvasgn int block send int int lvar] }
it_behaves_like 'yields', 'only the block node and the child send node'
end
context "when there's a singleton method definition" do
let(:source) { <<~RUBY }
foo = 1
def self.some_method(arg1, arg2)
:body
end
foo
RUBY
let(:scope_node_type) { :begin }
let(:expected_types) { %w[begin lvasgn int defs self lvar] }
it_behaves_like 'yields', 'only the defs node and the method host node'
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/variable_force/variable_spec.rb | spec/rubocop/cop/variable_force/variable_spec.rb | # frozen_string_literal: true
require 'rubocop/ast/sexp'
RSpec.describe RuboCop::Cop::VariableForce::Variable do
include RuboCop::AST::Sexp
describe '.new' do
context 'when non variable declaration node is passed' do
it 'raises error' do
name = :foo
declaration_node = s(:def)
scope = RuboCop::Cop::VariableForce::Scope.new(s(:class))
expect { described_class.new(name, declaration_node, scope) }.to raise_error(ArgumentError)
end
end
end
describe '#referenced?' do
subject { variable.referenced? }
let(:name) { :foo }
let(:declaration_node) { s(:arg, name) }
let(:scope) { instance_double(RuboCop::Cop::VariableForce::Scope).as_null_object }
let(:variable) { described_class.new(name, declaration_node, scope) }
context 'when the variable is not assigned' do
it { is_expected.to be(false) }
context 'and the variable is referenced' do
before { variable.reference!(s(:lvar, name)) }
it { is_expected.to be(true) }
end
end
context 'when the variable has an assignment' do
before { variable.assign(s(:lvasgn, name)) }
context 'and the variable is not yet referenced' do
it { is_expected.to be(false) }
end
context 'and the variable is referenced' do
before { variable.reference!(s(:lvar, name)) }
it { is_expected.to be(true) }
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/variable_force/variable_table_spec.rb | spec/rubocop/cop/variable_force/variable_table_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::VariableForce::VariableTable do
include RuboCop::AST::Sexp
subject(:variable_table) { described_class.new }
describe '#push_scope' do
it 'returns pushed scope object' do
node = s(:def)
scope = variable_table.push_scope(node)
expect(scope).to equal(variable_table.current_scope)
expect(scope.node).to equal(node)
end
end
describe '#pop_scope' do
before do
node = s(:def)
variable_table.push_scope(node)
end
it 'returns popped scope object' do
last_scope = variable_table.current_scope
popped_scope = variable_table.pop_scope
expect(popped_scope).to equal(last_scope)
end
end
describe '#current_scope_level' do
before { variable_table.push_scope(s(:def)) }
it 'increases by pushing scope' do
last_scope_level = variable_table.current_scope_level
variable_table.push_scope(s(:def))
expect(variable_table.current_scope_level).to eq(last_scope_level + 1)
end
it 'decreases by popping scope' do
last_scope_level = variable_table.current_scope_level
variable_table.pop_scope
expect(variable_table.current_scope_level).to eq(last_scope_level - 1)
end
end
describe '#declare_variable' do
before do
2.times do
node = s(:def)
variable_table.push_scope(node)
end
end
it 'adds variable to current scope with its name as key' do
node = s(:lvasgn, :foo)
variable_table.declare_variable(:foo, node)
expect(variable_table.current_scope.variables).to be_key(:foo)
expect(variable_table.scope_stack[-2].variables).to be_empty
variable = variable_table.current_scope.variables[:foo]
expect(variable.declaration_node).to equal(node)
end
it 'returns the added variable' do
node = s(:lvasgn, :foo)
variable = variable_table.declare_variable(:foo, node)
expect(variable.declaration_node).to equal(node)
end
end
describe '#find_variable' do
before do
variable_table.push_scope(s(:class))
variable_table.declare_variable(:baz, s(:lvasgn, :baz))
variable_table.push_scope(s(:def))
variable_table.declare_variable(:bar, s(:lvasgn, :bar))
end
context 'when current scope is block' do
before { variable_table.push_scope(s(:block)) }
context 'when a variable with the target name exists in current scope' do
before { variable_table.declare_variable(:foo, s(:lvasgn, :foo)) }
context 'and does not exist in outer scope' do
it 'returns the current scope variable' do
found_variable = variable_table.find_variable(:foo)
expect(found_variable.name).to eq(:foo)
end
end
context 'and also exists in outer scope' do
before { variable_table.declare_variable(:bar, s(:lvasgn, :bar)) }
it 'returns the current scope variable' do
found_variable = variable_table.find_variable(:bar)
expect(found_variable.name).to equal(:bar)
expect(variable_table.current_scope.variables).to be_value(found_variable)
expect(variable_table.scope_stack[-2].variables).not_to be_value(found_variable)
end
end
end
context 'when a variable with the target name does not exist in current scope' do
context 'but exists in the direct outer scope' do
it 'returns the direct outer scope variable' do
found_variable = variable_table.find_variable(:bar)
expect(found_variable.name).to equal(:bar)
end
end
context 'but exists in a indirect outer scope' do
context 'when the direct outer scope is block' do
before do
variable_table.pop_scope
variable_table.pop_scope
variable_table.push_scope(s(:block))
variable_table.push_scope(s(:block))
end
it 'returns the indirect outer scope variable' do
found_variable = variable_table.find_variable(:baz)
expect(found_variable.name).to equal(:baz)
end
end
context 'when the direct outer scope is not block' do
it 'returns nil' do
found_variable = variable_table.find_variable(:baz)
expect(found_variable).to be_nil
end
end
end
context 'and does not exist in all outer scopes' do
it 'returns nil' do
found_variable = variable_table.find_variable(:non)
expect(found_variable).to be_nil
end
end
end
end
context 'when current scope is not block' do
before { variable_table.push_scope(s(:def)) }
context 'when a variable with the target name exists in current scope' do
before { variable_table.declare_variable(:foo, s(:lvasgn, :foo)) }
context 'and does not exist in outer scope' do
it 'returns the current scope variable' do
found_variable = variable_table.find_variable(:foo)
expect(found_variable.name).to eq(:foo)
end
end
context 'and also exists in outer scope' do
it 'returns the current scope variable' do
found_variable = variable_table.find_variable(:foo)
expect(found_variable.name).to equal(:foo)
expect(variable_table.current_scope.variables).to be_value(found_variable)
expect(variable_table.scope_stack[-2].variables).not_to be_value(found_variable)
end
end
end
context 'when a variable with the target name does not exist in current scope' do
context 'but exists in the direct outer scope' do
it 'returns nil' do
found_variable = variable_table.find_variable(:bar)
expect(found_variable).to be_nil
end
end
context 'and does not exist in all outer scopes' do
it 'returns nil' do
found_variable = variable_table.find_variable(:non)
expect(found_variable).to be_nil
end
end
end
end
end
describe '#find_variable with an empty scope stack' do
it 'returns nil' do
found_variable = variable_table.find_variable(:unknown)
expect(found_variable).to be_nil
end
end
describe '#accessible_variables' do
let(:accessible_variable_names) { variable_table.accessible_variables.map(&:name) }
before { variable_table.push_scope(s(:class)) }
context 'when there are no variables' do
it 'returns empty array' do
expect(variable_table.accessible_variables).to be_empty
end
end
context 'when the current scope has some variables' do
before do
variable_table.declare_variable(:foo, s(:lvasgn, :foo))
variable_table.declare_variable(:bar, s(:lvasgn, :bar))
end
it 'returns all the variables' do
expect(accessible_variable_names).to contain_exactly(:foo, :bar)
end
end
context 'when the direct outer scope has some variables' do
before { variable_table.declare_variable(:foo, s(:lvasgn, :foo)) }
context 'and the current scope is block' do
before do
variable_table.push_scope(s(:block))
variable_table.declare_variable(:bar, s(:lvasgn, :bar))
variable_table.declare_variable(:baz, s(:lvasgn, :baz))
end
it 'returns the current and direct outer scope variables' do
expect(accessible_variable_names).to contain_exactly(:foo, :bar, :baz)
end
end
context 'and the current scope is not block' do
before do
variable_table.push_scope(s(:def))
variable_table.declare_variable(:bar, s(:lvasgn, :bar))
variable_table.declare_variable(:baz, s(:lvasgn, :baz))
end
it 'returns only the current scope variables' do
expect(accessible_variable_names).to contain_exactly(:bar, :baz)
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/variable_force/assignment_spec.rb | spec/rubocop/cop/variable_force/assignment_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::VariableForce::Assignment do
include RuboCop::AST::Sexp
let(:ast) { RuboCop::ProcessedSource.new(source, ruby_version, parser_engine: parser_engine).ast }
let(:source) do
<<~RUBY
class SomeClass
def some_method(flag)
puts 'Hello World!'
if flag > 0
foo = 1
end
end
end
RUBY
end
let(:def_node) { ast.each_node.find(&:def_type?) }
let(:lvasgn_node) { ast.each_node.find(&:lvasgn_type?) }
let(:name) { lvasgn_node.name }
let(:scope) { RuboCop::Cop::VariableForce::Scope.new(def_node) }
let(:variable) { RuboCop::Cop::VariableForce::Variable.new(name, lvasgn_node, scope) }
let(:assignment) { described_class.new(lvasgn_node, variable) }
describe '.new' do
let(:variable) { instance_double(RuboCop::Cop::VariableForce::Variable) }
context 'when an assignment node is passed' do
it 'does not raise error' do
node = s(:lvasgn, :foo)
expect { described_class.new(node, variable) }.not_to raise_error
end
end
context 'when an argument declaration node is passed' do
it 'raises error' do
node = s(:arg, :foo)
expect { described_class.new(node, variable) }.to raise_error(ArgumentError)
end
end
context 'when any other type node is passed' do
it 'raises error' do
node = s(:def)
expect { described_class.new(node, variable) }.to raise_error(ArgumentError)
end
end
end
describe '#name' do
it 'returns the variable name' do
expect(assignment.name).to eq(:foo)
end
end
describe '#meta_assignment_node' do
context 'when it is += operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo += 1
end
RUBY
end
it 'returns op_asgn node' do
expect(assignment.meta_assignment_node.type).to eq(:op_asgn)
end
end
context 'when it is ||= operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo ||= 1
end
RUBY
end
it 'returns or_asgn node' do
expect(assignment.meta_assignment_node.type).to eq(:or_asgn)
end
end
context 'when it is &&= operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo &&= 1
end
RUBY
end
it 'returns and_asgn node' do
expect(assignment.meta_assignment_node.type).to eq(:and_asgn)
end
end
context 'when it is multiple assignment' do
let(:source) do
<<~RUBY
def some_method
foo, bar = [1, 2]
end
RUBY
end
it 'returns masgn node' do
expect(assignment.meta_assignment_node.type).to eq(:masgn)
end
end
context 'when it is rest assignment' do
let(:source) do
<<~RUBY
def some_method
*foo = [1, 2]
end
RUBY
end
it 'returns masgn node' do
expect(assignment.meta_assignment_node.type).to eq(:masgn)
end
end
context 'when it is `for` assignment' do
let(:source) do
<<~RUBY
def some_method
for item in items
end
end
RUBY
end
it 'returns splat node' do
expect(assignment.meta_assignment_node.type).to eq(:for)
end
end
context 'when it is an argument of a send node' do
# The `lvasgn` in question in this `context` is the one inside a call to `my_method`.
let(:lvasgn_node) { ast.each_node.to_a.reverse.find(&:lvasgn_type?) }
context 'when it is += operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo += my_method(bar = 1)
end
RUBY
end
it 'returns nil' do
expect(assignment.meta_assignment_node).to be_nil
end
end
context 'when it is ||= operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo ||= my_method(bar = 1)
end
RUBY
end
it 'returns nil' do
expect(assignment.meta_assignment_node).to be_nil
end
end
context 'when it is &&= operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo &&= my_method(bar = 1)
end
RUBY
end
it 'returns nil' do
expect(assignment.meta_assignment_node).to be_nil
end
end
context 'with multiple assignment' do
let(:source) do
<<~RUBY
def some_method
foo, baz = my_method(bar = 1)
end
RUBY
end
it 'returns nil' do
expect(assignment.meta_assignment_node).to be_nil
end
end
context 'when it is multiple assignment inside multiple assignment' do
let(:source) do
<<~RUBY
def some_method
foo, bar = my_method((baz, quux = [1, 2]))
end
RUBY
end
it 'returns masgn node' do
expect(assignment.meta_assignment_node.type).to eq(:masgn)
end
end
context 'when it is rest assignment' do
let(:source) do
<<~RUBY
def some_method
*foo = my_method(bar = 1)
end
RUBY
end
it 'returns nil' do
expect(assignment.meta_assignment_node).to be_nil
end
end
context 'when it is `for` assignment' do
let(:source) do
<<~RUBY
def some_method
for item in my_method(bar = 1)
end
end
RUBY
end
it 'returns nil' do
expect(assignment.meta_assignment_node).to be_nil
end
end
end
end
describe '#operator' do
context 'when it is normal assignment' do
let(:source) do
<<~RUBY
def some_method
foo = 1
end
RUBY
end
it 'returns =' do
expect(assignment.operator).to eq('=')
end
end
context 'when it is += operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo += 1
end
RUBY
end
it 'returns +=' do
expect(assignment.operator).to eq('+=')
end
end
context 'when it is ||= operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo ||= 1
end
RUBY
end
it 'returns ||=' do
expect(assignment.operator).to eq('||=')
end
end
context 'when it is &&= operator assignment' do
let(:source) do
<<~RUBY
def some_method
foo &&= 1
end
RUBY
end
it 'returns &&=' do
expect(assignment.operator).to eq('&&=')
end
end
context 'when it is multiple assignment' do
let(:source) do
<<~RUBY
def some_method
foo, bar = [1, 2]
end
RUBY
end
it 'returns =' do
expect(assignment.operator).to eq('=')
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/server/rubocop_server_spec.rb | spec/rubocop/server/rubocop_server_spec.rb | # frozen_string_literal: true
require 'open3'
RSpec.describe 'rubocop --server', :isolated_environment do # rubocop:disable RSpec/DescribeClass
let(:rubocop) { "#{RuboCop::ConfigLoader::RUBOCOP_HOME}/exe/rubocop" }
include_context 'cli spec behavior'
before do
# Makes sure the project dir of rubocop server is the isolated_environment
create_empty_file('Gemfile')
end
after do
`ruby -I . "#{rubocop}" --stop-server`
end
if RuboCop::Server.support_server?
context 'when using `--server` option after updating RuboCop' do
it 'displays a restart information message' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
NewCops: disable
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
create_file('Gemfile', <<~RUBY)
# frozen_string_literal: true
RUBY
options = '--server --only Style/FrozenStringLiteralComment,Style/StringLiterals'
expect(`ruby -I . "#{rubocop}" #{options}`).to start_with('RuboCop server starting on')
# Emulate the server starting with an older RuboCop version.
stub_const('RuboCop::Version::STRING', '0.0.1')
RuboCop::Server::Cache.write_version_file(RuboCop::Server::Cache.restart_key)
expect(`ruby -I . "#{rubocop}" --server-status`).to match(/RuboCop server .* is running/)
_stdout, stderr, _status = Open3.capture3("ruby -I . \"#{rubocop}\" #{options}")
expect(stderr).to start_with(
'RuboCop version incompatibility found, RuboCop server restarting...'
)
end
end
context 'when using --config option after update specified config file' do
it 'displays a restart information message' do
create_file('.rubocop_todo.yml', <<~YAML)
AllCops:
NewCops: enable
SuggestExtensions: false
Layout/LineLength:
Max: 100
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
options = '--server --only Style/StringLiterals --config .rubocop_todo.yml example.rb'
`ruby -I . \"#{rubocop}\" #{options}`
# Update .rubocop_todo.yml
create_file('.rubocop_todo.yml', <<~YAML)
AllCops:
NewCops: enable
SuggestExtensions: false
Layout/LineLength:
Max: 101
YAML
_stdout, stderr, _status = Open3.capture3("ruby -I . \"#{rubocop}\" #{options}")
expect(stderr).to start_with(
'RuboCop version incompatibility found, RuboCop server restarting...'
)
end
end
context 'when using `--server` with `--stderr`' do
it 'sends corrected source to stdout and rest to stderr' do
create_file('example.rb', <<~RUBY)
puts 0
RUBY
stdout, stderr, status = Open3.capture3(
'ruby', '-I', '.',
rubocop, '--no-color', '--server', '--stderr', '-A',
'--stdin', 'example.rb',
stdin_data: 'puts 0'
)
expect(status).to be_success
expect(stdout).to eq(<<~RUBY)
# frozen_string_literal: true
puts 0
RUBY
expect(stderr)
.to include('[Corrected] Style/FrozenStringLiteralComment')
.and include('[Corrected] Layout/EmptyLineAfterMagicComment')
end
end
context 'when using `--server` and json is specified as the format' do
context 'when `--format=json`' do
it 'does not display the server start message' do
create_file('example.rb', <<~RUBY)
puts 0
RUBY
stdout, _stderr, _status = Open3.capture3(
'ruby', '-I', '.',
rubocop, '--server', '--format=json', '--stdin', 'example.rb', stdin_data: 'puts 0'
)
expect(stdout).not_to start_with 'RuboCop server starting on '
end
end
context 'when `--format=j`' do
it 'does not display the server start message' do
create_file('example.rb', <<~RUBY)
puts 0
RUBY
stdout, _stderr, _status = Open3.capture3(
'ruby', '-I', '.',
rubocop, '--server', '--format=j', '--stdin', 'example.rb', stdin_data: 'puts 0'
)
expect(stdout).not_to start_with 'RuboCop server starting on '
end
end
context 'when `--format json`' do
it 'does not display the server start message' do
create_file('example.rb', <<~RUBY)
puts 0
RUBY
stdout, _stderr, _status = Open3.capture3(
'ruby', '-I', '.',
rubocop, '--server', '--format', 'json', '--stdin', 'example.rb', stdin_data: 'puts 0'
)
expect(stdout).not_to start_with 'RuboCop server starting on '
end
end
context 'when `--format j`' do
it 'does not display the server start message' do
create_file('example.rb', <<~RUBY)
puts 0
RUBY
stdout, _stderr, _status = Open3.capture3(
'ruby', '-I', '.',
rubocop, '--server', '--format', 'j', '--stdin', 'example.rb', stdin_data: 'puts 0'
)
expect(stdout).not_to start_with 'RuboCop server starting on '
end
end
context 'when `-f json`' do
it 'does not display the server start message' do
create_file('example.rb', <<~RUBY)
puts 0
RUBY
stdout, _stderr, _status = Open3.capture3(
'ruby', '-I', '.',
rubocop, '--server', '-f', 'json', '--stdin', 'example.rb', stdin_data: 'puts 0'
)
expect(stdout).not_to start_with 'RuboCop server starting on '
end
end
context 'when `-f j`' do
it 'does not display the server start message' do
create_file('example.rb', <<~RUBY)
puts 0
RUBY
stdout, _stderr, _status = Open3.capture3(
'ruby', '-I', '.',
rubocop, '--server', '-f', 'j', '--stdin', 'example.rb', stdin_data: 'puts 0'
)
expect(stdout).not_to start_with 'RuboCop server starting on '
end
end
end
context 'when using `--server` option after running server and updating configuration' do
it 'applies .rubocop.yml configuration changes even during server startup' do
create_file('example.rb', <<~RUBY)
x = 0
puts x
RUBY
create_file('Gemfile', <<~RUBY)
# frozen_string_literal: true
RUBY
# Disable `Style/FrozenStringLiteralComment` cop.
create_file('.rubocop.yml', <<~YAML)
AllCops:
NewCops: enable
SuggestExtensions: false
Style/FrozenStringLiteralComment:
Enabled: false
YAML
message = expect(`ruby -I . "#{rubocop}" --server`)
message.to start_with('RuboCop server starting on ')
message.to include('no offenses')
RuboCop::Server.wait_for_running_status!(true)
debug_output = [
'After server start',
RuboCop::Server.running?,
`ruby -I . "#{rubocop}" --server-status`,
`tail #{RuboCop::Server::Cache.dir}/*`,
`ps aux`,
`env | grep HOME`,
Dir.home,
`ruby -I . -e 'require "rubocop/server"; puts RuboCop::Server::Cache.dir'`
]
expect(`ruby -I . "#{rubocop}" --server-status`).to(
match(/RuboCop server .* is running/), debug_output.join("\n")
)
# Enable `Style/FrozenStringLiteralComment` cop.
create_file('.rubocop.yml', <<~YAML)
AllCops:
NewCops: enable
SuggestExtensions: false
Style/FrozenStringLiteralComment:
Enabled: true
YAML
debug_output += [
'After create file',
RuboCop::Server.running?,
`ruby -I . "#{rubocop}" --server-status`,
`tail #{RuboCop::Server::Cache.dir}/*`,
`ps aux`,
`env | grep HOME`,
Dir.home,
`ruby -I . -e 'require "rubocop/server"; puts RuboCop::Server::Cache.dir'`
]
expect(`ruby -I . "#{rubocop}" --server-status`).to(
match(/RuboCop server .* is running/), debug_output.join("\n")
)
# Recompute the cache key with the modified .rubocop.yml content.
RuboCop::Server::Cache.write_version_file(RuboCop::Server::Cache.restart_key)
message = expect(`ruby -I . "#{rubocop}" --server`)
message.not_to start_with('RuboCop server starting on '), debug_output.join("\n")
message.to include(<<~OFFENSE_DETECTED)
Style/FrozenStringLiteralComment: Missing frozen string literal comment.
OFFENSE_DETECTED
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/server/cli_spec.rb | spec/rubocop/server/cli_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Server::CLI, :isolated_environment do
subject(:cli) { described_class.new }
include_context 'cli spec behavior'
if RuboCop::Server.support_server?
before do
allow_any_instance_of(RuboCop::Server::Core).to receive(:server_mode?).and_return(false) # rubocop:disable RSpec/AnyInstance
end
after do
RuboCop::Server::ClientCommand::Stop.new.run
end
context 'when using `--server` option' do
it 'returns exit status 0 and display an information message' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--server', '--format', 'simple', 'example.rb'])).to eq(0)
expect(cli).not_to be_exit
expect($stdout.string).to start_with 'RuboCop server starting on '
expect($stderr.string).to eq ''
end
end
context 'when using `--no-server` option' do
it 'returns exit status 0' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--no-server', '--format', 'simple', 'example.rb'])).to eq(0)
expect(cli).not_to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq ''
end
end
context 'when using `--start-server` option' do
it 'returns exit status 0 and display an information message' do
expect(cli.run(['--start-server'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to start_with 'RuboCop server starting on '
expect($stderr.string).to eq ''
end
end
context 'when using `--start-server` option with `--no-detach`' do
it 'returns exit status 0 and display an information message' do
expect(cli.run(['--start-server', '--no-detach'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to match(/RuboCop server starting on/)
expect($stderr.string).to eq ''
end
end
context 'when using `--stop-server` option' do
it 'returns exit status 0 and display a warning message' do
expect(cli.run(['--stop-server'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "RuboCop server is not running.\n"
end
end
context 'when using `--restart-server` option' do
it 'returns exit status 0 and display an information and a warning messages' do
expect(cli.run(['--restart-server'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to start_with 'RuboCop server starting on '
expect($stderr.string).to eq "RuboCop server is not running.\n"
end
end
context 'when using `--restart-server` option with `--no-detach`' do
it 'returns exit status 0 and display an information message' do
expect(cli.run(['--restart-server', '--no-detach'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to match(/RuboCop server starting on/)
expect($stderr.string).to eq "RuboCop server is not running.\n"
end
end
context 'when using `--server-status` option' do
it 'returns exit status 0 and display an information message' do
expect(cli.run(['--server-status'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to eq "RuboCop server is not running.\n"
expect($stderr.string).to eq ''
end
end
context 'when not using any server options' do
it 'returns exit status 0' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(0)
expect(cli).not_to be_exit
expect($stdout.string).to be_blank
expect($stderr.string).to be_blank
end
end
context 'when not using any server options and specifying `--server` in .rubocop file' do
before { create_file('.rubocop', '--server') }
it 'returns exit status 0 and display an information message' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(0)
expect(cli).not_to be_exit
expect($stdout.string).to start_with 'RuboCop server starting on '
expect($stderr.string).to eq ''
end
end
context 'when not using any server options and specifying `--server` in `RUBOCOP_OPTS` environment variable' do
around do |example|
ENV['RUBOCOP_OPTS'] = '--server'
begin
example.run
ensure
ENV.delete('RUBOCOP_OPTS')
end
end
it 'returns exit status 0 and display an information message' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(0)
expect(cli).not_to be_exit
expect($stdout.string).to start_with 'RuboCop server starting on '
expect($stderr.string).to eq ''
end
end
context 'when using multiple server options' do
it 'returns exit status 2 and display an error message' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--server', '--no-server', '--format', 'simple', 'example.rb'])).to eq(2)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "--server, --no-server cannot be specified together.\n"
end
end
context 'when using exclusive `--restart-server` option' do
it 'returns exit status 2 and display an error message' do
expect(cli.run(['--restart-server', '--format', 'simple'])).to eq(2)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "--restart-server cannot be combined with --format.\n"
end
end
context 'when using exclusive `--start-server` option' do
it 'returns exit status 2 and display an error message' do
expect(cli.run(['--start-server', '--format', 'simple'])).to eq(2)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "--start-server cannot be combined with --format.\n"
end
end
context 'when using exclusive `--stop-server` option' do
it 'returns exit status 2 and display an error message' do
expect(cli.run(['--stop-server', '--format', 'simple'])).to eq(2)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "--stop-server cannot be combined with --format.\n"
end
end
context 'when using exclusive `--server-status` option' do
it 'returns exit status 2 and display an error message' do
expect(cli.run(['--server-status', '--format', 'simple'])).to eq(2)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "--server-status cannot be combined with --format.\n"
end
end
context 'when using server option with `--no-detach` option' do
it 'returns exit status 2 and display an error message' do
expect(cli.run(['--server-status', '--no-detach'])).to eq(2)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "--server-status cannot be combined with --no-detach.\n"
end
end
context 'when using server option with `--cache-root path` option' do
it 'returns exit status 0 and display an error message' do
expect(cli.run(['--server-status', '--cache-root', '/tmp'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to eq "RuboCop server is not running.\n"
expect($stderr.string).not_to eq "--server-status cannot be combined with --cache-root.\n"
end
end
context 'when using server option with `--cache-root=path` option' do
it 'returns exit status 0 and display an information message' do
expect(cli.run(['--server-status', '--cache-root=/tmp'])).to eq(0)
expect(cli).to be_exit
expect($stdout.string).to eq "RuboCop server is not running.\n"
expect($stderr.string).not_to eq "--server-status cannot be combined with --cache-root.\n"
end
end
else
context 'when using `--server` option' do
it 'returns exit status 2 and display an error message' do
expect(cli.run(['--server', '--format', 'simple'])).to eq(2)
expect(cli).to be_exit
expect($stdout.string).to eq ''
expect($stderr.string).to eq "RuboCop server is not supported by this Ruby.\n"
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/server/cache_spec.rb | spec/rubocop/server/cache_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Server::Cache do
subject(:cache_class) { described_class }
include_context 'cli spec behavior'
describe '.cache_path' do
context 'when cache root path is not specified as default' do
before do
cache_class.cache_root_path = nil
end
it 'is the default path' do
expect(cache_class.cache_path).to eq("#{Dir.home}/.cache/rubocop_cache/server")
end
end
context 'when cache root path is specified path' do
before do
cache_class.cache_root_path = '/tmp'
end
it 'is the specified path' do
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq('D:/tmp/rubocop_cache/server')
else
expect(cache_class.cache_path).to eq('/tmp/rubocop_cache/server')
end
end
end
context 'when `CacheRootDirectory` configure value is not set', :isolated_environment do
after { cache_class.cache_path }
it 'does not require `erb` and `yaml`' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
DisabledByDefault: true
YAML
expect(described_class).not_to receive(:require).with('erb')
expect(described_class).not_to receive(:require).with('yaml')
end
end
context 'when `CacheRootDirectory` configure value is set', :isolated_environment do
context 'when cache root path is not specified path' do
let(:cache_path) { File.join('/tmp/cache-root-directory', 'rubocop_cache', 'server') }
before do
cache_class.cache_root_path = nil
end
it 'contains the root from `CacheRootDirectory` configure value' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
CacheRootDirectory: '/tmp/cache-root-directory'
YAML
expect(described_class).to receive(:require).with('erb')
expect(described_class).to receive(:require).with('yaml')
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(cache_path.prepend('D:'))
else
expect(cache_class.cache_path).to eq(cache_path)
end
end
end
context 'when cache root path is not specified path and `XDG_CACHE_HOME` environment variable is specified' do
let(:cache_path) { File.join('/tmp/cache-root-directory', 'rubocop_cache', 'server') }
around do |example|
cache_class.cache_root_path = nil
ENV['XDG_CACHE_HOME'] = '/tmp/cache-from-xdg-env'
begin
example.run
ensure
ENV.delete('XDG_CACHE_HOME')
end
end
it 'contains the root from `CacheRootDirectory` configure value' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
CacheRootDirectory: '/tmp/cache-root-directory'
YAML
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(cache_path.prepend('D:'))
else
expect(cache_class.cache_path).to eq(cache_path)
end
end
end
context 'when cache root path is specified path' do
before do
cache_class.cache_root_path = '/tmp'
end
it 'contains the root from cache root path' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
CacheRootDirectory: '/tmp/cache-root-directory'
YAML
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(File.join('D:/tmp', 'rubocop_cache', 'server'))
else
expect(cache_class.cache_path).to eq(File.join('/tmp', 'rubocop_cache', 'server'))
end
end
end
end
context 'when `RUBOCOP_CACHE_ROOT` environment variable is set' do
around do |example|
ENV['RUBOCOP_CACHE_ROOT'] = '/tmp/rubocop-cache-root-env'
begin
example.run
ensure
ENV.delete('RUBOCOP_CACHE_ROOT')
end
end
context 'when cache root path is not specified path' do
let(:cache_path) { File.join('/tmp/rubocop-cache-root-env', 'rubocop_cache', 'server') }
before do
cache_class.cache_root_path = nil
end
it 'contains the root from `RUBOCOP_CACHE_ROOT`' do
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(cache_path.prepend('D:'))
else
expect(cache_class.cache_path).to eq(cache_path)
end
end
end
context 'when cache root path is not specified path and `XDG_CACHE_HOME` environment variable is specified' do
let(:cache_path) { File.join('/tmp/rubocop-cache-root-env', 'rubocop_cache', 'server') }
around do |example|
cache_class.cache_root_path = nil
ENV['XDG_CACHE_HOME'] = '/tmp/cache-from-xdg-env'
begin
example.run
ensure
ENV.delete('XDG_CACHE_HOME')
end
end
it 'contains the root from `RUBOCOP_CACHE_ROOT`' do
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(cache_path.prepend('D:'))
else
expect(cache_class.cache_path).to eq(cache_path)
end
end
end
context 'when cache root path is specified path' do
before do
cache_class.cache_root_path = '/tmp'
end
it 'contains the root from cache root path' do
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(File.join('D:/tmp', 'rubocop_cache', 'server'))
else
expect(cache_class.cache_path).to eq(File.join('/tmp', 'rubocop_cache', 'server'))
end
end
end
end
context 'when `XDG_CACHE_HOME` environment variable is set' do
around do |example|
ENV['XDG_CACHE_HOME'] = '/tmp/cache-from-xdg-env'
begin
example.run
ensure
ENV.delete('XDG_CACHE_HOME')
end
end
context 'when cache root path is not specified path' do
let(:puid) { Process.uid.to_s }
let(:cache_path) { File.join('/tmp/cache-from-xdg-env', puid, 'rubocop_cache', 'server') }
before do
cache_class.cache_root_path = nil
end
it 'contains the root from `XDG_CACHE_HOME`' do
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(cache_path.prepend('D:'))
else
expect(cache_class.cache_path).to eq(cache_path)
end
end
end
context 'when cache root path is specified path' do
before do
cache_class.cache_root_path = '/tmp'
end
it 'contains the root from cache root path' do
if RuboCop::Platform.windows?
expect(cache_class.cache_path).to eq(File.join('D:/tmp', 'rubocop_cache', 'server'))
else
expect(cache_class.cache_path).to eq(File.join('/tmp', 'rubocop_cache', 'server'))
end
end
end
end
context 'when .rubocop.yml is empty', :isolated_environment do
context 'when cache root path is not specified path' do
before do
cache_class.cache_root_path = nil
end
it 'does not raise an error' do
create_empty_file('.rubocop.yml')
expect { cache_class.cache_path }.not_to raise_error
end
end
end
context 'when ERB pre-processing of the configuration file', :isolated_environment do
context 'when cache root path is not specified path' do
before do
cache_class.cache_root_path = nil
end
it 'does not raise an error' do
create_file('.rubocop.yml', <<~YAML)
Style/Encoding:
Enabled: <%= 1 == 1 %>
Exclude:
<% Dir['*.rb'].sort.each do |name| %>
- <%= name %>
<% end %>
YAML
expect { cache_class.cache_path }.not_to raise_error
end
end
end
context 'when using YAML alias in .rubocop.yml', :isolated_environment do
it 'does not raise an error' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Style/StringLiterals: &config
Enable: true
Style/HashSyntax:
<<: *config
YAML
expect { cache_class.cache_path }.not_to raise_error
end
end
end
unless RuboCop::Platform.windows?
describe '.restart_key', :isolated_environment do
subject(:restart_key) do
described_class.restart_key(args_config_file_path: args_config_file_path)
end
let(:args_config_file_path) { nil }
let(:hexdigest) do
Digest::SHA1.hexdigest(contents)
end
context 'when a local path is used in `inherit_from` of .rubocop.yml' do
let(:contents) do
RuboCop::Version::STRING + File.read('.rubocop.yml') + File.read('.rubocop_todo.yml')
end
before do
create_file('.rubocop_todo.yml', <<~YAML)
Metrics/ClassLength:
Max: 192
YAML
end
context 'when `inherit_from` is specified as a string path' do
before do
create_file('.rubocop.yml', <<~YAML)
inherit_from: .rubocop_todo.yml
YAML
end
it { expect(restart_key).to eq(hexdigest) }
end
context 'when `inherit_from` is specified as an array path' do
before do
create_file('.rubocop.yml', <<~YAML)
inherit_from:
- .rubocop_todo.yml
YAML
end
it { expect(restart_key).to eq(hexdigest) }
end
end
context 'when a remote path is used in `inherit_from` of .rubocop.yml' do
let(:contents) do
RuboCop::Version::STRING + File.read('.rubocop.yml')
end
context 'when `inherit_from` is specified as a string path' do
before do
create_file('.rubocop.yml', <<~YAML)
inherit_from: https://example.com
YAML
end
it { expect(restart_key).to eq(hexdigest) }
end
end
context 'when a local path is used in `require` of .rubocop.yml' do
let(:contents) do
RuboCop::Version::STRING + File.read('.rubocop.yml') + File.read('local_file.rb')
end
before do
create_file('local_file.rb', <<~RUBY)
do_something
RUBY
end
context 'when `inherit_from` is specified as a string path' do
before do
create_file('.rubocop.yml', <<~YAML)
require: ./local_file
YAML
end
it { expect(restart_key).to eq(hexdigest) }
end
context 'when `inherit_from` is specified as an array path' do
before do
create_file('.rubocop.yml', <<~YAML)
require:
./local_file
YAML
end
it { expect(restart_key).to eq(hexdigest) }
end
end
context 'when a load path may be used in `require` of .rubocop.yml' do
let(:contents) do
RuboCop::Version::STRING + File.read('.rubocop.yml')
end
context 'when `inherit_from` is specified as a string path' do
before do
create_file('.rubocop.yml', <<~YAML)
inherit_from: rubocop-performance
YAML
end
it { expect(restart_key).to eq(hexdigest) }
end
end
context 'when ERB pre-processing of the configuration file', :isolated_environment do
context 'when `CacheRootDirectory` configure value is set' do
it 'does not raise an error' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
CacheRootDirectory: '/tmp/cache-root-directory'
Style/Encoding:
Enabled: <%= 1 == 1 %>
Exclude:
<% Dir['*.rb'].sort.each do |name| %>
- <%= name %>
<% end %>
YAML
expect { restart_key }.not_to raise_error
end
end
end
context 'when args_config_file_path is specified' do
let(:args_config_file_path) { '.rubocop_todo.yml' }
let(:contents) do
RuboCop::Version::STRING + File.read('.rubocop_todo.yml')
end
before do
create_file('.rubocop_todo.yml', <<~YAML)
Metrics/ClassLength:
Max: 192
YAML
end
it { expect(restart_key).to eq(hexdigest) }
end
end
describe '.pid_running?', :isolated_environment do
it 'works properly when concurrency with server stopping and cleaning cache dir' do
expect(described_class).to receive(:pid_path).and_wrap_original do |method|
result = method.call
described_class.dir.rmtree # server stopping behavior
result
end
expect(described_class).not_to be_pid_running
end
it 'works properly when insufficient permissions to server cache dir are granted' do
expect(described_class).to receive(:pid_path).and_wrap_original do |method|
result = method.call
described_class.dir.chmod(0o644) # Make insufficient permissions.
result
end
expect(described_class).not_to be_pid_running
end
it 'works properly when the file system is read-only' do
expect(described_class).to receive(:pid_path).and_wrap_original do |method|
result = method.call
allow(result).to receive(:read).and_raise(Errno::EROFS)
result
end
expect(described_class).not_to be_pid_running
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/server/client_command/exec_spec.rb | spec/rubocop/server/client_command/exec_spec.rb | # frozen_string_literal: true
RSpec.describe RuboCop::Server::ClientCommand::Exec do
if RuboCop::Server.support_server?
it 'does not read from $stdin when -s/--stdin not specified' do
exec_command = described_class.new
expect(ARGV).to receive(:include?).with('-s').and_return(false)
expect(ARGV).to receive(:include?).with('--stdin').and_return(false)
expect(exec_command).to receive(:ensure_server!).and_return(nil)
expect(exec_command).to receive(:send_request).and_return(nil)
expect(exec_command).to receive(:stderr).and_return('')
expect(exec_command).to receive(:status).and_return(0)
allow($stdin).to receive(:tty?).and_return(false)
expect($stdin).not_to receive(:read)
exec_command.run
end
it 'reads from $stdin when -s/--stdin specified' do
exec_command = described_class.new
expect(ARGV).to receive(:include?).with('-s').and_return(true)
expect(exec_command).to receive(:ensure_server!).and_return(nil)
expect(exec_command).to receive(:send_request).and_return(nil)
expect(exec_command).to receive(:stderr).and_return('')
expect(exec_command).to receive(:status).and_return(0)
allow($stdin).to receive(:tty?).and_return(false)
expect($stdin).to receive(:read)
exec_command.run
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cli/autocorrect_spec.rb | spec/rubocop/cli/autocorrect_spec.rb | # frozen_string_literal: true
RSpec.describe 'RuboCop::CLI --autocorrect', :isolated_environment do # rubocop:disable RSpec/DescribeClass
subject(:cli) { RuboCop::CLI.new }
include_context 'cli spec behavior'
before do
RuboCop::ConfigLoader.default_configuration = nil
RuboCop::ConfigLoader.default_configuration.for_all_cops['SuggestExtensions'] = false
end
it 'does not correct ExtraSpacing in a hash that would be changed back' do
create_file('.rubocop.yml', <<~YAML)
Layout/HashAlignment:
EnforcedColonStyle: table
Lint/UselessAssignment:
Enabled: false
Style/FrozenStringLiteralComment:
Enabled: false
YAML
source = <<~RUBY
hash = {
alice: {
age: 23,
role: 'Director'
},
bob: {
age: 25,
role: 'Consultant'
}
}
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect-all'])).to eq(0)
expect(File.read('example.rb')).to eq(source)
end
it 'plays nicely with default cops in complex ExtraSpacing scenarios' do
create_file('.rubocop.yml', <<~YAML)
# These cops change indentation and thus need disabling in order for the
# ExtraSpacing rules to apply to this scenario.
Layout/BlockAlignment:
Enabled: false
Layout/ExtraSpacing:
ForceEqualSignAlignment: true
Layout/MultilineMethodCallBraceLayout:
Enabled: false
Lint/UselessAssignment:
Enabled: false
YAML
source = <<~RUBY
def batch
@areas = params[:param].map do
var_1 = 123_456
variable_2 = 456_123
end
@another = params[:param].map do
char_1 = begin
variable_1_1 = 'a'
variable_1_20 = 'b'
variable_1_300 = 'c'
# A Comment
variable_1_4000 = 'd'
variable_1_50000 = 'e'
puts 'a non-assignment statement without a blank line'
some_other_length_variable = 'f'
end
var_2 = 456_123
end
render json: @areas
end
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect-all'])).to eq(1)
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
def batch
@areas = params[:param].map do
var_1 = 123_456
variable_2 = 456_123
end
@another = params[:param].map do
char_1 = begin
variable_1_1 = 'a'
variable_1_20 = 'b'
variable_1_300 = 'c'
# A Comment
variable_1_4000 = 'd'
variable_1_50000 = 'e'
puts 'a non-assignment statement without a blank line'
some_other_length_variable = 'f'
end
var_2 = 456_123
end
render json: @areas
end
RUBY
end
it 'corrects `Layout/SpaceAroundOperators` and `Layout/ExtraSpacing` ' \
'offenses when using `ForceEqualSignAlignment: true`' do
create_file('.rubocop.yml', <<~YAML)
Layout/ExtraSpacing:
ForceEqualSignAlignment: true
Lint/UselessAssignment:
Enabled: false
YAML
create_file('example.rb', <<~RUBY)
test123456 = nil
test1234 = nil
test1_test2_test3_test4_12 =nil
RUBY
expect(cli.run(['--autocorrect-all'])).to eq(1)
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
test123456 = nil
test1234 = nil
test1_test2_test3_test4_12 = nil
RUBY
end
it 'does not correct SpaceAroundOperators in a hash that would be changed back' do
create_file('.rubocop.yml', <<~YAML)
Style/HashSyntax:
EnforcedStyle: hash_rockets
Layout/HashAlignment:
EnforcedHashRocketStyle: table
Lint/UselessAssignment:
Enabled: false
YAML
source = <<~RUBY
a = { 1=>2, a => b }
hash = {
:alice => {
:age => 23,
:role => 'Director'
},
:bob => {
:age => 25,
:role => 'Consultant'
}
}
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect-all'])).to eq(0)
# 1=>2 is changed to 1 => 2. The rest is unchanged.
# SpaceAroundOperators leaves it to HashAlignment when the style is table.
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
a = { 1 => 2, a => b }
hash = {
:alice => {
:age => 23,
:role => 'Director'
},
:bob => {
:age => 25,
:role => 'Consultant'
}
}
RUBY
end
it 'corrects `EnforcedStyle: hash_rockets` of `Style/HashSyntax` with `Layout/HashAlignment`' do
create_file('.rubocop.yml', <<~YAML)
Style/HashSyntax:
EnforcedStyle: hash_rockets
YAML
source = <<~RUBY
some_method(a: 'abc', b: 'abc',
c: 'abc', d: 'abc'
)
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect-all',
'--only', 'Style/HashSyntax,Style/HashAlignment'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
some_method(:a => 'abc', :b => 'abc',
:c => 'abc', :d => 'abc'
)
RUBY
end
it 'does not correct `AllowInMultilineConditions: true` of `Style/ParenthesesAroundCondition` with `Style/RedundantParentheses`' do
create_file('.rubocop.yml', <<~YAML)
Style/ParenthesesAroundCondition:
AllowInMultilineConditions: true
YAML
source = <<~RUBY
if (foo &&
bar)
end
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect', '--only',
'Style/ParenthesesAroundCondition,' \
'Style/RedundantParentheses'])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
if (foo &&
bar)
end
RUBY
end
it 'corrects `EnforcedShorthandSyntax: always` of `Style/HashSyntax` with `Style/RedundantParentheses` when using Ruby 3.1' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 3.1
Style/HashSyntax:
EnforcedShorthandSyntax: always
Style/RedundantParentheses:
Enabled: true
Style/MethodCallWithArgsParentheses:
Enabled: true
EnforcedStyle: omit_parentheses
YAML
source = <<~RUBY
it 'fails' do
foo = create :foo, bar: bar, other: (create :other, bar: bar)
quux = (doo bar: bar).baz
pass
end
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect', '--only',
'Style/HashSyntax,' \
'Style/RedundantParentheses,' \
'Style/MethodCallWithArgsParentheses'])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
it 'fails' do
foo = create :foo, bar:, other: (create :other, bar:)
quux = (doo bar:).baz
pass
end
RUBY
end
it 'corrects `EnforcedShorthandSyntax: always` of `Style/HashSyntax` with `Style/IfUnlessModifier` when using Ruby 3.1' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 3.1
Style/HashSyntax:
EnforcedShorthandSyntax: always
YAML
source = <<~RUBY
if condition
do_something foo: foo
end
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect', '--only', 'Style/HashSyntax,Style/IfUnlessModifier'])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
do_something(foo:) if condition
RUBY
end
it 'corrects `EnforcedStyle: line_count_based` of `Style/BlockDelimiters` with `Style/CommentedKeyword` and `Layout/BlockEndNewline`' do
create_file('.rubocop.yml', <<~YAML)
Style/BlockDelimiters:
EnforcedStyle: line_count_based
YAML
source = <<~RUBY
foo {
bar } # This comment should be kept.
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect',
'--only', 'Style/BlockDelimiters,Style/CommentedKeyword,Layout/BlockEndNewline'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
# This comment should be kept.
foo do
bar
end
RUBY
end
it 'corrects `EnforcedStyle: semantic` of `Style/BlockDelimiters` with `Layout/SpaceInsideBlockBraces`' do
create_file('.rubocop.yml', <<~YAML)
Style/BlockDelimiters:
EnforcedStyle: semantic
YAML
source = <<~RUBY
File.open('a', 'w') { }
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect-all',
'--only', 'Style/BlockDelimiters,Layout/SpaceInsideBlockBraces'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
File.open('a', 'w') do end
RUBY
end
it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with `Style/NestedParenthesizedCalls`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: require_parentheses
YAML
source = <<~RUBY
a(b 1)
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect-all',
'--only', 'Style/MethodCallWithArgsParentheses,Style/NestedParenthesizedCalls'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
a(b(1))
RUBY
end
it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with `Style/RescueModifier`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: require_parentheses
YAML
source = <<~RUBY
do_something arg rescue nil
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect-all',
'--only', 'Style/MethodCallWithArgsParentheses,Style/RescueModifier'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
begin
do_something(arg)
rescue
nil
end
RUBY
end
it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \
'`EnforcedStyle: conditionals` of `Style/AndOr`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: require_parentheses
Style/AndOr:
EnforcedStyle: conditionals
YAML
create_file('example.rb', <<~RUBY)
if foo and bar :arg
end
RUBY
expect(
cli.run(['--autocorrect-all', '--only', 'Style/MethodCallWithArgsParentheses,Style/AndOr'])
).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
if foo && bar(:arg)
end
RUBY
end
it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \
'`Lint/AmbiguousBlockAssociation`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: require_parentheses
YAML
create_file('example.rb', <<~RUBY)
expect { foo }.not_to change { bar }
RUBY
expect(
cli.run(
[
'--autocorrect',
'--only', 'Style/MethodCallWithArgsParentheses,Lint/AmbiguousBlockAssociation'
]
)
).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
expect { foo }.not_to(change { bar })
RUBY
end
it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \
'`Lint/AmbiguousOperator`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: require_parentheses
YAML
create_file('example.rb', <<~RUBY)
def foo(&block)
do_something &block
end
RUBY
expect(
cli.run(
['--autocorrect', '--only', 'Style/MethodCallWithArgsParentheses,Lint/AmbiguousOperator']
)
).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
def foo(&block)
do_something(&block)
end
RUBY
end
it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \
'`Layout/SpaceBeforeFirstArg`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: require_parentheses
YAML
create_file('example.rb', <<~RUBY)
obj.do_something"message"
RUBY
expect(
cli.run(
[
'--autocorrect',
'--only', 'Style/MethodCallWithArgsParentheses,Layout/SpaceBeforeFirstArg'
]
)
).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
obj.do_something("message")
RUBY
end
it 'corrects `EnforcedStyle: require_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \
'`Style/SoleNestedConditional`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: require_parentheses
YAML
create_file('example.rb', <<~RUBY)
if items.include? item
if condition
do_something
end
end
RUBY
expect(
cli.run(
[
'--autocorrect',
'--only', 'Style/MethodCallWithArgsParentheses,Style/SoleNestedConditional'
]
)
).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
if items.include?(item) && condition
do_something
end
RUBY
end
it 'corrects `EnforcedStyle: omit_parentheses` of `Style/MethodCallWithArgsParentheses` with ' \
'`Style/SuperWithArgsParentheses`' do
create_file('.rubocop.yml', <<~YAML)
Style/MethodCallWithArgsParentheses:
EnforcedStyle: omit_parentheses
YAML
create_file('example.rb', <<~RUBY)
class Derived < Base
def do_something(arg)
super(arg)
end
end
RUBY
expect(
cli.run(
[
'--autocorrect',
'--only', 'Style/MethodCallWithArgsParentheses,Style/SuperWithArgsParentheses'
]
)
).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
class Derived < Base
def do_something(arg)
super(arg)
end
end
RUBY
end
it 'corrects `Style/IfUnlessModifier` with `Style/SoleNestedConditional`' do
source = <<~RUBY
def foo
# NOTE: comment
if a? && b?
puts "looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong message" unless c?
end
end
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect-all',
'--only', 'Style/IfUnlessModifier,Style/SoleNestedConditional'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
def foo
# NOTE: comment
if a? && b? && !c?
puts "looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong message"
end
end
RUBY
end
it 'corrects `Style/SoleNestedConditional` with `Style/InverseMethods` and `Style/IfUnlessModifier`' do
source = <<~RUBY
unless foo.to_s == 'foo'
if condition
return foo
end
end
RUBY
create_file('example.rb', source)
expect(cli.run(
[
'--autocorrect-all',
'--only', 'Style/SoleNestedConditional,Style/InverseMethods,Style/IfUnlessModifier'
]
)).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
return foo if foo.to_s != 'foo' && condition
RUBY
end
it 'corrects `Lint/UnusedMethodArgument` with `Style/ExplicitBlockArgument`' do
source = <<~RUBY
def foo(&block)
bar { yield }
end
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect',
'--only', 'Lint/UnusedMethodArgument,Style/ExplicitBlockArgument'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
def foo(&block)
bar(&block)
end
RUBY
end
it 'corrects `Naming/BlockForwarding` with `Lint/AmbiguousOperator`' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 3.1
YAML
source = <<~RUBY
def foo(options, &block)
bar **options, &block
end
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect',
'--only', 'Naming/BlockForwarding,Lint/AmbiguousOperator'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
def foo(options, &)
bar(**options, &)
end
RUBY
end
it 'corrects `Naming/BlockForwarding` with `Style/ArgumentsForwarding`' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 3.2
YAML
source = <<~RUBY
def some_method(form, **options, &block)
render 'template', form: form, **options, &block
end
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect',
'--only', 'Naming/BlockForwarding,Style/ArgumentsForwarding'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
def some_method(form, **, &)
render('template', form: form, **, &)
end
RUBY
end
it 'corrects `Naming/BlockForwarding` with `Style/ExplicitBlockArgument`' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 3.2
YAML
source = <<~RUBY
def foo(&block)
bar do |baz|
yield(baz)
end
end
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect',
'--only', 'Naming/BlockForwarding,Style/ExplicitBlockArgument'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
def foo(&)
bar(&)
end
RUBY
end
it 'corrects `EnforcedStyle: explicit` of `Naming/BlockForwarding` with `Style/ArgumentsForwarding`' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 3.1
Naming/BlockForwarding:
EnforcedStyle: explicit
YAML
source = <<~RUBY
def some_method(&block)
render &block
end
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect',
'--only', 'Naming/BlockForwarding,Style/ArgumentsForwarding'
])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
def some_method(&block)
render &block
end
RUBY
end
describe 'trailing comma cops' do
let(:source) do
<<~RUBY
func({
@abc => 0,
@xyz => 1
})
func(
{
abc: 0
}
)
func(
{},
{
xyz: 1
}
)
RUBY
end
let(:config) do
{
'Style/TrailingCommaInArguments' => {
'EnforcedStyleForMultiline' => comma_style
},
'Style/TrailingCommaInArrayLiteral' => {
'EnforcedStyleForMultiline' => comma_style
},
'Style/TrailingCommaInHashLiteral' => {
'EnforcedStyleForMultiline' => comma_style
}
}
end
before do
create_file('example.rb', source)
create_file('.rubocop.yml', YAML.dump(config))
end
shared_examples 'corrects offenses without producing a double comma' do
it 'corrects TrailingCommaInLiteral and TrailingCommaInArguments ' \
'without producing a double comma' do
cli.run(['--autocorrect-all'])
expect(File.read('example.rb')).to eq(expected_corrected_source)
expect($stderr.string).to eq('')
end
end
context 'when the style is `comma`' do
let(:comma_style) { 'comma' }
let(:expected_corrected_source) do
<<~RUBY
# frozen_string_literal: true
func({
@abc => 0,
@xyz => 1,
})
func(
{
abc: 0,
},
)
func(
{},
{
xyz: 1,
},
)
RUBY
end
it_behaves_like 'corrects offenses without producing a double comma'
end
context 'when the style is `consistent_comma`' do
let(:comma_style) { 'consistent_comma' }
let(:expected_corrected_source) do
<<~RUBY
# frozen_string_literal: true
func({
@abc => 0,
@xyz => 1,
})
func(
{
abc: 0,
},
)
func(
{},
{
xyz: 1,
},
)
RUBY
end
it_behaves_like 'corrects offenses without producing a double comma'
end
end
context 'space_inside_bracket cops' do
let(:source) do
<<~RUBY
puts [ a[b], c[ d ], [1, 2] ]
foo[[ 3, 4 ], [5, 6] ]
RUBY
end
let(:config) do
{
'Layout/SpaceInsideArrayLiteralBrackets' => {
'EnforcedStyle' => array_style
},
'Layout/SpaceInsideReferenceBrackets' => {
'EnforcedStyle' => reference_style
}
}
end
before do
create_file('example.rb', source)
create_file('.rubocop.yml', YAML.dump(config))
end
shared_examples 'corrects offenses' do
it 'corrects SpaceInsideArrayLiteralBrackets and SpaceInsideReferenceBrackets' do
cli.run(['--autocorrect-all'])
expect(File.read('example.rb')).to eq(corrected_source)
expect($stderr.string).to eq('')
end
end
context 'when array style is space & reference style is no space' do
let(:array_style) { 'space' }
let(:reference_style) { 'no_space' }
let(:corrected_source) do
<<~RUBY
# frozen_string_literal: true
puts [ a[b], c[d], [ 1, 2 ] ]
foo[[ 3, 4 ], [ 5, 6 ]]
RUBY
end
it_behaves_like 'corrects offenses'
end
context 'when array style is no_space & reference style is space' do
let(:array_style) { 'no_space' }
let(:reference_style) { 'space' }
let(:corrected_source) do
<<~RUBY
# frozen_string_literal: true
puts [a[ b ], c[ d ], [1, 2]]
foo[ [3, 4], [5, 6] ]
RUBY
end
it_behaves_like 'corrects offenses'
end
context 'when array style is compact & reference style is no_space' do
let(:array_style) { 'compact' }
let(:reference_style) { 'no_space' }
let(:corrected_source) do
<<~RUBY
# frozen_string_literal: true
puts [ a[b], c[d], [ 1, 2 ]]
foo[[ 3, 4 ], [ 5, 6 ]]
RUBY
end
it_behaves_like 'corrects offenses'
end
context 'when array style is compact & reference style is space' do
let(:array_style) { 'compact' }
let(:reference_style) { 'space' }
let(:corrected_source) do
<<~RUBY
# frozen_string_literal: true
puts [ a[ b ], c[ d ], [ 1, 2 ]]
foo[ [ 3, 4 ], [ 5, 6 ] ]
RUBY
end
it_behaves_like 'corrects offenses'
end
end
it 'corrects IndentationWidth, RedundantBegin, and RescueEnsureAlignment offenses' do
source = <<~RUBY
def verify_section
begin
scroll_down_until_element_exists
rescue StandardError
scroll_down_until_element_exists
end
end
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect-all'])).to eq(0)
corrected = <<~RUBY
# frozen_string_literal: true
def verify_section
scroll_down_until_element_exists
rescue StandardError
scroll_down_until_element_exists
end
RUBY
expect(File.read('example.rb')).to eq(corrected)
end
it 'corrects `Style/RedundantBegin` with `Style/MultilineMemoization`' do
source = <<~RUBY
@memo ||= begin
if condition
do_something
end
end
RUBY
create_file('example.rb', source)
expect(cli.run(['-a', '--only', 'Style/RedundantBegin,Style/MultilineMemoization'])).to eq(0)
corrected = <<~RUBY
@memo ||= if condition
do_something
end
#{trailing_whitespace * 10}
RUBY
expect(File.read('example.rb')).to eq(corrected)
end
it 'corrects `Layout/SpaceAroundKeyword` with `Layout/SpaceInsideRangeLiteral`' do
source = <<~RUBY
def method
1..super
end
RUBY
create_file('example.rb', source)
expect(
cli.run(['-a', '--only', 'Layout/SpaceAroundKeyword,Layout/SpaceInsideRangeLiteral'])
).to eq(0)
expect($stdout.string).to include('no offenses detected')
expect(File.read('example.rb')).to eq(source)
end
it 'corrects LineEndConcatenation offenses leaving the ' \
'RedundantInterpolation offense unchanged' do
# If we change string concatenation from plus to backslash, the string
# literal that follows must remain a string literal.
source = <<~'RUBY'
puts 'foo' +
"#{bar}"
puts 'a' +
'b'
"#{c}"
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect-all'])).to eq(0)
corrected = ['# frozen_string_literal: true',
'',
"puts 'foo' \\",
' "#{bar}"',
# Expressions that need correction from only one of these cops
# are corrected as expected.
"puts 'a' \\",
" 'b'",
'c.to_s',
''].join("\n")
expect(File.read('example.rb')).to eq(corrected)
end
it 'corrects Style/InverseMethods and Style/Not offenses' do
source = <<~RUBY
x.select {|y| not y.z }
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect-all', '--only', 'Style/InverseMethods,Style/Not'])).to eq(0)
corrected = <<~RUBY
x.reject {|y| y.z }
RUBY
expect(File.read('example.rb')).to eq(corrected)
end
it 'corrects Style/Next and Style/SafeNavigation offenses' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 2.7
YAML
source = <<~RUBY
until x
if foo
foo.some_method do
y
end
end
end
RUBY
create_file('example.rb', source)
expect(cli.run(['--autocorrect-all', '--only', 'Style/Next,Style/SafeNavigation'])).to eq(0)
corrected = <<~RUBY
until x
next unless foo
foo.some_method do
y
end
end
RUBY
expect(File.read('example.rb')).to eq(corrected)
end
it 'corrects `Lint/Lambda` and `Lint/UnusedBlockArgument` offenses' do
source = <<~RUBY
c = -> event do
puts 'Hello world'
end
RUBY
create_file('example.rb', source)
expect(cli.run([
'--autocorrect-all',
'--only', 'Lint/Lambda,Lint/UnusedBlockArgument'
])).to eq(0)
corrected = <<~RUBY
c = lambda do |_event|
puts 'Hello world'
end
RUBY
expect(File.read('example.rb')).to eq(corrected)
end
describe 'caching' do
let(:cache) do
instance_double(RuboCop::ResultCache, 'valid?' => true, 'load' => cached_offenses)
end
let(:source) { %(puts "Hi"\n) }
before do
allow(RuboCop::ResultCache).to receive(:new) { cache }
create_file('example.rb', source)
end
context 'with no offenses in the cache' do
let(:cached_offenses) { [] }
it "doesn't correct offenses" do
expect(cli.run(['--autocorrect-all'])).to eq(0)
expect(File.read('example.rb')).to eq(source)
end
end
context 'with an offense in the cache' do
let(:cached_offenses) { ['Style/StringLiterals: ...'] }
it 'corrects offenses' do
allow(cache).to receive(:save)
expect(cli.run(['--autocorrect-all'])).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
puts 'Hi'
RUBY
end
end
end
%i[line_count_based semantic braces_for_chaining].each do |style|
context "when BlockDelimiters has #{style} style" do
it 'corrects SpaceBeforeBlockBraces, SpaceInsideBlockBraces offenses' do
source = <<~RUBY
r = foo.map{|a|
a.bar.to_s
}
foo.map{|a|
a.bar.to_s
}.baz
RUBY
create_file('example.rb', source)
create_file('.rubocop.yml', <<~YAML)
Lint/UselessAssignment:
Enabled: false
Style/BlockDelimiters:
EnforcedStyle: #{style}
YAML
expect(cli.run(['--autocorrect-all'])).to eq(0)
# rubocop:disable Style/HashLikeCase
corrected = case style
when :semantic
<<~RUBY
# frozen_string_literal: true
r = foo.map { |a|
a.bar.to_s
}
foo.map { |a|
a.bar.to_s
}.baz
RUBY
when :braces_for_chaining
<<~RUBY
# frozen_string_literal: true
r = foo.map do |a|
a.bar.to_s
end
foo.map { |a|
a.bar.to_s
}.baz
RUBY
when :line_count_based
<<~RUBY
# frozen_string_literal: true
r = foo.map do |a|
a.bar.to_s
end
foo.map do |a|
a.bar.to_s
end.baz
RUBY
end
# rubocop:enable Style/HashLikeCase
expect($stderr.string).to eq('')
expect(File.read('example.rb')).to eq(corrected)
end
end
end
it 'corrects InitialIndentation offenses' do
source = <<~RUBY
# comment 1
# comment 2
def func
begin
foo
bar
rescue StandardError
baz
end
end
RUBY
create_file('example.rb', source)
create_file('.rubocop.yml', <<~YAML)
Layout/DefEndAlignment:
AutoCorrect: always
YAML
expect(cli.run(['--autocorrect-all'])).to eq(0)
corrected = <<~RUBY
# frozen_string_literal: true
# comment 1
# comment 2
def func
foo
bar
rescue StandardError
baz
end
RUBY
expect($stderr.string).to eq('')
expect(File.read('example.rb')).to eq(corrected)
end
it 'corrects RedundantCopDisableDirective offenses' do
source = <<~RUBY
class A
# rubocop:disable Metrics/MethodLength
def func
# rubocop:enable Metrics/MethodLength
x = foo # rubocop:disable Lint/UselessAssignment,Style/For
# rubocop:disable all
# rubocop:disable Style/ClassVars
@@bar = "3"
end
end
RUBY
create_file('example.rb', source)
expect(cli.run(%w[--autocorrect-all --format simple])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
== example.rb ==
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cli/disable_uncorrectable_spec.rb | spec/rubocop/cli/disable_uncorrectable_spec.rb | # frozen_string_literal: true
RSpec.describe 'RuboCop::CLI --disable-uncorrectable', :isolated_environment do # rubocop:disable RSpec/DescribeClass
subject(:cli) { RuboCop::CLI.new }
include_context 'cli spec behavior'
describe '--disable-uncorrectable' do
let(:cli_opts) { %w[--autocorrect-all --format simple --disable-uncorrectable] }
let(:exit_code) { cli.run(cli_opts) }
let(:setup_long_line) do
create_file('.rubocop.yml', <<~YAML)
Style/IpAddresses:
Enabled: true
Layout/LineLength:
Max: #{max_length}
YAML
create_file('example.rb', <<~RUBY)
ip('1.2.3.4')
# last line
RUBY
end
let(:max_length) { 46 }
it 'does not disable anything for cops that support autocorrect' do
create_file('example.rb', 'puts 1==2')
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
C: 1: 7: [Corrected] Layout/SpaceAroundOperators: Surrounding space missing for operator ==.
C: 2: 1: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
1 file inspected, 3 offenses detected, 3 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
puts 1 == 2
RUBY
end
context 'if one one-line disable statement fits' do
it 'adds it' do
setup_long_line
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
C: 1: 4: [Todo] Style/IpAddresses: Do not hardcode IP addresses.
C: 2: 1: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
1 file inspected, 3 offenses detected, 3 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
ip('1.2.3.4') # rubocop:todo Style/IpAddresses
# last line
RUBY
end
it 'adds it when the cop supports autocorrect but does not correct the offense' do
create_file('example.rb', <<~RUBY)
def ordinary_method(some_arg)
puts 'Ignoring args'
end
def method_with_keyword_arg(some_keyword_arg:)
puts 'Ignoring args'
end
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
W: 1: 21: [Corrected] Lint/UnusedMethodArgument: Unused method argument - some_arg. If it's necessary, use _ or _some_arg as an argument name to indicate that it won't be used. If it's unnecessary, remove it. You can also write as ordinary_method(*) if you want the method to accept any arguments but don't care about them.
C: 2: 1: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
W: 5: 29: [Todo] Lint/UnusedMethodArgument: Unused method argument - some_keyword_arg. You can also write as method_with_keyword_arg(*) if you want the method to accept any arguments but don't care about them.
1 file inspected, 4 offenses detected, 4 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
def ordinary_method(_some_arg)
puts 'Ignoring args'
end
def method_with_keyword_arg(some_keyword_arg:) # rubocop:todo Lint/UnusedMethodArgument
puts 'Ignoring args'
end
RUBY
end
context 'and the offending line has a multiline %w literal' do
it 'adds comment at EOL or before and after depending on where it fits' do
create_file('.rubocop.yml', <<~YAML)
Lint/UselessConstantScoping:
Enabled: true
Style/IpAddresses:
Enabled: true
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
class Foo # :nodoc:
private
ALLOWED_VALUES = %w[ value1
value2 ].freeze + [ip('1.2.3.4')]
def lolol; end
end
RUBY
expect(exit_code).to eq(0)
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
W: 6: 3: [Todo] Lint/UselessConstantScoping: Useless private access modifier for constant scope.
C: 7: 46: [Todo] Style/IpAddresses: Do not hardcode IP addresses.
1 file inspected, 2 offenses detected, 2 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
class Foo # :nodoc:
private
# rubocop:todo Lint/UselessConstantScoping
ALLOWED_VALUES = %w[ value1
value2 ].freeze + [ip('1.2.3.4')] # rubocop:todo Style/IpAddresses
# rubocop:enable Lint/UselessConstantScoping
def lolol; end
end
RUBY
end
end
context 'and there are two offenses of the same kind on one line' do
it 'adds a single one-line disable statement' do
create_file('.rubocop.yml', <<~YAML)
Style/IpAddresses:
Enabled: true
YAML
create_file('example.rb', <<~RUBY)
ip('1.2.3.4', '5.6.7.8')
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
C: 1: 4: [Todo] Style/IpAddresses: Do not hardcode IP addresses.
C: 1: 15: [Todo] Style/IpAddresses: Do not hardcode IP addresses.
C: 2: 1: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
1 file inspected, 4 offenses detected, 4 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
ip('1.2.3.4', '5.6.7.8') # rubocop:todo Style/IpAddresses
RUBY
end
end
context "but there are more offenses on the line and they don't all fit" do
it 'adds both one-line and before-and-after disable statements' do
create_file('example.rb', <<~RUBY)
# Chess engine.
class Chess
def choose_move(who_to_move)
legal_moves = all_legal_moves_that_dont_put_me_in_check(who_to_move)
return nil if legal_moves.empty?
mating_move = checkmating_move(legal_moves)
return mating_move if mating_move
best_moves = checking_moves(legal_moves)
best_moves = castling_moves(legal_moves) if best_moves.empty?
best_moves = taking_moves(legal_moves) if best_moves.empty?
best_moves = legal_moves if best_moves.empty?
best_moves = remove_dangerous_moves(best_moves, who_to_move)
best_moves = legal_moves if best_moves.empty?
best_moves.sample
end
end
RUBY
create_file('.rubocop.yml', <<~YAML)
Metrics/AbcSize:
Max: 15
Metrics/CyclomaticComplexity:
Max: 6
YAML
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
C: 2: 1: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
C: 3: 3: [Todo] Metrics/AbcSize: Assignment Branch Condition size for choose_move is too high. [<8, 12, 6> 15.62/15]
C: 3: 3: [Todo] Metrics/CyclomaticComplexity: Cyclomatic complexity for choose_move is too high. [7/6]
C: 3: 3: [Todo] Metrics/MethodLength: Method has too many lines. [11/10]
C: 4: 3: [Todo] Metrics/AbcSize: Assignment Branch Condition size for choose_move is too high. [<8, 12, 6> 15.62/15]
C: 4: 3: [Todo] Metrics/MethodLength: Method has too many lines. [11/10]
C: 4: 32: [Corrected] Style/DoubleCopDisableDirective: More than one disable comment on one line.
1 file inspected, 8 offenses detected, 8 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# Chess engine.
class Chess
# rubocop:todo Metrics/MethodLength
# rubocop:todo Metrics/AbcSize
def choose_move(who_to_move) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength
legal_moves = all_legal_moves_that_dont_put_me_in_check(who_to_move)
return nil if legal_moves.empty?
mating_move = checkmating_move(legal_moves)
return mating_move if mating_move
best_moves = checking_moves(legal_moves)
best_moves = castling_moves(legal_moves) if best_moves.empty?
best_moves = taking_moves(legal_moves) if best_moves.empty?
best_moves = legal_moves if best_moves.empty?
best_moves = remove_dangerous_moves(best_moves, who_to_move)
best_moves = legal_moves if best_moves.empty?
best_moves.sample
end
# rubocop:enable Metrics/AbcSize
# rubocop:enable Metrics/MethodLength
end
RUBY
end
end
end
context "if a one-line disable statement doesn't fit" do
let(:max_length) { super() - 1 }
it 'adds before-and-after disable statement' do
setup_long_line
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
C: 1: 4: [Todo] Style/IpAddresses: Do not hardcode IP addresses.
C: 2: 1: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
1 file inspected, 3 offenses detected, 3 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Style/IpAddresses
ip('1.2.3.4')
# rubocop:enable Style/IpAddresses
# last line
RUBY
end
context 'and the offense is inside a heredoc' do
it 'adds before-and-after disable statement around the heredoc' do
create_file('example.rb', <<~'RUBY')
# frozen_string_literal: true
def our_function
ourVariable = "foo"
script = <<~JS
<script>
window.stuff = "#{ourVariable}"
</script>
JS
puts(script)
end
RUBY
expect(exit_code).to eq(0)
expect(File.read('example.rb')).to eq(<<~'RUBY')
# frozen_string_literal: true
def our_function
ourVariable = 'foo' # rubocop:todo Naming/VariableName
# rubocop:todo Naming/VariableName
script = <<~JS
<script>
window.stuff = "#{ourVariable}"
</script>
JS
# rubocop:enable Naming/VariableName
puts(script)
end
RUBY
end
end
context 'and the offense is inside a percent array' do
before do
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Max: 30
YAML
end
it 'adds before-and-after disable statement around the percent array' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
ARRAY = %i[AAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBB].freeze
RUBY
expect(exit_code).to eq(0)
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 3: 31: [Corrected] Layout/LineLength: Line is too long. [60/30]
C: 4: 1: [Corrected] Layout/FirstArrayElementIndentation: Use 2 spaces for indentation in an array, relative to the start of the line where the left square bracket is.
C: 4: 31: [Todo] Layout/LineLength: Line is too long. [49/30]
C: 4: 42: [Corrected] Layout/MultilineArrayBraceLayout: The closing array brace must be on the line after the last array element when the opening brace is on a separate line from the first array element.
1 file inspected, 4 offenses detected, 4 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Layout/LineLength
ARRAY = %i[
AAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBB
].freeze
# rubocop:enable Layout/LineLength
RUBY
end
it 'adds before-and-after disable statement around the multi-line percent array' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
ARRAY = %i[
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
].freeze
RUBY
expect(exit_code).to eq(0)
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Layout/LineLength
ARRAY = %i[
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
].freeze
# rubocop:enable Layout/LineLength
RUBY
end
end
context 'and the offense is outside a percent array' do
it 'adds a single one-line disable statement' do
create_file('.rubocop.yml', <<~YAML)
Metrics/MethodLength:
Max: 2
YAML
create_file('example.rb', <<~RUBY)
def foo
bar do
%w[]
end
end
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 1: 1: [Todo] Metrics/MethodLength: Method has too many lines. [3/2]
C: 1: 1: [Corrected] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
C: 2: 1: [Corrected] Layout/EmptyLineAfterMagicComment: Add an empty line after magic comments.
1 file inspected, 3 offenses detected, 3 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
def foo # rubocop:todo Metrics/MethodLength
bar do
%w[]
end
end
RUBY
end
end
context 'and the offense is on a line containing a string continuation' do
it 'adds before-and-after disable statement around the string continuation' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
DisabledByDefault: true
Layout/LineLength:
Enabled: true
Lint/DuplicateHashKey:
Enabled: true
YAML
create_file('example.rb', <<~'RUBY')
{
key1: 'something',
key1: 'whatever'\
'something else'
}
RUBY
expect(exit_code).to eq(0)
expect(File.read('example.rb')).to eq(<<~'RUBY')
{
key1: 'something',
# rubocop:todo Lint/DuplicateHashKey
key1: 'whatever'\
'something else'
# rubocop:enable Lint/DuplicateHashKey
}
RUBY
end
end
context 'and the offense is on a different line than a string continuation' do
it 'adds a single one-line disable statement' do
create_file('.rubocop.yml', <<~YAML)
AllCops:
DisabledByDefault: true
Layout/LineLength:
Enabled: true
Lint/DuplicateHashKey:
Enabled: true
YAML
create_file('example.rb', <<~'RUBY')
x = 'something'\
'something else'
{
key1: 'foo',
key1: 'bar'
}
RUBY
expect(exit_code).to eq(0)
expect(File.read('example.rb')).to eq(<<~'RUBY')
x = 'something'\
'something else'
{
key1: 'foo',
key1: 'bar' # rubocop:todo Lint/DuplicateHashKey
}
RUBY
end
end
context 'and the offense is within a single-line string' do
before do
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Max: 40
YAML
end
it 'adds before-and-after disable statements' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
'the quick brown fox jumps over the lazy dog.'
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 3: 41: [Todo] Layout/LineLength: Line is too long. [46/40]
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Layout/LineLength
'the quick brown fox jumps over the lazy dog.'
# rubocop:enable Layout/LineLength
RUBY
end
end
context 'and the offense is within a multi-line string' do
before do
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Max: 40
YAML
end
context 'with quotes' do
it 'adds before-and-after disable statements' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
"
the quick brown fox jumps over the lazy dog.
"
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 4: 41: [Todo] Layout/LineLength: Line is too long. [46/40]
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Layout/LineLength
"
the quick brown fox jumps over the lazy dog.
"
# rubocop:enable Layout/LineLength
RUBY
end
end
context 'with %()' do
it 'adds before-and-after disable statements' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
%(
the quick brown fox jumps over the lazy dog.
)
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 4: 41: [Todo] Layout/LineLength: Line is too long. [46/40]
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Layout/LineLength
%(
the quick brown fox jumps over the lazy dog.
)
# rubocop:enable Layout/LineLength
RUBY
end
end
context 'with %q()' do
let(:cli_opts) { super().push('--except', 'Style/RedundantPercentQ') }
it 'adds before-and-after disable statements' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
%q(
the quick brown fox jumps over the lazy dog.
)
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 4: 41: [Todo] Layout/LineLength: Line is too long. [46/40]
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Layout/LineLength
%q(
the quick brown fox jumps over the lazy dog.
)
# rubocop:enable Layout/LineLength
RUBY
end
end
context 'with %Q()' do
let(:cli_opts) do
super().push('--except', 'Style/BarePercentLiterals,Style/RedundantPercentQ')
end
it 'adds before-and-after disable statements' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
%Q(
the quick brown fox jumps over the lazy dog.
)
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 4: 41: [Todo] Layout/LineLength: Line is too long. [46/40]
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
# rubocop:todo Layout/LineLength
%Q(
the quick brown fox jumps over the lazy dog.
)
# rubocop:enable Layout/LineLength
RUBY
end
end
end
end
context 'when `Layout/LineLength` is disabled' do
it 'adds comment at EOL or before and after depending on where it fits' do
create_file('.rubocop.yml', <<~YAML)
Lint/UselessConstantScoping:
Enabled: true
Style/IpAddresses:
Enabled: true
Layout/LineLength:
Enabled: false
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
class Foo # :nodoc:
private
ALLOWED_VALUES = %w[ value1
value2 ].freeze + [ip('1.2.3.4')]
def lolol; end
end
RUBY
expect(exit_code).to eq(0)
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
W: 6: 3: [Todo] Lint/UselessConstantScoping: Useless private access modifier for constant scope.
C: 7: 46: [Todo] Style/IpAddresses: Do not hardcode IP addresses.
1 file inspected, 2 offenses detected, 2 offenses corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
class Foo # :nodoc:
private
# rubocop:todo Lint/UselessConstantScoping
ALLOWED_VALUES = %w[ value1
value2 ].freeze + [ip('1.2.3.4')] # rubocop:todo Style/IpAddresses
# rubocop:enable Lint/UselessConstantScoping
def lolol; end
end
RUBY
end
end
context 'when exist offense for Layout/SpaceInsideArrayLiteralBrackets' do
context 'when `EnforcedStyle: no_space`' do
it 'does not disable anything for cops that support autocorrect' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
puts [ :something ]
# last line
RUBY
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 3: 7: [Corrected] Layout/SpaceInsideArrayLiteralBrackets: Do not use space inside array brackets.
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
puts [:something]
# last line
RUBY
end
end
context 'when `EnforcedStyle: space`' do
let(:setup_space_inside_array) do
create_file('.rubocop.yml', <<~YAML)
Layout/SpaceInsideArrayLiteralBrackets:
EnforcedStyle: space
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
puts [:something]
# last line
RUBY
end
it 'does not disable anything for cops that support autocorrect' do
setup_space_inside_array
expect(exit_code).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
== example.rb ==
C: 3: 6: [Corrected] Layout/SpaceInsideArrayLiteralBrackets: Use space inside array brackets.
1 file inspected, 1 offense detected, 1 offense corrected
OUTPUT
expect(File.read('example.rb')).to eq(<<~RUBY)
# frozen_string_literal: true
puts [ :something ]
# last line
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/cli/auto_gen_config_spec.rb | spec/rubocop/cli/auto_gen_config_spec.rb | # frozen_string_literal: true
RSpec.describe 'RuboCop::CLI --auto-gen-config', :isolated_environment do # rubocop:disable RSpec/DescribeClass
subject(:cli) { RuboCop::CLI.new }
include_context 'cli spec behavior'
describe '--auto-gen-config' do
before do
RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
end
shared_examples 'LineLength handling' do |ctx, initial_dotfile, exp_dotfile|
context ctx do
# Since there is a line with length 99 in the inspected code,
# Style/IfUnlessModifier will register an offense when
# Layout/LineLength:Max has been set to 99. With a lower
# LineLength:Max there would be no IfUnlessModifier offense.
it "bases other cops' configuration on the code base's current maximum line length" do
if initial_dotfile
initial_config = YAML.safe_load(initial_dotfile.join($RS)) || {}
inherited_files = Array(initial_config['inherit_from'])
(inherited_files - ['.rubocop.yml']).each { |f| create_empty_file(f) }
create_file('.rubocop.yml', initial_dotfile)
create_file('.rubocop_todo.yml', [''])
end
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
def f
#{' #' * 46}
if #{'a' * 120}
return y
end
z
end
RUBY
expect(cli.run(['--auto-gen-config'])).to eq(0)
expect(File.readlines('.rubocop_todo.yml')
.drop_while { |line| line.start_with?('#') }.join)
.to eq(<<~YAML)
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
Style/IfUnlessModifier:
Exclude:
- 'example.rb'
# Offense count: 2
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: AllowHeredoc, AllowURI, AllowQualifiedName, URISchemes, AllowRBSInlineAnnotation, AllowCopDirectives, AllowedPatterns, SplitStrings.
# URISchemes: http, https
Layout/LineLength:
Max: 138
YAML
expect(File.read('.rubocop.yml').strip).to eq(exp_dotfile.join($RS))
$stdout = StringIO.new
expect(RuboCop::CLI.new.run([])).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to include('no offenses detected')
end
end
end
it_behaves_like 'LineLength handling',
'when .rubocop.yml does not exist',
nil,
['inherit_from: .rubocop_todo.yml']
it_behaves_like 'LineLength handling',
'when .rubocop.yml is empty',
[''],
['inherit_from: .rubocop_todo.yml']
it_behaves_like 'LineLength handling',
'when .rubocop.yml inherits only from .rubocop_todo.yml',
['inherit_from: .rubocop_todo.yml'],
['inherit_from: .rubocop_todo.yml']
it_behaves_like 'LineLength handling',
'when .rubocop.yml inherits only from .rubocop_todo.yml ' \
'in an array',
['inherit_from:',
' - .rubocop_todo.yml'],
['inherit_from:',
' - .rubocop_todo.yml']
it_behaves_like 'LineLength handling',
'when .rubocop.yml inherits from another file and ' \
'.rubocop_todo.yml',
['inherit_from:',
' - common.yml',
' - .rubocop_todo.yml'],
['inherit_from:',
' - common.yml',
' - .rubocop_todo.yml']
it_behaves_like 'LineLength handling',
'when .rubocop.yml inherits from two other files',
['inherit_from:',
' - common1.yml',
' - common2.yml'],
['inherit_from:',
' - .rubocop_todo.yml',
' - common1.yml',
' - common2.yml']
it_behaves_like 'LineLength handling',
'when .rubocop.yml inherits from another file',
['inherit_from: common.yml'],
['inherit_from:',
' - .rubocop_todo.yml',
' - common.yml']
it_behaves_like 'LineLength handling',
"when .rubocop.yml doesn't inherit",
['Style/For:',
' Enabled: false'],
['inherit_from: .rubocop_todo.yml',
'',
'Style/For:',
' Enabled: false']
context 'with Layout/LineLength:Max overridden' do
before do
create_file('.rubocop.yml', ['Layout/LineLength:',
" Max: #{line_length_max}",
" Enabled: #{line_length_enabled}"])
create_file('.rubocop_todo.yml', [''])
create_file('example.rb', <<~RUBY)
def f
#{' #' * 33}
if #{'a' * 80}
return y
end
z
end
RUBY
end
context 'when .rubocop.yml has Layout/LineLength:Max less than code base max' do
let(:line_length_max) { 90 }
let(:line_length_enabled) { true }
it "bases other cops' configuration on the overridden LineLength:Max" do
expect(cli.run(['--auto-gen-config'])).to eq(0)
expect($stdout.string).to include(<<~YAML)
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
Phase 1 of 2: run Layout/LineLength cop (skipped because the default Layout/LineLength:Max is overridden)
Phase 2 of 2: run all cops
YAML
# Layout/LineLength gets an Exclude property because Max is set in .rubocop.yml.
#
# Note that there is no Style/IfUnlessModifier offense registered due to the Max:90
# setting.
expect(File.readlines('.rubocop_todo.yml')
.drop_while { |line| line.start_with?('#') }.join)
.to eq(<<~YAML)
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: Max, AllowHeredoc, AllowURI, AllowQualifiedName, URISchemes, AllowRBSInlineAnnotation, AllowCopDirectives, AllowedPatterns, SplitStrings.
# URISchemes: http, https
Layout/LineLength:
Exclude:
- 'example.rb'
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example.rb'
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
inherit_from: .rubocop_todo.yml
Layout/LineLength:
Max: 90
Enabled: true
YAML
expect(RuboCop::CLI.new.run([])).to eq(0)
end
end
context 'when .rubocop.yml has Layout/LineLength disabled' do
let(:line_length_max) { 90 }
let(:line_length_enabled) { false }
it 'skips the cop from both phases of the run' do
expect(cli.run(['--auto-gen-config'])).to eq(0)
expect($stdout.string).to include(<<~YAML)
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
Phase 1 of 2: run Layout/LineLength cop (skipped because Layout/LineLength is disabled)
Phase 2 of 2: run all cops
YAML
# The code base max line length is 99, but the setting Enabled: false
# overrides that so no Layout/LineLength:Max setting is generated in
# .rubocop_todo.yml.
expect(File.readlines('.rubocop_todo.yml')
.drop_while { |line| line.start_with?('#') }.join)
.to eq(<<~YAML)
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example.rb'
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
Style/IfUnlessModifier:
Exclude:
- 'example.rb'
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
inherit_from: .rubocop_todo.yml
Layout/LineLength:
Max: 90
Enabled: false
YAML
$stdout = StringIO.new
expect(RuboCop::CLI.new.run(%w[--format simple])).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
1 file inspected, no offenses detected
OUTPUT
end
end
context 'when .rubocop.yml has Layout/LineLength:Max more than code base max' do
let(:line_length_max) { 150 }
let(:line_length_enabled) { true }
it "bases other cops' configuration on the overridden LineLength:Max" do
expect(cli.run(['--auto-gen-config'])).to eq(0)
expect($stdout.string).to include(<<~YAML)
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
Phase 1 of 2: run Layout/LineLength cop (skipped because the default Layout/LineLength:Max is overridden)
Phase 2 of 2: run all cops
YAML
# The code base max line length is 99, but the setting Max:150
# overrides that so no Layout/LineLength:Max setting is generated in
# .rubocop_todo.yml.
expect(File.readlines('.rubocop_todo.yml')
.drop_while { |line| line.start_with?('#') }.join)
.to eq(<<~YAML)
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example.rb'
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
Style/IfUnlessModifier:
Exclude:
- 'example.rb'
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
inherit_from: .rubocop_todo.yml
Layout/LineLength:
Max: 150
Enabled: true
YAML
$stdout = StringIO.new
expect(RuboCop::CLI.new.run(%w[--format simple])).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~OUTPUT)
1 file inspected, no offenses detected
OUTPUT
end
end
end
shared_examples 'overwrites todo file' do |description, code|
context "when .rubocop.yml contains #{description}" do
it 'overwrites an existing todo file' do
create_file('example1.rb', ['# frozen_string_literal: true',
'',
'x= 0 ',
'#' * 125,
'y ',
'puts x'])
create_file('example2.rb', <<~RUBY)
# frozen_string_literal: true
module M1::M2
class C # :nodoc:
def m
puts '!'
end
end
end
RUBY
create_file('.rubocop_todo.yml', <<~YAML)
Layout/LineLength:
Enabled: false
YAML
create_empty_file('other.yml')
create_file('.rubocop.yml', code)
expect(cli.run(['--auto-gen-config'])).to eq(0)
expect(File.readlines('.rubocop_todo.yml')[8..].map(&:chomp))
.to eq(['# Offense count: 1',
'# This cop supports safe autocorrection (--autocorrect).',
'# Configuration parameters: AllowForAlignment, ' \
'EnforcedStyleForExponentOperator, EnforcedStyleForRationalLiterals.',
'# SupportedStylesForExponentOperator: space, no_space',
'# SupportedStylesForRationalLiterals: space, no_space',
'Layout/SpaceAroundOperators:',
' Exclude:',
" - 'example1.rb'",
'',
'# Offense count: 2',
'# This cop supports safe autocorrection (--autocorrect).',
'# Configuration parameters: AllowInHeredoc.',
'Layout/TrailingWhitespace:',
' Exclude:',
" - 'example1.rb'",
'',
'# Offense count: 1',
'# This cop supports unsafe autocorrection (--autocorrect-all).',
'# Configuration parameters: EnforcedStyle, EnforcedStyleForClasses, ' \
'EnforcedStyleForModules.',
'# SupportedStyles: nested, compact',
'# SupportedStylesForClasses: ~, nested, compact',
'# SupportedStylesForModules: ~, nested, compact',
'Style/ClassAndModuleChildren:',
' Exclude:',
" - 'example2.rb'",
'',
'# Offense count: 1',
'# This cop supports safe autocorrection (--autocorrect).',
'# Configuration parameters: AllowHeredoc, AllowURI, AllowQualifiedName, ' \
'URISchemes, AllowRBSInlineAnnotation, AllowCopDirectives, ' \
'AllowedPatterns, SplitStrings.',
'# URISchemes: http, https',
'Layout/LineLength:',
' Max: 125'])
expect(File.readlines('.rubocop.yml').map(&:chomp)).to eq(code)
# Create new CLI instance to avoid using cached configuration.
new_cli = RuboCop::CLI.new
expect(new_cli.run(['example1.rb'])).to eq(0)
end
end
end
it_behaves_like 'overwrites todo file',
'only the inherit_from line',
['inherit_from: .rubocop_todo.yml']
# Makes the shared example work the same with the conditional as without.
ENV['HZPKCEAXTFQLOWB'] = 'true'
it_behaves_like 'overwrites todo file',
'a single line inherit_from in an ERB conditional',
['<% if ENV["HZPKCEAXTFQLOWB"] %>',
'inherit_from: .rubocop_todo.yml',
'<% end %>']
it_behaves_like 'overwrites todo file',
'a multiline inherit_from in an ERB conditional',
['<% if ENV["HZPKCEAXTFQLOWB"] %>',
'inherit_from:',
' - .rubocop_todo.yml',
' - other.yml',
'<% end %>']
it 'honors rubocop:disable comments' do
create_file('example1.rb', ['#' * 121,
'# rubocop:disable LineLength',
'#' * 125,
'y ',
'puts 123456',
'# rubocop:enable LineLength'])
create_file('.rubocop.yml', ['inherit_from: .rubocop_todo.yml'])
create_file('.rubocop_todo.yml', [''])
expect(cli.run(['--auto-gen-config'])).to eq(0)
expect(File.readlines('.rubocop_todo.yml')[8..].join)
.to eq(['# Offense count: 1',
'# This cop supports safe autocorrection (--autocorrect).',
'# Configuration parameters: AllowInHeredoc.',
'Layout/TrailingWhitespace:',
' Exclude:',
" - 'example1.rb'",
'',
'# Offense count: 2',
'# This cop supports safe autocorrection (--autocorrect).',
'Migration/DepartmentName:',
' Exclude:',
" - 'example1.rb'",
'',
'# Offense count: 1',
'# This cop supports unsafe autocorrection (--autocorrect-all).',
'# Configuration parameters: EnforcedStyle.',
'# SupportedStyles: always, always_true, never',
'Style/FrozenStringLiteralComment:',
' Exclude:',
" - '**/*.arb'",
" - 'example1.rb'",
'',
'# Offense count: 1',
'# This cop supports safe autocorrection (--autocorrect).',
'# Configuration parameters: Strict, AllowedNumbers, AllowedPatterns.',
'Style/NumericLiterals:',
' MinDigits: 7',
'',
'# Offense count: 1',
'# This cop supports safe autocorrection (--autocorrect).',
'# Configuration parameters: AllowHeredoc, AllowURI, AllowQualifiedName, ' \
'URISchemes, AllowRBSInlineAnnotation, AllowCopDirectives, ' \
'AllowedPatterns, SplitStrings.',
'# URISchemes: http, https',
'Layout/LineLength:',
' Max: 121',
''].join("\n"))
end
context 'when --only is used' do
before do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
class MyClass
def initialize
p "No documentation for class"
end
end
def f
#{' #' * 46}
if #{'a' * 120}
return y
end
z
end
RUBY
end
context 'when --only does not contain Layout/LineLength' do
it 'generates TODO only for the mentioned cop' do
$stdout = StringIO.new
expect(cli.run(['--auto-gen-config', '--only', 'Style/Documentation'])).to eq(0)
expect(File.readlines('.rubocop_todo.yml')
.drop_while { |line| line.start_with?('#') }.join)
.to eq(<<~YAML)
# Offense count: 1
# Configuration parameters: AllowedConstants.
Style/Documentation:
Exclude:
- 'spec/**/*'
- 'test/**/*'
- 'example.rb'
YAML
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~STRING)
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
Phase 1 of 2: run Layout/LineLength cop (skipped because a list of cops is passed to the `--only` flag)
Phase 2 of 2: run all cops
Inspecting 1 file
C
1 file inspected, 1 offense detected
Created .rubocop_todo.yml.
STRING
end
end
context 'when --only contains Layout/LineLength' do
it 'generates TODO for every cop listed in the --only flag' do
$stdout = StringIO.new
expect(cli.run(['--auto-gen-config', '--only', 'Layout/LineLength,Style/Documentation']))
.to eq(0)
expect(File.readlines('.rubocop_todo.yml')
.drop_while { |line| line.start_with?('#') }.join)
.to eq(<<~YAML)
# Offense count: 2
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: AllowHeredoc, AllowURI, AllowQualifiedName, URISchemes, AllowRBSInlineAnnotation, AllowCopDirectives, AllowedPatterns, SplitStrings.
# URISchemes: http, https
Layout/LineLength:
Max: 138
# Offense count: 1
# Configuration parameters: AllowedConstants.
Style/Documentation:
Exclude:
- 'spec/**/*'
- 'test/**/*'
- 'example.rb'
YAML
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~STRING)
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
Phase 1 of 2: run Layout/LineLength cop (skipped because a list of cops is passed to the `--only` flag)
Phase 2 of 2: run all cops
Inspecting 1 file
C
1 file inspected, 3 offenses detected
Created .rubocop_todo.yml.
STRING
end
end
end
context 'when --config is used' do
it 'can generate a todo list' do
create_file('example1.rb', ['$x = 0 ', '#' * 90, 'y ', 'puts x'])
create_file('dir/cop_config.yml', <<~YAML)
Layout/TrailingWhitespace:
Enabled: false
Layout/LineLength:
Max: 95
YAML
expect(cli.run(%w[--auto-gen-config --config dir/cop_config.yml])).to eq(0)
expect(Dir['.*']).to include('.rubocop_todo.yml')
todo_contents = File.read('.rubocop_todo.yml').lines[8..].join
expect(todo_contents).to eq(<<~YAML)
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example1.rb'
# Offense count: 1
# Configuration parameters: AllowedVariables.
Style/GlobalVars:
Exclude:
- 'example1.rb'
YAML
expect(File.read('dir/cop_config.yml')).to eq(<<~YAML)
inherit_from: ../.rubocop_todo.yml
Layout/TrailingWhitespace:
Enabled: false
Layout/LineLength:
Max: 95
YAML
# Checks that the command can be run again with config modified by itself.
expect(cli.run(%w[--auto-gen-config --config dir/cop_config.yml])).to eq(0)
end
context 'when --config is used with an absolute path' do
it 'can generate a todo list' do
create_file('example1.rb', ['$x = 0 ', '#' * 90, 'y ', 'puts x'])
create_empty_file('.rubocop.yml')
config_path = File.absolute_path('.rubocop.yml')
expect(cli.run(['--auto-gen-config', '--config', config_path])).to eq(0)
expect(Dir['.*']).to include('.rubocop_todo.yml')
# Check that paths are relativised correctly
expect(File.read('.rubocop_todo.yml')).to include(" - 'example1.rb'")
expect(File.read('.rubocop.yml')).to include('inherit_from: .rubocop_todo.yml')
# Checks that the command can be run again with config modified by itself.
expect(cli.run(['--auto-gen-config', '--config', config_path])).to eq(0)
end
end
it 'can generate a todo list if default .rubocop.yml exists' do
create_file('example1.rb', ['def foo', ' # bar', ' end'])
create_file('.rubocop.yml', <<~YAML)
AllCops:
DisabledByDefault: true
Layout/DefEndAlignment:
Enabled: true
YAML
create_empty_file('cop_config.yml')
expect(cli.run(%w[--auto-gen-config --config cop_config.yml])).to eq(0)
expect(Dir['.*']).to include('.rubocop_todo.yml')
todo_contents = File.read('.rubocop_todo.yml').lines[8..].join
expect(todo_contents).to eq(<<~YAML)
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: AllowForAlignment.
Layout/CommentIndentation:
Exclude:
- 'example1.rb'
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
# Configuration parameters: EnforcedStyleAlignWith.
# SupportedStylesAlignWith: start_of_line, def
Layout/DefEndAlignment:
Exclude:
- 'example1.rb'
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example1.rb'
YAML
expect(File.read('cop_config.yml')).to eq(<<~YAML)
inherit_from: .rubocop_todo.yml
YAML
end
end
context 'when working with a cop who do not support autocorrection' do
it 'can generate a todo list' do
create_file('example1.rb', <<~RUBY)
def fooBar; end
RUBY
create_file('.rubocop.yml', <<~YAML)
# The following cop does not support autocorrection.
Naming/MethodName:
Enabled: true
YAML
expect(cli.run(%w[--auto-gen-config])).to eq(0)
expect($stderr.string).to eq('')
# expect($stdout.string).to include('Created .rubocop_todo.yml.')
expect(Dir['.*']).to include('.rubocop_todo.yml')
todo_contents = File.read('.rubocop_todo.yml').lines[8..].join
expect(todo_contents).to eq(<<~YAML)
# Offense count: 1
# Configuration parameters: AllowedPatterns, ForbiddenIdentifiers, ForbiddenPatterns.
# SupportedStyles: snake_case, camelCase
# ForbiddenIdentifiers: __id__, __send__
Naming/MethodName:
EnforcedStyle: camelCase
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example1.rb'
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
inherit_from: .rubocop_todo.yml
# The following cop does not support autocorrection.
Naming/MethodName:
Enabled: true
YAML
end
end
context 'when cop is not safe to autocorrect' do
it 'can generate a todo list, with the appropriate flag' do
create_file('example1.rb', <<~RUBY)
# frozen_string_literal: true
users = (user.name + ' ' + user.email) * 5
puts users
RUBY
create_file('.rubocop.yml', <<~YAML)
# The following cop supports autocorrection but is not safe
Style/StringConcatenation:
Enabled: true
YAML
expect(cli.run(%w[--auto-gen-config])).to eq(0)
expect($stderr.string).to eq('')
expect(Dir['.*']).to include('.rubocop_todo.yml')
todo_contents = File.read('.rubocop_todo.yml').lines[8..].join
expect(todo_contents).to eq(<<~YAML)
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: Mode.
Style/StringConcatenation:
Exclude:
- 'example1.rb'
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
inherit_from: .rubocop_todo.yml
# The following cop supports autocorrection but is not safe
Style/StringConcatenation:
Enabled: true
YAML
end
end
context 'when existing config file has a YAML document start header' do
it 'inserts `inherit_from` key after header' do
create_file('example1.rb', <<~RUBY)
def foo; end
RUBY
create_file('.rubocop.yml', <<~YAML)
# rubocop config file
--- # YAML document start
# The following cop does not support autocorrection.
Naming/MethodName:
Enabled: true
YAML
expect(cli.run(%w[--auto-gen-config])).to eq(0)
expect($stderr.string).to eq('')
expect(Dir['.*']).to include('.rubocop_todo.yml')
todo_contents = File.read('.rubocop_todo.yml').lines[8..].join
expect(todo_contents).to eq(<<~YAML)
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example1.rb'
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
# rubocop config file
--- # YAML document start
inherit_from: .rubocop_todo.yml
# The following cop does not support autocorrection.
Naming/MethodName:
Enabled: true
YAML
end
end
context 'when working in a subdirectory' do
it 'can generate a todo list' do
create_file('dir/example1.rb', ['$x = 0 ', '#' * 90, 'y ', 'puts x'])
create_file('dir/.rubocop.yml', <<~YAML)
inherit_from: ../.rubocop.yml
YAML
create_file('.rubocop.yml', <<~YAML)
Layout/TrailingWhitespace:
Enabled: false
Layout/LineLength:
Max: 95
YAML
Dir.chdir('dir') { expect(cli.run(%w[--auto-gen-config])).to eq(0) }
expect($stderr.string).to eq('')
# expect($stdout.string).to include('Created .rubocop_todo.yml.')
expect(Dir['dir/.*']).to include('dir/.rubocop_todo.yml')
todo_contents = File.read('dir/.rubocop_todo.yml').lines[8..].join
expect(todo_contents).to eq(<<~YAML)
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# SupportedStyles: always, always_true, never
Style/FrozenStringLiteralComment:
Exclude:
- '**/*.arb'
- 'example1.rb'
# Offense count: 1
# Configuration parameters: AllowedVariables.
Style/GlobalVars:
Exclude:
- 'example1.rb'
YAML
expect(File.read('dir/.rubocop.yml')).to eq(<<~YAML)
inherit_from:
- .rubocop_todo.yml
- ../.rubocop.yml
YAML
end
end
context 'when inheriting from a URL' do
let(:remote_config_url) { 'https://example.com/foo/bar' }
before do
stub_request(:get, remote_config_url)
.to_return(status: 200, body: "Style/Encoding:\n Enabled: true")
end
context 'when there is a single entry' do
it 'can generate a todo list' do
create_file('dir/example1.rb', ['$x = 0 ', '#' * 90, 'y ', 'puts x'])
create_file('.rubocop.yml', <<~YAML)
inherit_from: #{remote_config_url}
YAML
expect(cli.run(%w[--auto-gen-config])).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to include(<<~YAML)
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
inherit_from:
- .rubocop_todo.yml
- #{remote_config_url}
YAML
end
end
context 'when there are multiple entries' do
it 'can generate a todo list' do
create_file('dir/example1.rb', ['$x = 0 ', '#' * 90, 'y ', 'puts x'])
create_file('.rubocop.yml', <<~YAML)
inherit_from:
- #{remote_config_url}
YAML
expect(cli.run(%w[--auto-gen-config])).to eq(0)
expect($stderr.string).to eq('')
expect($stdout.string).to include(<<~YAML)
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
YAML
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
inherit_from:
- .rubocop_todo.yml
- #{remote_config_url}
YAML
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cli/suggest_extensions_spec.rb | spec/rubocop/cli/suggest_extensions_spec.rb | # frozen_string_literal: true
require 'timeout'
RSpec.describe 'RuboCop::CLI SuggestExtensions', :isolated_environment do # rubocop:disable RSpec/DescribeClass
subject(:cli) { RuboCop::CLI.new }
include_context 'cli spec behavior'
describe 'extension suggestions', :config do
matcher :suggest_extensions do
supports_block_expectations
attr_accessor :install_suggested, :load_suggested
def extensions_to_install_suggest
@extensions_to_install_suggest ||= []
end
def extensions_to_load_suggest
@extensions_to_load_suggest ||= []
end
def install_suggestion_regex
Regexp.new(<<~REGEXP, Regexp::MULTILINE).freeze
Tip: Based on detected gems, the following RuboCop extension libraries might be helpful:
(?<suggestions>.*?)
^$
REGEXP
end
def load_suggestion_regex
Regexp.new(<<~REGEXP, Regexp::MULTILINE).freeze
The following RuboCop extension libraries are installed but not loaded in config:
(?<suggestions>.*?)
^$
REGEXP
end
def find_suggestions
actual.call
suggestions = (install_suggestion_regex.match($stdout.string) || {})[:suggestions]
self.install_suggested = suggestions ? suggestions.scan(/(?<=\* )[a-z0-9_-]+\b/.freeze) : []
suggestions = (load_suggestion_regex.match($stdout.string) || {})[:suggestions]
self.load_suggested = suggestions ? suggestions.scan(/(?<=\* )[a-z0-9_-]+\b/.freeze) : []
end
chain :to_install do |*extensions|
@extensions_to_install_suggest = extensions
end
chain :to_load do |*extensions|
@extensions_to_load_suggest = extensions
end
match do
find_suggestions
install_suggested == extensions_to_install_suggest &&
load_suggested == extensions_to_load_suggest
end
match_when_negated do
find_suggestions
install_suggested.none? && load_suggested.none?
end
failure_message do
'expected to suggest extensions to install ' \
"[#{extensions_to_install_suggest.join(', ')}], " \
"load [#{extensions_to_load_suggest.join(', ')}], " \
"but got [#{install_suggested.join(', ')}], [#{load_suggested.join(', ')}]"
end
failure_message_when_negated do
'expected to not suggest extensions, ' \
"but got [#{install_suggested.join(', ')}] as install suggestion, " \
"[#{load_suggested.join(', ')}] as load suggestion"
end
end
let(:loaded_plugins) { %w[] }
let(:loaded_features) { %w[] }
let(:lockfile) do
create_file('Gemfile.lock', <<~LOCKFILE)
GEM
specs:
rake (13.0.1)
rspec (3.9.0)
PLATFORMS
ruby
DEPENDENCIES
rake (~> 13.0)
rspec (~> 3.7)
LOCKFILE
end
before do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
puts 'ok'
RUBY
# Ensure that these specs works in CI, since the feature is generally
# disabled in when ENV['CI'] is set.
allow(ENV).to receive(:fetch).and_call_original
allow(ENV).to receive(:fetch).with('CI', nil).and_return(false)
# Mock the lockfile to be parsed by bundler
allow(Bundler).to receive(:default_lockfile)
.and_return(lockfile ? Pathname.new(lockfile) : nil)
allow_any_instance_of(RuboCop::Config).to receive(:loaded_plugins).and_return(loaded_plugins)
allow_any_instance_of(RuboCop::Config).to receive(:loaded_features)
.and_return(loaded_features)
end
context 'when bundler is not loaded' do
before do
hide_const('Bundler')
end
it 'does not show the suggestion' do
expect { cli.run(['example.rb']) }.not_to suggest_extensions
expect($stderr.string).to be_blank
end
end
context 'when there are gems to suggest' do
context 'that are not installed' do
it 'shows the suggestion' do
expect do
cli.run(['example.rb'])
end.to suggest_extensions.to_install('rubocop-rake', 'rubocop-rspec')
end
end
context 'that are dependencies' do
before do
create_file('Gemfile.lock', <<~TEXT)
GEM
remote: https://rubygems.org/
specs:
rake (13.0.1)
rspec (3.9.0)
rspec-core (~> 3.9.0)
rspec-core (3.9.3)
rubocop-rake (0.5.1)
rubocop-rspec (2.0.1)
DEPENDENCIES
rake (~> 13.0)
rspec (~> 3.7)
rubocop-rake (~> 0.5)
rubocop-rspec (~> 2.0.0)
TEXT
end
it 'does not show the load suggestion' do
expect do
cli.run(['example.rb'])
end.to suggest_extensions.to_load('rubocop-rake', 'rubocop-rspec')
end
end
context 'that some are dependencies' do
before do
create_file('Gemfile.lock', <<~TEXT)
GEM
remote: https://rubygems.org/
specs:
rake (13.0.1)
rspec (3.9.0)
rspec-core (~> 3.9.0)
rspec-core (3.9.3)
rubocop-rake (0.5.1)
DEPENDENCIES
rake (~> 13.0)
rspec (~> 3.7)
rubocop-rake (~> 0.5)
TEXT
end
it 'only suggests unused gems' do
expect do
cli.run(['example.rb'])
end.to suggest_extensions.to_install('rubocop-rspec').to_load('rubocop-rake')
end
end
context 'that are added by dependencies' do
let(:lockfile) do
create_file('Gemfile.lock', <<~TEXT)
GEM
specs:
rake (13.0.1)
rspec (3.9.0)
shared-gem (1.0.0)
rubocop-rake (0.5.1)
rubocop-rspec (2.0.1)
DEPENDENCIES
rake (~> 13.0)
rspec (~> 3.7)
shared-gem (~> 1.0.0)
TEXT
end
it 'does not show the suggestion' do
expect do
cli.run(['example.rb'])
end.to suggest_extensions.to_load('rubocop-rake', 'rubocop-rspec')
end
end
context 'that are dependencies and required plugins in config' do
let(:lockfile) do
create_file('Gemfile.lock', <<~TEXT)
GEM
remote: https://rubygems.org/
specs:
rake (13.0.1)
rspec (3.9.0)
rspec-core (~> 3.9.0)
rspec-core (3.9.3)
rubocop-rake (0.5.1)
rubocop-rspec (2.0.1)
DEPENDENCIES
rake (~> 13.0)
rspec (~> 3.7)
rubocop-rake (~> 0.5)
rubocop-rspec (~> 2.0.0)
TEXT
end
let(:loaded_plugins) { %w[rubocop-rspec rubocop-rake] }
it 'does not show the suggestion' do
expect { cli.run(['example.rb']) }.not_to suggest_extensions
end
end
context 'that are dependencies and required features in config' do
let(:lockfile) do
create_file('Gemfile.lock', <<~TEXT)
GEM
remote: https://rubygems.org/
specs:
rake (13.0.1)
rspec (3.9.0)
rspec-core (~> 3.9.0)
rspec-core (3.9.3)
rubocop-rake (0.5.1)
rubocop-rspec (2.0.1)
DEPENDENCIES
rake (~> 13.0)
rspec (~> 3.7)
rubocop-rake (~> 0.5)
rubocop-rspec (~> 2.0.0)
TEXT
end
let(:loaded_features) { %w[rubocop-rspec rubocop-rake] }
it 'does not show the suggestion' do
expect { cli.run(['example.rb']) }.not_to suggest_extensions
end
end
end
context 'when gems with suggestions are not primary dependencies' do
let(:lockfile) do
create_file('Gemfile.lock', <<~LOCKFILE)
GEM
specs:
shared-gem (1.0.0)
rake (13.0.1)
rspec (3.9.0)
PLATFORMS
ruby
DEPENDENCIES
shared-gem (~> 1.0)
LOCKFILE
end
it 'does not show the suggestion' do
expect { cli.run(['example.rb']) }.not_to suggest_extensions
end
end
context 'when there are multiple gems loaded that have the same suggestion' do
let(:lockfile) do
create_file('Gemfile.lock', <<~LOCKFILE)
GEM
specs:
rspec (3.9.0)
rspec-rails (4.0.1)
PLATFORMS
ruby
DEPENDENCIES
rspec (~> 3.9)
rspec-rails (~> 4.0)
LOCKFILE
end
it 'shows the suggestion' do
expect { cli.run(['example.rb']) }.to suggest_extensions.to_install(
'rubocop-rspec', 'rubocop-rspec_rails'
)
end
end
context 'with AllCops/SuggestExtensions: false' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
SuggestExtensions: false
YAML
end
it 'does not show the suggestion' do
expect { cli.run(['example.rb']) }.not_to suggest_extensions
end
end
context 'with AllCops/SuggestExtensions: true' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
SuggestExtensions: true
YAML
end
let(:lockfile) do
create_file('Gemfile.lock', <<~LOCKFILE)
GEM
specs:
rspec (3.9.0)
rspec-rails (4.0.1)
PLATFORMS
ruby
DEPENDENCIES
rspec (~> 3.9)
rspec-rails (~> 4.0)
LOCKFILE
end
it 'shows the suggestion' do
expect { cli.run(['example.rb']) }.to suggest_extensions.to_install(
'rubocop-rspec', 'rubocop-rspec_rails'
)
end
end
context 'when an extension is disabled in AllCops/SuggestExtensions' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
SuggestExtensions:
rubocop-rake: false
YAML
end
it 'show the suggestion for non-disabled extensions' do
expect { cli.run(['example.rb']) }.to suggest_extensions.to_install('rubocop-rspec')
end
end
context 'when in CI mode' do
before { allow(ENV).to receive(:fetch).with('CI', nil).and_return(true) }
it 'does not show the suggestion' do
expect { cli.run(['example.rb']) }.not_to suggest_extensions
end
end
context 'when given --only' do
it 'does not show the suggestion' do
expect { cli.run(['example.rb', '--only', 'Style/Alias']) }.not_to suggest_extensions
end
end
context 'when given --debug' do
it 'does not show the suggestion' do
expect { cli.run(['example.rb', '--debug']) }.not_to suggest_extensions
end
end
context 'when given --list-target-files' do
it 'does not show the suggestion' do
expect { cli.run(['example.rb', '--list-target-files']) }.not_to suggest_extensions
end
end
context 'when given --out' do
it 'does not show the suggestion' do
expect { cli.run(['example.rb', '--out', 'output.txt']) }.not_to suggest_extensions
end
end
context 'when given --stdin' do
it 'does not show the suggestion' do
$stdin = StringIO.new('p $/')
expect { cli.run(['--stdin', 'example.rb']) }.not_to suggest_extensions
ensure
$stdin = STDIN
end
end
context 'when given a non-supported formatter' do
it 'does not show the suggestion' do
expect { cli.run(['example.rb', '--format', 'simple']) }.not_to suggest_extensions
end
end
context 'when given an invalid path' do
it 'does not show the suggestion' do
expect { cli.run(['example1.rb']) }.not_to suggest_extensions
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/cli/options_spec.rb | spec/rubocop/cli/options_spec.rb | # frozen_string_literal: true
require 'open3'
RSpec.describe 'RuboCop::CLI options', :isolated_environment do # rubocop:disable RSpec/DescribeClass
subject(:cli) { RuboCop::CLI.new }
include_context 'cli spec behavior'
let(:rubocop) { "#{RuboCop::ConfigLoader::RUBOCOP_HOME}/exe/rubocop" }
before do
RuboCop::ConfigLoader.default_configuration = nil
RuboCop::ConfigLoader.clear_options
end
describe '--parallel' do
if RuboCop::Platform.windows?
context 'on Windows' do
before do
create_file('test_1.rb', ['puts "hello world"'])
create_file('test_2.rb', ['puts "what a lovely day"'])
end
it 'prints a warning' do
cli.run ['-P']
expect($stderr.string).to include('Process.fork is not supported by this Ruby')
end
end
else
context 'combined with AllCops:UseCache:false' do
before { create_file('.rubocop.yml', ['AllCops:', ' UseCache: false']) }
it 'fails with an error message' do
cli.run %w[-P]
expect($stderr.string)
.to include('-P/--parallel uses caching to speed up execution, so ' \
'combining with AllCops: UseCache: false is not allowed.')
end
end
context 'on Unix-like systems' do
it 'prints a message if --debug is specified' do
cli.run ['--parallel', '--debug']
expect($stdout.string).to match(
/Skipping parallel inspection: only a single file needs inspection/
)
end
it 'does not print a message if --debug is not specified' do
cli.run ['--parallel']
expect($stdout.string).not_to match(/Running parallel inspection/)
end
end
context 'in combination with --ignore-parent-exclusion' do
before do
create_file('.rubocop.yml', ['AllCops:', ' Exclude:', ' - subdir/*'])
create_file('subdir/.rubocop.yml', ['AllCops:', ' Exclude:', ' - foobar'])
create_file('subdir/test.rb', 'puts 1')
end
it 'does ignore the exclusion in the parent directory configuration' do
Dir.chdir('subdir') { cli.run ['--parallel', '--ignore-parent-exclusion'] }
expect($stdout.string).to match(/Inspecting 1 file/)
end
end
context 'in combination with --force-default-config' do
before do
create_file('.rubocop.yml', ['ALLCOPS:', # Faulty configuration
' Exclude:',
' - subdir/*'])
create_file('test.rb', 'puts 1')
end
it 'does not parse local configuration' do
cli.run ['--parallel', '--force-default-config']
expect($stdout.string).to match(/Inspecting 1 file/)
end
end
end
end
if RuboCop::Server.support_server?
context 'when supporting server' do
describe '--server' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
NewCops: enable
YAML
create_file('example.rb', '"hello"')
end
after do
`ruby -I . "#{rubocop}" --stop-server`
end
it 'starts server and inspects' do
options = '--server --only Style/FrozenStringLiteralComment,Style/StringLiterals'
output = `ruby -I . "#{rubocop}" #{options}`
expect(output).to match(
/RuboCop server starting on \d+\.\d+\.\d+\.\d+:\d+\.\nInspecting 1 file/
)
end
end
describe '--no-server' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
NewCops: enable
YAML
create_file('example.rb', '"hello"')
end
it 'starts server and inspects' do
options = '--no-server --only Style/FrozenStringLiteralComment,Style/StringLiterals'
output = `ruby -I . "#{rubocop}" #{options}`
expect(output).not_to match(/RuboCop server starting on \d+\.\d+\.\d+\.\d+:\d+\./)
expect(output).to include(<<~RESULT)
Inspecting 1 file
C
Offenses:
example.rb:1:1: C: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
"hello"
^
example.rb:1:1: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
"hello"
^^^^^^^
1 file inspected, 2 offenses detected, 2 offenses autocorrectable
RESULT
end
end
describe '--start-server' do
after do
`ruby -I . "#{rubocop}" --stop-server`
end
it 'start server process and displays an information message' do
output = `ruby -I . "#{rubocop}" --start-server`
expect(output).to match(/RuboCop server starting on \d+\.\d+\.\d+\.\d+:\d+\./)
end
end
describe '--stop-server' do
before do
`ruby -I . "#{rubocop}" --start-server`
end
it 'stops server process and displays an information message' do
output = `ruby -I . "#{rubocop}" --stop-server`
expect(output).to eq ''
end
end
describe '--restart-server' do
before do
`ruby -I . "#{rubocop}" --start-server`
end
after do
`ruby -I . "#{rubocop}" --stop-server`
end
it 'restart server process and displays an information message' do
output = `ruby -I . "#{rubocop}" --restart-server`
expect(output).to match(/RuboCop server starting on \d+\.\d+\.\d+\.\d+:\d+\./)
end
end
describe '--server-status' do
context 'when server is not running' do
it 'displays server status' do
output = `ruby -I . "#{rubocop}" --server-status`
expect(output).to match(/RuboCop server is not running./)
end
end
context 'when server is running' do
before do
`ruby -I . "#{rubocop}" --start-server`
end
after do
`ruby -I . "#{rubocop}" --stop-server`
end
it 'displays server status' do
output = `ruby -I . "#{rubocop}" --server-status`
expect(output).to match(/RuboCop server \(\d+\) is running./)
end
end
end
end
else
context 'when not supporting server' do
describe 'no server options' do
it 'displays a warning message' do
stdout, stderr, status = Open3.capture3("ruby -I . \"#{rubocop}\"")
expect(stdout).to eq(<<~RESULT)
Inspecting 0 files
0 files inspected, no offenses detected
RESULT
expect(stderr).not_to include("RuboCop server is not supported by this Ruby.\n")
expect(status.exitstatus).to eq 0
end
end
describe '--start-server' do
it 'displays a warning message' do
stdout, stderr, status = Open3.capture3("ruby -I . \"#{rubocop}\" --start-server")
expect(stdout).to eq ''
expect(stderr).to include("RuboCop server is not supported by this Ruby.\n")
expect(status.exitstatus).to eq 2
end
end
end
end
describe '--list-target-files' do
context 'when there are no files' do
it 'prints nothing with -L' do
cli.run ['-L']
expect($stdout.string).to be_empty
end
it 'prints nothing with --list-target-files' do
cli.run ['--list-target-files']
expect($stdout.string).to be_empty
end
end
context 'when there are some files' do
before do
create_file('show.rabl2', 'object @user => :person')
create_file('show.rabl', 'object @user => :person')
create_file('app.rb', 'puts "hello world"')
create_file('Gemfile', <<~RUBY)
source "https://rubygems.org"
gem "rubocop"
RUBY
create_file('lib/helper.rb', 'puts "helpful"')
end
context 'when there are no includes or excludes' do
it 'prints known ruby files' do
cli.run ['-L']
expect($stdout.string.split("\n")).to contain_exactly(
'app.rb', 'Gemfile', 'lib/helper.rb', 'show.rabl'
)
end
end
context 'when there is an include and exclude' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- Gemfile
Include:
- "**/*.rb"
- "**/*.rabl"
- "**/*.rabl2"
YAML
end
it 'prints the included files and not the excluded ones' do
cli.run ['--list-target-files']
expect($stdout.string.split("\n")).to contain_exactly(
'app.rb', 'lib/helper.rb', 'show.rabl', 'show.rabl2'
)
end
end
end
end
describe '--version' do
it 'exits cleanly' do
expect(cli.run(['-v'])).to eq(0)
expect(cli.run(['--version'])).to eq(0)
expect($stdout.string).to eq("#{RuboCop::Version::STRING}\n" * 2)
end
end
describe '-V' do
it 'exits cleanly' do
expect(cli.run(['-V'])).to eq(0)
expect($stdout.string).to include(RuboCop::Version::STRING)
expect($stdout.string).to match(/Parser \d+\.\d+\.\d+/)
expect($stdout.string).to match(/rubocop-ast \d+\.\d+\.\d+/)
expect($stdout.string).to match(/analyzing as Ruby #{RuboCop::TargetRuby::DEFAULT_VERSION}/o)
end
context 'when requiring extension cops' do
before do
create_file('.rubocop.yml', <<~YAML)
plugins:
- rubocop-performance
- rubocop-rspec
YAML
end
it 'shows with version of extension cops' do
# Run in different process that requiring rubocop-performance and rubocop-rspec
# does not affect other testing processes.
output = `ruby -I . "#{rubocop}" -V --disable-pending-cops`
expect(output).to include(RuboCop::Version::STRING)
expect(output).to match(/Parser \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-ast \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-performance \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-rspec \d+\.\d+\.\d+/)
end
end
context 'when requiring extension cops in multiple layers' do
before do
create_file('.rubocop-parent.yml', <<~YAML)
plugins:
- rubocop-performance
YAML
create_file('.rubocop.yml', <<~YAML)
inherit_from: ./.rubocop-parent.yml
plugins:
- rubocop-rspec
YAML
end
it 'shows with version of extension cops' do
# Run in different process that requiring rubocop-performance and rubocop-rspec
# does not affect other testing processes.
output = `ruby -I . "#{rubocop}" -V --disable-pending-cops`
expect(output).to include(RuboCop::Version::STRING)
expect(output).to match(/Parser \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-ast \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-performance \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-rspec \d+\.\d+\.\d+/)
end
end
context 'when requiring redundant extension cop' do
before do
create_file('ext.yml', <<~YAML)
plugins:
- rubocop-rspec
YAML
create_file('.rubocop.yml', <<~YAML)
inherit_from: ext.yml
plugins:
- rubocop-performance
- rubocop-rspec
YAML
end
it 'shows with version of each extension cop once' do
output = `ruby -I . "#{rubocop}" -V --disable-pending-cops`
expect(output).to include(RuboCop::Version::STRING)
expect(output).to match(/Parser \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-ast \d+\.\d+\.\d+/)
expect(output).to match(
/- rubocop-performance \d+\.\d+\.\d+\n - rubocop-rspec \d+\.\d+\.\d+\n\z/
)
end
end
context 'when there are pending cops' do
let(:pending_cop_warning) { <<~PENDING_COP_WARNING }
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file.
PENDING_COP_WARNING
before do
create_file('.rubocop.yml', <<~YAML)
require: rubocop_ext
AllCops:
NewCops: pending
Style/SomeCop:
Description: Something
Enabled: pending
VersionAdded: '1.6'
YAML
create_file('rubocop_ext.rb', <<~RUBY)
module RuboCop
module Cop
module Style
class SomeCop < Base
end
end
end
end
RUBY
create_file('redirect.rb', '$stderr = STDOUT')
end
it 'does not show warnings for pending cops' do
output = `ruby -I . "#{rubocop}" --require redirect.rb -V`
expect(output).to include(RuboCop::Version::STRING)
expect(output).to match(/Parser \d+\.\d+\.\d+/)
expect(output).to match(/rubocop-ast \d+\.\d+\.\d+/)
expect(output).not_to include(pending_cop_warning)
end
end
context 'when the config contains erb' do
before do
create_file('.rubocop.yml', <<~YAML)
<% if true %>
<% end %>
YAML
end
it 'exits cleanly' do
expect(cli.run(['-V'])).to eq(0)
expect($stdout.string).to include(RuboCop::Version::STRING)
end
end
context 'when run in a subfolder with `.rubocop.yml` specifying `TargetRubyVersion`' do
before do
create_file('subdir/.rubocop.yml', <<~YAML)
AllCops:
TargetRubyVersion: 3.0
YAML
end
it 'shows that Ruby version in the output' do
Dir.chdir('subdir') { cli.run ['-V'] }
expect($stdout.string).to match(/analyzing as Ruby 3\.0/)
end
end
end
describe '--only' do
context 'when one cop is given' do
it 'runs just one cop' do
# The disable comment should not be reported as unnecessary (even if
# it is) since --only overrides configuration.
create_file('example.rb', ['# rubocop:disable LineLength', 'if x== 0 ', "\ty", 'end'])
# IfUnlessModifier depends on the configuration of LineLength.
expect(cli.run(['--format', 'simple',
'--only', 'Style/IfUnlessModifier',
'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(['== example.rb ==',
'C: 2: 1: [Correctable] Style/IfUnlessModifier: Favor modifier if ' \
'usage when having a single-line body. Another good ' \
'alternative is the usage of control flow &&/||.',
'',
'1 file inspected, 1 offense detected, 1 offense autocorrectable',
''].join("\n"))
end
it 'exits with error if an incorrect cop name is passed' do
create_file('example.rb', ['if x== 0 ', "\ty", 'end'])
expect(cli.run(['--only', 'Style/123'])).to eq(2)
expect($stderr.string).to include('Unrecognized cop or department: Style/123.')
end
it 'displays correction candidate if an incorrect cop name is given' do
create_file('example.rb', ['x'])
expect(cli.run(['--only', 'Style/BlockComment'])).to eq(2)
expect($stderr.string).to include('Unrecognized cop or department: Style/BlockComment.')
expect($stderr.string).to include('Did you mean? Style/BlockComments')
end
it 'exits with error if an empty string is given' do
create_file('example.rb', 'x')
expect(cli.run(['--only', ''])).to eq(2)
expect($stderr.string).to include('Unrecognized cop or department: .')
end
it '`Lint/Syntax` must be enabled even if `--only` is given `Style/StringLiterals` only' do
create_file('example.rb', '1 /// 2')
expect(cli.run(['--only', 'Style/StringLiterals', 'example.rb'])).to eq(1)
expect(
$stdout.string
).to include('example.rb:1:7: F: Lint/Syntax: unexpected token tINTEGER')
end
%w[Syntax Lint/Syntax].each do |name|
it "only checks syntax if #{name} is given" do
create_file('example.rb', 'x ')
expect(cli.run(['--only', name])).to eq(0)
expect($stdout.string).to include('no offenses detected')
end
end
%w[Lint/RedundantCopDisableDirective
RedundantCopDisableDirective].each do |name|
it "exits with error if cop name #{name} is passed" do
create_file('example.rb', ['if x== 0 ', "\ty", 'end'])
expect(cli.run(['--only', 'RedundantCopDisableDirective'])).to eq(2)
expect($stderr.string)
.to include(
'Lint/RedundantCopDisableDirective cannot be used with --only.'
)
end
end
it 'accepts cop names from plugins' do
create_file('.rubocop.yml', <<~YAML)
require: rubocop_ext
Style/SomeCop:
Description: Something
Enabled: true
YAML
create_file('rubocop_ext.rb', <<~RUBY)
module RuboCop
module Cop
module Style
class SomeCop < Base
end
end
end
end
RUBY
create_file('redirect.rb', '$stderr = STDOUT')
rubocop = "#{RuboCop::ConfigLoader::RUBOCOP_HOME}/exe/rubocop"
# Since we define a new cop class, we have to do this in a separate
# process. Otherwise, the extra cop will affect other specs.
output = `ruby -I . "#{rubocop}" --require redirect.rb --only Style/SomeCop`
# Excludes a warning when new `Enabled: pending` status cop is specified
# in config/default.yml.
output_excluding_warn_for_pending_cops = output.split("\n").last(4).join("\n") << "\n"
expect(output_excluding_warn_for_pending_cops)
.to eq(<<~RESULT)
Inspecting 2 files
..
2 files inspected, no offenses detected
RESULT
end
context 'when specifying a pending cop' do
# Since we define a new cop class, we have to do this in a separate
# process. Otherwise, the extra cop will affect other specs.
let(:output) { `ruby -I . "#{rubocop}" --require redirect.rb --only Style/SomeCop` }
let(:pending_cop_warning) { <<~PENDING_COP_WARNING }
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file.
PENDING_COP_WARNING
let(:inspected_output) { <<~INSPECTED_OUTPUT }
Inspecting 2 files
..
2 files inspected, no offenses detected
INSPECTED_OUTPUT
let(:versioning_manual_url) { <<~VERSIONING_MANUAL_URL.chop }
For more information: https://docs.rubocop.org/rubocop/versioning.html
VERSIONING_MANUAL_URL
before do
create_file('rubocop_ext.rb', <<~RUBY)
module RuboCop
module Cop
module Style
class SomeCop < Base
end
end
end
end
RUBY
create_file('redirect.rb', '$stderr = STDOUT')
end
context 'when Style department is enabled' do
let(:new_cops_option) { '' }
let(:version_added) { "VersionAdded: '0.80'" }
before do
create_file('.rubocop.yml', <<~YAML)
require: rubocop_ext
AllCops:
DefaultFormatter: progress
#{new_cops_option}
Style/SomeCop:
Description: Something
Enabled: pending
#{version_added}
YAML
end
context 'when `VersionAdded` is specified' do
it 'accepts cop names from plugins with a pending cop warning' do
expect(output).to start_with(pending_cop_warning)
expect(output).to end_with(inspected_output)
remaining_range = pending_cop_warning.length..-(inspected_output.length + 1)
pending_cops = output[remaining_range]
expect(pending_cops)
.to include("Style/SomeCop: # new in 0.80\n Enabled: true")
manual_url = output[remaining_range].split("\n").last
expect(manual_url).to eq(versioning_manual_url)
end
end
context 'when `VersionAdded` is not specified' do
let(:version_added) { '' }
it 'accepts cop names from plugins with a pending cop warning' do
expect(output).to start_with(pending_cop_warning)
expect(output).to end_with(inspected_output)
remaining_range = pending_cop_warning.length..-(inspected_output.length + 1)
pending_cops = output[remaining_range]
expect(pending_cops)
.to include("Style/SomeCop: # new in N/A\n Enabled: true")
manual_url = output[remaining_range].split("\n").last
expect(manual_url).to eq(versioning_manual_url)
end
end
context 'when using `--disable-pending-cops` command-line option' do
let(:option) { '--disable-pending-cops' }
let(:output) { `ruby -I . "#{rubocop}" --require redirect.rb #{option}` }
it 'does not display a pending cop warning' do
expect(output).not_to start_with(pending_cop_warning)
end
end
context 'when using `--enable-pending-cops` command-line option' do
let(:option) { '--enable-pending-cops' }
let(:output) { `ruby -I . "#{rubocop}" --require redirect.rb #{option}` }
it 'does not display a pending cop warning' do
expect(output).not_to start_with(pending_cop_warning)
end
end
context 'when specifying `NewCops: pending` in .rubocop.yml' do
let(:new_cops_option) { 'NewCops: pending' }
let(:output) { `ruby -I . "#{rubocop}" --require redirect.rb` }
it 'displays a pending cop warning' do
expect(output).to start_with(pending_cop_warning)
end
end
context 'when specifying `NewCops: disable` in .rubocop.yml' do
let(:new_cops_option) { 'NewCops: disable' }
let(:output) { `ruby -I . "#{rubocop}" --require redirect.rb` }
it 'does not display a pending cop warning' do
expect(output).not_to start_with(pending_cop_warning)
end
end
context 'when specifying `NewCops: enable` in .rubocop.yml' do
let(:new_cops_option) { 'NewCops: enable' }
let(:output) { `ruby -I . "#{rubocop}" --require redirect.rb` }
it 'does not display a pending cop warning' do
expect(output).not_to start_with(pending_cop_warning)
end
end
end
context 'when Style department is disabled' do
before do
create_file('.rubocop.yml', <<~YAML)
require: rubocop_ext
Lint:
Enabled: false
Style:
Enabled: false
Layout:
Enabled: false
Gemspec:
Enabled: false
Naming:
Enabled: false
Security:
Enabled: false
Metrics:
Enabled: false
Style/SomeCop:
Description: Something
Enabled: pending
YAML
end
it 'does not show pending cop warning' do
expect(output).to eq(inspected_output)
end
end
end
context 'when specifying disabled `Layout/LineLength` cop' do
let(:line) { "Object::#{'A' * 100}".inspect }
it 'enables the given cop' do
create_file('example.rb', [line])
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Enabled: false
Max: 80
YAML
expect(cli.run(['--format', 'simple',
'--only', 'Layout/LineLength',
'example.rb'])).to be_zero
expect($stderr.string).to eq('')
expect($stdout.string)
.to eq(<<~RESULT)
1 file inspected, no offenses detected
RESULT
end
end
context 'without using namespace' do
it 'runs just one cop' do
create_file('example.rb', ['if x== 0 ', "\ty", 'end'])
expect(cli.run(['--format', 'simple',
'--display-cop-names',
'--only', 'IfUnlessModifier',
'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(['== example.rb ==',
'C: 1: 1: [Correctable] Style/IfUnlessModifier: Favor modifier if ' \
'usage when having a single-line body. Another good ' \
'alternative is the usage of control flow &&/||.',
'',
'1 file inspected, 1 offense detected, 1 offense autocorrectable',
''].join("\n"))
end
end
it 'enables the given cop' do
create_file('example.rb',
['x = 0 ',
# Disabling comments still apply.
'# rubocop:disable Layout/TrailingWhitespace',
'y = 1 '])
create_file('.rubocop.yml', <<~YAML)
Layout/TrailingWhitespace:
Enabled: false
YAML
expect(cli.run(['--format', 'simple',
'--only', 'Layout/TrailingWhitespace',
'example.rb'])).to eq(1)
expect($stderr.string).to eq('')
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 6: [Correctable] Layout/TrailingWhitespace: Trailing whitespace detected.
1 file inspected, 1 offense detected, 1 offense autocorrectable
RESULT
end
end
context 'when several cops are given' do
it 'runs the given cops' do
create_file('example.rb', ['if x== 100000000000000 ', "\ty", 'end'])
expect(cli.run(['--format', 'simple',
'--only',
'Style/IfUnlessModifier,Layout/IndentationStyle,' \
'Layout/SpaceAroundOperators',
'example.rb'])).to eq(1)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~RESULT)
== example.rb ==
C: 1: 1: [Correctable] Style/IfUnlessModifier: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.
C: 1: 5: [Correctable] Layout/SpaceAroundOperators: Surrounding space missing for operator ==.
C: 2: 1: [Correctable] Layout/IndentationStyle: Tab detected in indentation.
1 file inspected, 3 offenses detected, 3 offenses autocorrectable
RESULT
end
context 'and --lint' do
it 'runs the given cops plus all enabled lint cops' do
create_file('example.rb', ['if x== 100000000000000 ', "\ty = 3", ' end'])
create_file('.rubocop.yml', <<~YAML)
Layout/EndAlignment:
Enabled: false
YAML
expect(cli.run(['--format', 'simple', '--only',
'Layout/IndentationStyle,Layout/SpaceAroundOperators',
'--lint', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 5: [Correctable] Layout/SpaceAroundOperators: Surrounding space missing for operator ==.
C: 2: 1: [Correctable] Layout/IndentationStyle: Tab detected in indentation.
W: 2: 2: [Correctable] Lint/UselessAssignment: Useless assignment to variable - y.
1 file inspected, 3 offenses detected, 3 offenses autocorrectable
RESULT
end
end
end
context 'when a namespace is given' do
it 'runs all enabled cops in that namespace' do
create_file('example.rb', ['if x== 100000000000000 ', " #{'#' * 130}", "\ty", 'end'])
expect(cli.run(%w[-f offenses --only Layout example.rb])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
1 Layout/CommentIndentation [Safe Correctable]
1 Layout/IndentationStyle [Safe Correctable]
1 Layout/IndentationWidth [Safe Correctable]
1 Layout/LineLength [Safe Correctable]
1 Layout/SpaceAroundOperators [Safe Correctable]
1 Layout/TrailingWhitespace [Safe Correctable]
--
6 Total in 1 files
RESULT
end
end
context 'when three namespaces are given' do
it 'runs all enabled cops in those namespaces' do
create_file('example.rb', ['if x== 100000000000000 ', " # #{'-' * 130}", "\ty", 'end'])
create_file('.rubocop.yml', <<~YAML)
Layout/SpaceAroundOperators:
Enabled: false
YAML
expect(cli.run(%w[-f o --only Metrics,Style,Layout example.rb])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
1 Layout/CommentIndentation [Safe Correctable]
1 Layout/IndentationStyle [Safe Correctable]
1 Layout/IndentationWidth [Safe Correctable]
1 Layout/LineLength [Safe Correctable]
1 Layout/TrailingWhitespace [Safe Correctable]
1 Style/FrozenStringLiteralComment [Unsafe Correctable]
1 Style/NumericLiterals [Safe Correctable]
--
7 Total in 1 files
RESULT
end
end
context 'when a cop name is not specified' do
it 'displays how to use `--only` option' do
expect(cli.run(%w[--except -a Lint/NumberConversion])).to eq(2)
expect($stderr.string).to eq(<<~MESSAGE)
--except argument should be [COP1,COP2,...].
MESSAGE
end
end
context 'when the cop is defined in a require', :restore_registry do
before do
create_file('.rubocop.yml', <<~YAML)
require:
- './custom_cops.rb'
YAML
create_file('example.rb', 'foo(:bar)')
end
context 'when the cop name is not duplicated' do
before do
create_file('custom_cops.rb', <<~RUBY)
module CustomCops
class NoMethods < RuboCop::Cop::Base
MSG = 'Methods are not allowed.'
def on_send(node)
add_offense(node)
end
end
end
RUBY
end
it 'runs the cop without warnings' do
expect(cli.run(['--format', 'simple',
'--only', 'CustomCops/NoMethods',
'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
== example.rb ==
C: 1: 1: CustomCops/NoMethods: Methods are not allowed.
1 file inspected, 1 offense detected
RESULT
expect($stderr.string).not_to match(%r{CustomCops/NoMethods has the wrong namespace})
end
end
context 'when the cop name duplicates a built-in cop' do
before do
create_file('custom_cops.rb', <<~RUBY)
module CustomCops
class MethodLength < RuboCop::Cop::Base
MSG = 'Method is too long.'
def on_send(node)
add_offense(node)
end
end
end
RUBY
end
it 'runs the correct cop without warnings' do
expect(cli.run(['--format', 'simple',
'--only', 'CustomCops/MethodLength',
'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
== example.rb ==
C: 1: 1: CustomCops/MethodLength: Method is too long.
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/html_formatter/project/app/controllers/books_controller.rb | spec/fixtures/html_formatter/project/app/controllers/books_controller.rb | class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
# GET /books
# GET /books.json
def index
@books = Book.all
end
# GET /books/1
# GET /books/1.json
def show
end
# GET /books/new
def new
@book = Book.new
end
# GET /books/1/edit
def edit
end
# POST /books
# POST /books.json
def create
@book = Book.new(book_params)
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' } # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /books/1
# PATCH/PUT /books/1.json
def update
respond_to do |format|
if @book.update(book_params)
format.html { redirect_to @book, notice: 'Book was successfully updated.' } # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
format.json { render :show, status: :ok, location: @book }
else
format.html { render :edit }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# DELETE /books/1
# DELETE /books/1.json
def destroy
@book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' } # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book
@book = Book.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the allow list through. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
def book_params
params.require(:book).permit(:name)
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/html_formatter/project/app/controllers/application_controller.rb | spec/fixtures/html_formatter/project/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# “Test encoding issues by using curly quotes”
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/html_formatter/project/app/models/book.rb | spec/fixtures/html_formatter/project/app/models/book.rb | class Book < ActiveRecord::Base
def someMethod
foo = bar = baz
qux(quux.scan(/&</))
Regexp.new(/\A<p>(.*)<\/p>\Z/m).match(full_document)[1] rescue full_document
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/ruby_lsp/example.rb | spec/fixtures/ruby_lsp/example.rb | s = 'hi'
puts s
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/markdown_formatter/project/app/controllers/books_controller.rb | spec/fixtures/markdown_formatter/project/app/controllers/books_controller.rb | class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
# GET /books
# GET /books.json
def index
@books = Book.all
end
# GET /books/1
# GET /books/1.json
def show
end
# GET /books/new
def new
@book = Book.new
end
# GET /books/1/edit
def edit
end
# POST /books
# POST /books.json
def create
@book = Book.new(book_params)
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' } # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /books/1
# PATCH/PUT /books/1.json
def update
respond_to do |format|
if @book.update(book_params)
format.html { redirect_to @book, notice: 'Book was successfully updated.' } # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
format.json { render :show, status: :ok, location: @book }
else
format.html { render :edit }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
# DELETE /books/1
# DELETE /books/1.json
def destroy
@book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' } # aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book
@book = Book.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the allow list through. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
def book_params
params.require(:book).permit(:name)
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/markdown_formatter/project/app/controllers/application_controller.rb | spec/fixtures/markdown_formatter/project/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# “Test encoding issues by using curly quotes”
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/markdown_formatter/project/app/models/book.rb | spec/fixtures/markdown_formatter/project/app/models/book.rb | class Book < ActiveRecord::Base
def someMethod
foo = bar = baz
Regexp.new(/\A<p>(.*)<\/p>\Z/m).match(full_document)[1] rescue full_document
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/fixtures/markdown_formatter/project/app/models/shelf.rb | spec/fixtures/markdown_formatter/project/app/models/shelf.rb | # frozen_string_literal: true
# Book class comment
class Book < ActiveRecord::Base
def some_method
Regexp.new(%r{\A<p>(.*)</p>\Z}m).match(full_document)[1]
rescue StandardError
full_document
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/core_ext/string.rb | spec/core_ext/string.rb | # frozen_string_literal: true
class String
unless method_defined? :strip_margin
# The method strips the characters preceding a special margin character.
# Useful for HEREDOCs and other multi-line strings.
#
# @example
#
# code = <<-END.strip_margin('|')
# |def test
# | some_method
# | other_method
# |end
# END
#
# #=> "def\n some_method\n \nother_method\nend"
def strip_margin(margin_characters)
margin = Regexp.quote(margin_characters)
gsub(/^\s+#{margin}/, '')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/ruby_lsp/rubocop/addon_spec.rb | spec/ruby_lsp/rubocop/addon_spec.rb | # frozen_string_literal: true
# NOTE: These don't work in Ruby LSP.
return if RUBY_VERSION < '3.0' || RUBY_ENGINE == 'jruby' || RuboCop::Platform.windows?
require 'ruby_lsp/internal'
require 'ruby_lsp/rubocop/addon'
# NOTE: ruby-lsp enables LSP mode. Ideally the two requires should happen in isolation, but
# for now this prevents it from failing unrelated tests.
RuboCop::LSP.disable
describe 'RubyLSP::RuboCop::Addon', :isolated_environment, :lsp do
include FileHelper
include_context 'mock console output'
let(:path) { 'example.rb' }
let(:uri) { path_to_uri(path) }
let(:source) do
<<~RUBY
s = "hello"
puts s
RUBY
end
let(:request_id) { (1..).to_enum }
let(:server) { create_server(source, uri) }
after do
RubyLsp::Addon.addons.each(&:deactivate)
RubyLsp::Addon.addons.clear
end
context 'Add-on metadata' do
let(:addon) do
RubyLsp::RuboCop::Addon.new
end
it 'has a name' do
expect(addon.name).to eq 'RuboCop'
end
it 'has a version' do
expect(addon.version).to match(/\A\d+\.\d+\.\d+\z/)
end
end
describe 'textDocument/diagnostic' do
subject(:result) do
process_message('textDocument/diagnostic', textDocument: { uri: uri })
server.pop_response
end
let(:first_item) { result.response.items.first }
let(:second_item) { result.response.items[1] }
it 'has basic result information' do
expect(result).to be_an_instance_of(RubyLsp::Result)
expect(result.response.kind).to eq 'full'
expect(result.response.items.size).to eq 2
end
it 'has first diagnostic information' do
expect(first_item.range.start.to_hash).to eq({ line: 0, character: 0 })
expect(first_item.range.end.to_hash).to eq({ line: 0, character: 1 })
expect(first_item.severity).to eq RubyLsp::Constant::DiagnosticSeverity::INFORMATION
expect(first_item.code).to eq 'Style/FrozenStringLiteralComment'
expect(first_item.code_description.href).to eq 'https://docs.rubocop.org/rubocop/cops_style.html#stylefrozenstringliteralcomment'
expect(first_item.source).to eq 'RuboCop'
expect(first_item.message).to eq <<~MESSAGE.chop
Style/FrozenStringLiteralComment: Missing frozen string literal comment.
MESSAGE
end
it 'has second diagnostic information' do
second_item = result.response.items[1]
expect(second_item.range.start.to_hash).to eq({ line: 0, character: 4 })
expect(second_item.range.end.to_hash).to eq({ line: 0, character: 11 })
expect(second_item.severity).to eq RubyLsp::Constant::DiagnosticSeverity::INFORMATION
expect(second_item.code).to eq 'Style/StringLiterals'
expect(second_item.code_description.href).to eq 'https://docs.rubocop.org/rubocop/cops_style.html#stylestringliterals'
expect(second_item.source).to eq 'RuboCop'
expect(second_item.message).to eq <<~MESSAGE.chop
Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
MESSAGE
end
context 'when `.rubocop` points to a different config file' do
before do
create_file('.rubocop', '-c custom.yml')
create_file('custom.yml', <<~YML)
<%= warn "Hello from 'custom.yml'" %>
YML
end
it 'uses the config file' do
expect { result }.to output(/Hello from 'custom\.yml'/).to_stderr
end
end
end
describe 'textDocument/formatting' do
subject(:result) do
process_message(
'textDocument/formatting',
textDocument: { uri: uri },
position: { line: 0, character: 0 }
)
server.pop_response
end
it 'has basic result information' do
expect(result).to be_an_instance_of(RubyLsp::Result)
expect(result.response.size).to eq 1
end
it 'has autocorrected code' do
expect(result.response.first.new_text).to eq <<~RUBY
s = 'hello'
puts s
RUBY
end
context 'with prism as the parser' do
before do
create_file('.rubocop.yml', <<~YML)
AllCops:
TargetRubyVersion: 3.4
YML
end
context 'with a `Layout/DefEndAlignment` offense' do
let(:source) do
<<~RUBY
class Foo
def bar
end
end
RUBY
end
it 'has autocorrected code' do
expect(result).to be_an_instance_of(RubyLsp::Result)
expect(result.response.size).to eq 1
expect(result.response.first.new_text).to eq <<~RUBY
class Foo
def bar
end
end
RUBY
end
end
end
context 'when an error occurs' do
context 'when `.rubocop.yml` is invalid' do
it 'handles it gracefully' do
create_file('.rubocop.yml', 'Not valid YAML!')
server.global_state.index.index_all(uris: [])
init_response = server.pop_response
expect(init_response).to be_an_instance_of(RubyLsp::Notification)
expect(init_response.params.attributes[:message]).to match(
/RuboCop configuration error: Malformed configuration/
)
process_message(
'textDocument/formatting',
textDocument: { uri: uri },
position: { line: 0, character: 0 }
)
formatting_response = server.pop_response
expect(formatting_response).to be_an_instance_of(RubyLsp::Result)
expect(formatting_response.response).to be_nil
create_empty_file('.rubocop.yml')
expect do
process_message(
'workspace/didChangeWatchedFiles',
changes: [{
uri: path_to_uri('.rubocop.yml').to_s,
type: RubyLsp::Constant::FileChangeType::CHANGED
}]
)
end.to output.to_stderr
process_message(
'textDocument/formatting',
textDocument: { uri: uri },
position: { line: 0, character: 0 }
)
formatting_response = server.pop_response
expect(formatting_response).to be_an_instance_of(RubyLsp::Result)
expect(formatting_response.response).not_to be_nil
end
end
context 'runtime error' do
before do
allow_any_instance_of(RuboCop::Cop::Style::StringLiterals) # rubocop:disable RSpec/AnyInstance
.to receive(:on_str)
.and_raise(RuntimeError, 'oops')
end
let(:source) { '""' }
it 'handles infinite loop errors' do
expect { result }.to output.to_stderr
expect(result).to be_an_instance_of(RubyLsp::Notification)
expect(result.params.attributes[:message]).to match(<<~MSG)
Formatting error: An internal error occurred for the Style/StringLiterals cop.
MSG
end
end
context 'infinite loop error' do
before do
allow(RuboCop::Cop::Registry).to receive(:all).and_return([cop])
end
let(:cop) { RuboCop::Cop::Test::InfiniteLoopDuringAutocorrectWithChangeCop }
let(:source) do
<<~RUBY
class Test
end
RUBY
end
it 'handles infinite loop errors' do
expect { result }.to output.to_stderr
expect(result).to be_an_instance_of(RubyLsp::Notification)
expect(result.params.attributes[:message]).to match(<<~MSG)
Formatting error: An internal error occurred - Infinite loop detected in #{uri} and caused by #{cop.badge}.
MSG
end
end
end
end
describe 'workspace/didChangeWatchedFiles' do
before do
# Ensure initial indexing is complete before trying to process did change watched file
# notifications.
server.global_state.index.index_all(uris: [])
end
context 'when `.rubocop.yml` changes' do
let(:source) do
<<~RUBY
# frozen_string_literal: true
""
RUBY
end
it 'reloads the addon and uses the updated config' do
create_file('.rubocop.yml', <<~YML)
Style/StringLiterals:
EnforcedStyle: single_quotes
YML
process_message('textDocument/diagnostic', textDocument: { uri: uri })
diagnostics_result = server.pop_response
expect(diagnostics_result).to be_an_instance_of(RubyLsp::Result)
rubocop_diagnostics = diagnostics_result.response.items.select do |diag|
diag.source == 'RuboCop'
end
expect(rubocop_diagnostics.size).to eq(1)
expect(rubocop_diagnostics[0].code).to eq('Style/StringLiterals')
create_file('.rubocop.yml', <<~YML)
Style/StringLiterals:
EnforcedStyle: double_quotes
YML
expect do
process_message(
'workspace/didChangeWatchedFiles',
changes: [{
uri: path_to_uri('.rubocop.yml').to_s,
type: RubyLsp::Constant::FileChangeType::CHANGED
}]
)
end.to output.to_stderr
process_message('textDocument/diagnostic', textDocument: { uri: uri })
diagnostics_result = server.pop_response
expect(diagnostics_result).to be_an_instance_of(RubyLsp::Result)
rubocop_diagnostics = diagnostics_result.response.items.select do |diag|
diag.source == 'RuboCop'
end
expect(rubocop_diagnostics).to be_empty
end
end
%w[.rubocop.yml .rubocop_todo.yml .rubocop].each do |path|
context "when `#{path}` changes" do
it 'logs a message that the add-on got re-initialized' do
expect do
process_message(
'workspace/didChangeWatchedFiles',
changes: [{
uri: path_to_uri(path).to_s,
type: RubyLsp::Constant::FileChangeType::CHANGED
}]
)
end.to output(/Re-initialized RuboCop LSP addon/).to_stderr
end
end
end
context 'when `test.rb` file changes' do
let(:path) { 'test.rb' }
it "doesn't log a message about re-initializing the addon" do
expect do
process_message(
'workspace/didChangeWatchedFiles',
changes: [{
uri: uri.to_s,
type: RubyLsp::Constant::FileChangeType::CHANGED
}]
)
end.not_to output.to_stderr
end
end
end
private
# rubocop:disable Metrics/MethodLength
def create_server(source, uri)
server = RubyLsp::Server.new(test_mode: true)
server.global_state.formatter = 'rubocop'
server.global_state.instance_variable_set(:@linters, ['rubocop'])
if source
server.process_message(
id: request_id.next,
method: 'textDocument/didOpen',
params: {
textDocument: {
uri: uri,
text: source,
version: 1
}
}
)
end
server.global_state.index.index_single(
URI::Generic.from_path(path: uri.to_standardized_path), source
)
server.load_addons
server
end
# rubocop:enable Metrics/MethodLength
def process_message(method, **params)
server.process_message(id: request_id.next, method: method, params: params)
end
def path_to_uri(path)
URI(File.absolute_path(path))
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop.rb | lib/rubocop.rb | # frozen_string_literal: true
require 'English'
# fileutils is autoloaded by pathname,
# but must be explicitly loaded here for inclusion in `$LOADED_FEATURES`.
require 'fileutils'
before_us = $LOADED_FEATURES.dup
require 'rainbow'
require 'regexp_parser'
require 'set'
require 'stringio'
require 'unicode/display_width'
# we have to require RuboCop's version, before rubocop-ast's
require_relative 'rubocop/version'
require 'rubocop-ast'
require_relative 'rubocop/ast_aliases'
require_relative 'rubocop/ext/comment'
require_relative 'rubocop/ext/range'
require_relative 'rubocop/ext/regexp_node'
require_relative 'rubocop/ext/regexp_parser'
require_relative 'rubocop/core_ext/string'
require_relative 'rubocop/ext/processed_source'
require_relative 'rubocop/error'
require_relative 'rubocop/file_finder'
require_relative 'rubocop/file_patterns'
require_relative 'rubocop/name_similarity'
require_relative 'rubocop/path_util'
require_relative 'rubocop/platform'
require_relative 'rubocop/string_interpreter'
require_relative 'rubocop/util'
require_relative 'rubocop/warning'
# rubocop:disable Style/RequireOrder
require_relative 'rubocop/cop/util'
require_relative 'rubocop/cop/offense'
require_relative 'rubocop/cop/message_annotator'
require_relative 'rubocop/cop/ignored_node'
require_relative 'rubocop/cop/autocorrect_logic'
require_relative 'rubocop/cop/exclude_limit'
require_relative 'rubocop/cop/badge'
require_relative 'rubocop/cop/registry'
require_relative 'rubocop/cop/base'
require_relative 'rubocop/cop/cop'
require_relative 'rubocop/cop/commissioner'
require_relative 'rubocop/cop/documentation'
require_relative 'rubocop/cop/corrector'
require_relative 'rubocop/cop/force'
require_relative 'rubocop/cop/severity'
require_relative 'rubocop/cop/generator'
require_relative 'rubocop/cop/generator/configuration_injector'
require_relative 'rubocop/cop/generator/require_file_injector'
require_relative 'rubocop/magic_comment'
require_relative 'rubocop/cop/variable_force'
require_relative 'rubocop/cop/variable_force/branch'
require_relative 'rubocop/cop/variable_force/branchable'
require_relative 'rubocop/cop/variable_force/variable'
require_relative 'rubocop/cop/variable_force/assignment'
require_relative 'rubocop/cop/variable_force/reference'
require_relative 'rubocop/cop/variable_force/scope'
require_relative 'rubocop/cop/variable_force/variable_table'
require_relative 'rubocop/cop/mixin/array_min_size'
require_relative 'rubocop/cop/mixin/array_syntax'
require_relative 'rubocop/cop/mixin/alignment'
require_relative 'rubocop/cop/mixin/allowed_identifiers'
require_relative 'rubocop/cop/mixin/allowed_methods'
require_relative 'rubocop/cop/mixin/allowed_pattern'
require_relative 'rubocop/cop/mixin/allowed_receivers'
require_relative 'rubocop/cop/mixin/forbidden_identifiers'
require_relative 'rubocop/cop/mixin/forbidden_pattern'
require_relative 'rubocop/cop/mixin/auto_corrector' # rubocop:todo Naming/InclusiveLanguage
require_relative 'rubocop/cop/mixin/check_assignment'
require_relative 'rubocop/cop/mixin/check_line_breakable'
require_relative 'rubocop/cop/mixin/check_single_line_suitability'
require_relative 'rubocop/cop/mixin/configurable_max'
require_relative 'rubocop/cop/mixin/code_length' # relies on configurable_max
require_relative 'rubocop/cop/mixin/configurable_enforced_style'
require_relative 'rubocop/cop/mixin/configurable_formatting'
require_relative 'rubocop/cop/mixin/configurable_naming'
require_relative 'rubocop/cop/mixin/configurable_numbering'
require_relative 'rubocop/cop/mixin/dig_help'
require_relative 'rubocop/cop/mixin/documentation_comment'
require_relative 'rubocop/cop/mixin/duplication'
require_relative 'rubocop/cop/mixin/range_help'
require_relative 'rubocop/cop/mixin/annotation_comment' # relies on range
require_relative 'rubocop/cop/mixin/empty_lines_around_body' # relies on range
require_relative 'rubocop/cop/mixin/empty_parameter'
require_relative 'rubocop/cop/mixin/end_keyword_alignment'
require_relative 'rubocop/cop/mixin/endless_method_rewriter'
require_relative 'rubocop/cop/mixin/enforce_superclass'
require_relative 'rubocop/cop/mixin/first_element_line_break'
require_relative 'rubocop/cop/mixin/frozen_string_literal'
require_relative 'rubocop/cop/mixin/gem_declaration'
require_relative 'rubocop/cop/mixin/gemspec_help'
require_relative 'rubocop/cop/mixin/hash_alignment_styles'
require_relative 'rubocop/cop/mixin/hash_subset'
require_relative 'rubocop/cop/mixin/hash_transform_method'
require_relative 'rubocop/cop/mixin/integer_node'
require_relative 'rubocop/cop/mixin/interpolation'
require_relative 'rubocop/cop/mixin/line_length_help'
require_relative 'rubocop/cop/mixin/match_range'
require_relative 'rubocop/cop/metrics/utils/repeated_csend_discount'
require_relative 'rubocop/cop/metrics/utils/repeated_attribute_discount'
require_relative 'rubocop/cop/mixin/hash_shorthand_syntax'
require_relative 'rubocop/cop/mixin/method_complexity'
require_relative 'rubocop/cop/mixin/method_preference'
require_relative 'rubocop/cop/mixin/min_body_length'
require_relative 'rubocop/cop/mixin/min_branches_count'
require_relative 'rubocop/cop/mixin/multiline_element_indentation'
require_relative 'rubocop/cop/mixin/multiline_element_line_breaks'
require_relative 'rubocop/cop/mixin/multiline_expression_indentation'
require_relative 'rubocop/cop/mixin/multiline_literal_brace_layout'
require_relative 'rubocop/cop/mixin/negative_conditional'
require_relative 'rubocop/cop/mixin/heredoc'
require_relative 'rubocop/cop/mixin/nil_methods'
require_relative 'rubocop/cop/mixin/on_normal_if_unless'
require_relative 'rubocop/cop/mixin/ordered_gem_node'
require_relative 'rubocop/cop/mixin/parentheses'
require_relative 'rubocop/cop/mixin/percent_array'
require_relative 'rubocop/cop/mixin/percent_literal'
require_relative 'rubocop/cop/mixin/preceding_following_alignment'
require_relative 'rubocop/cop/mixin/preferred_delimiters'
require_relative 'rubocop/cop/mixin/rational_literal'
require_relative 'rubocop/cop/mixin/require_library'
require_relative 'rubocop/cop/mixin/rescue_node'
require_relative 'rubocop/cop/mixin/safe_assignment'
require_relative 'rubocop/cop/mixin/space_after_punctuation'
require_relative 'rubocop/cop/mixin/space_before_punctuation'
require_relative 'rubocop/cop/mixin/surrounding_space'
require_relative 'rubocop/cop/mixin/statement_modifier'
require_relative 'rubocop/cop/mixin/string_help'
require_relative 'rubocop/cop/mixin/string_literals_help'
require_relative 'rubocop/cop/mixin/symbol_help'
require_relative 'rubocop/cop/mixin/target_ruby_version'
require_relative 'rubocop/cop/mixin/trailing_body'
require_relative 'rubocop/cop/mixin/trailing_comma'
require_relative 'rubocop/cop/mixin/uncommunicative_name'
require_relative 'rubocop/cop/mixin/unused_argument'
require_relative 'rubocop/cop/mixin/visibility_help'
require_relative 'rubocop/cop/mixin/comments_help' # relies on visibility_help
require_relative 'rubocop/cop/mixin/def_node' # relies on visibility_help
require_relative 'rubocop/cop/utils/format_string'
require_relative 'rubocop/cop/migration/department_name'
require_relative 'rubocop/cop/correctors/alignment_corrector'
require_relative 'rubocop/cop/correctors/condition_corrector'
require_relative 'rubocop/cop/correctors/each_to_for_corrector'
require_relative 'rubocop/cop/correctors/empty_line_corrector'
require_relative 'rubocop/cop/correctors/for_to_each_corrector'
require_relative 'rubocop/cop/correctors/if_then_corrector'
require_relative 'rubocop/cop/correctors/lambda_literal_to_method_corrector'
require_relative 'rubocop/cop/correctors/line_break_corrector'
require_relative 'rubocop/cop/correctors/multiline_literal_brace_corrector'
require_relative 'rubocop/cop/correctors/ordered_gem_corrector'
require_relative 'rubocop/cop/correctors/parentheses_corrector'
require_relative 'rubocop/cop/correctors/percent_literal_corrector'
require_relative 'rubocop/cop/correctors/punctuation_corrector'
require_relative 'rubocop/cop/correctors/require_library_corrector'
require_relative 'rubocop/cop/correctors/space_corrector'
require_relative 'rubocop/cop/correctors/string_literal_corrector'
require_relative 'rubocop/cop/correctors/unused_arg_corrector'
require_relative 'rubocop/cop/bundler/duplicated_gem'
require_relative 'rubocop/cop/bundler/duplicated_group'
require_relative 'rubocop/cop/bundler/gem_comment'
require_relative 'rubocop/cop/bundler/gem_filename'
require_relative 'rubocop/cop/bundler/gem_version'
require_relative 'rubocop/cop/bundler/insecure_protocol_source'
require_relative 'rubocop/cop/bundler/ordered_gems'
require_relative 'rubocop/cop/gemspec/add_runtime_dependency'
require_relative 'rubocop/cop/gemspec/attribute_assignment'
require_relative 'rubocop/cop/gemspec/dependency_version'
require_relative 'rubocop/cop/gemspec/deprecated_attribute_assignment'
require_relative 'rubocop/cop/gemspec/development_dependencies'
require_relative 'rubocop/cop/gemspec/duplicated_assignment'
require_relative 'rubocop/cop/gemspec/ordered_dependencies'
require_relative 'rubocop/cop/gemspec/require_mfa'
require_relative 'rubocop/cop/gemspec/required_ruby_version'
require_relative 'rubocop/cop/gemspec/ruby_version_globals_usage'
require_relative 'rubocop/cop/layout/access_modifier_indentation'
require_relative 'rubocop/cop/layout/argument_alignment'
require_relative 'rubocop/cop/layout/array_alignment'
require_relative 'rubocop/cop/layout/assignment_indentation'
require_relative 'rubocop/cop/layout/begin_end_alignment'
require_relative 'rubocop/cop/layout/block_alignment'
require_relative 'rubocop/cop/layout/block_end_newline'
require_relative 'rubocop/cop/layout/case_indentation'
require_relative 'rubocop/cop/layout/class_structure'
require_relative 'rubocop/cop/layout/closing_heredoc_indentation'
require_relative 'rubocop/cop/layout/closing_parenthesis_indentation'
require_relative 'rubocop/cop/layout/comment_indentation'
require_relative 'rubocop/cop/layout/condition_position'
require_relative 'rubocop/cop/layout/def_end_alignment'
require_relative 'rubocop/cop/layout/dot_position'
require_relative 'rubocop/cop/layout/else_alignment'
require_relative 'rubocop/cop/layout/empty_comment'
require_relative 'rubocop/cop/layout/empty_line_after_guard_clause'
require_relative 'rubocop/cop/layout/empty_line_after_magic_comment'
require_relative 'rubocop/cop/layout/empty_line_after_multiline_condition'
require_relative 'rubocop/cop/layout/empty_line_between_defs'
require_relative 'rubocop/cop/layout/empty_lines_after_module_inclusion'
require_relative 'rubocop/cop/layout/empty_lines_around_access_modifier'
require_relative 'rubocop/cop/layout/empty_lines_around_arguments'
require_relative 'rubocop/cop/layout/empty_lines_around_attribute_accessor'
require_relative 'rubocop/cop/layout/empty_lines_around_begin_body'
require_relative 'rubocop/cop/layout/empty_lines_around_block_body'
require_relative 'rubocop/cop/layout/empty_lines_around_class_body'
require_relative 'rubocop/cop/layout/empty_lines_around_exception_handling_keywords'
require_relative 'rubocop/cop/layout/empty_lines_around_method_body'
require_relative 'rubocop/cop/layout/empty_lines_around_module_body'
require_relative 'rubocop/cop/layout/empty_lines'
require_relative 'rubocop/cop/layout/end_alignment'
require_relative 'rubocop/cop/layout/end_of_line'
require_relative 'rubocop/cop/layout/extra_spacing'
require_relative 'rubocop/cop/layout/first_argument_indentation'
require_relative 'rubocop/cop/layout/first_array_element_indentation'
require_relative 'rubocop/cop/layout/first_array_element_line_break'
require_relative 'rubocop/cop/layout/first_hash_element_indentation'
require_relative 'rubocop/cop/layout/first_hash_element_line_break'
require_relative 'rubocop/cop/layout/first_method_argument_line_break'
require_relative 'rubocop/cop/layout/first_method_parameter_line_break'
require_relative 'rubocop/cop/layout/first_parameter_indentation'
require_relative 'rubocop/cop/layout/hash_alignment'
require_relative 'rubocop/cop/layout/heredoc_argument_closing_parenthesis'
require_relative 'rubocop/cop/layout/heredoc_indentation'
require_relative 'rubocop/cop/layout/indentation_consistency'
require_relative 'rubocop/cop/layout/indentation_style'
require_relative 'rubocop/cop/layout/indentation_width'
require_relative 'rubocop/cop/layout/initial_indentation'
require_relative 'rubocop/cop/layout/leading_comment_space'
require_relative 'rubocop/cop/layout/leading_empty_lines'
require_relative 'rubocop/cop/layout/line_continuation_leading_space'
require_relative 'rubocop/cop/layout/line_continuation_spacing'
require_relative 'rubocop/cop/layout/line_end_string_concatenation_indentation'
require_relative 'rubocop/cop/layout/line_length'
require_relative 'rubocop/cop/layout/multiline_array_brace_layout'
require_relative 'rubocop/cop/layout/multiline_array_line_breaks'
require_relative 'rubocop/cop/layout/multiline_assignment_layout'
require_relative 'rubocop/cop/layout/multiline_block_layout'
require_relative 'rubocop/cop/layout/multiline_hash_brace_layout'
require_relative 'rubocop/cop/layout/multiline_hash_key_line_breaks'
require_relative 'rubocop/cop/layout/multiline_method_argument_line_breaks'
require_relative 'rubocop/cop/layout/multiline_method_call_brace_layout'
require_relative 'rubocop/cop/layout/multiline_method_call_indentation'
require_relative 'rubocop/cop/layout/multiline_method_definition_brace_layout'
require_relative 'rubocop/cop/layout/multiline_method_parameter_line_breaks'
require_relative 'rubocop/cop/layout/multiline_operation_indentation'
require_relative 'rubocop/cop/layout/parameter_alignment'
require_relative 'rubocop/cop/layout/redundant_line_break'
require_relative 'rubocop/cop/layout/rescue_ensure_alignment'
require_relative 'rubocop/cop/layout/single_line_block_chain'
require_relative 'rubocop/cop/layout/space_after_colon'
require_relative 'rubocop/cop/layout/space_after_comma'
require_relative 'rubocop/cop/layout/space_after_method_name'
require_relative 'rubocop/cop/layout/space_after_not'
require_relative 'rubocop/cop/layout/space_after_semicolon'
require_relative 'rubocop/cop/layout/space_around_block_parameters'
require_relative 'rubocop/cop/layout/space_around_equals_in_parameter_default'
require_relative 'rubocop/cop/layout/space_around_keyword'
require_relative 'rubocop/cop/layout/space_around_method_call_operator'
require_relative 'rubocop/cop/layout/space_around_operators'
require_relative 'rubocop/cop/layout/space_before_block_braces'
require_relative 'rubocop/cop/layout/space_before_brackets'
require_relative 'rubocop/cop/layout/space_before_comma'
require_relative 'rubocop/cop/layout/space_before_comment'
require_relative 'rubocop/cop/layout/space_before_first_arg'
require_relative 'rubocop/cop/layout/space_before_semicolon'
require_relative 'rubocop/cop/layout/space_in_lambda_literal'
require_relative 'rubocop/cop/layout/space_inside_array_percent_literal'
require_relative 'rubocop/cop/layout/space_inside_array_literal_brackets'
require_relative 'rubocop/cop/layout/space_inside_block_braces'
require_relative 'rubocop/cop/layout/space_inside_hash_literal_braces'
require_relative 'rubocop/cop/layout/space_inside_parens'
require_relative 'rubocop/cop/layout/space_inside_percent_literal_delimiters'
require_relative 'rubocop/cop/layout/space_inside_range_literal'
require_relative 'rubocop/cop/layout/space_inside_reference_brackets'
require_relative 'rubocop/cop/layout/space_inside_string_interpolation'
require_relative 'rubocop/cop/layout/trailing_empty_lines'
require_relative 'rubocop/cop/layout/trailing_whitespace'
require_relative 'rubocop/cop/lint/utils/nil_receiver_checker'
require_relative 'rubocop/cop/lint/ambiguous_assignment'
require_relative 'rubocop/cop/lint/ambiguous_block_association'
require_relative 'rubocop/cop/lint/ambiguous_operator'
require_relative 'rubocop/cop/lint/ambiguous_operator_precedence'
require_relative 'rubocop/cop/lint/ambiguous_range'
require_relative 'rubocop/cop/lint/ambiguous_regexp_literal'
require_relative 'rubocop/cop/lint/array_literal_in_regexp'
require_relative 'rubocop/cop/lint/assignment_in_condition'
require_relative 'rubocop/cop/lint/big_decimal_new'
require_relative 'rubocop/cop/lint/binary_operator_with_identical_operands'
require_relative 'rubocop/cop/lint/boolean_symbol'
require_relative 'rubocop/cop/lint/circular_argument_reference'
require_relative 'rubocop/cop/lint/constant_definition_in_block'
require_relative 'rubocop/cop/lint/constant_overwritten_in_rescue'
require_relative 'rubocop/cop/lint/constant_reassignment'
require_relative 'rubocop/cop/lint/constant_resolution'
require_relative 'rubocop/cop/lint/cop_directive_syntax'
require_relative 'rubocop/cop/lint/debugger'
require_relative 'rubocop/cop/lint/deprecated_class_methods'
require_relative 'rubocop/cop/lint/deprecated_constants'
require_relative 'rubocop/cop/lint/deprecated_open_ssl_constant'
require_relative 'rubocop/cop/lint/disjunctive_assignment_in_constructor'
require_relative 'rubocop/cop/lint/duplicate_branch'
require_relative 'rubocop/cop/lint/duplicate_case_condition'
require_relative 'rubocop/cop/lint/duplicate_elsif_condition'
require_relative 'rubocop/cop/lint/duplicate_hash_key'
require_relative 'rubocop/cop/lint/duplicate_magic_comment'
require_relative 'rubocop/cop/lint/duplicate_match_pattern'
require_relative 'rubocop/cop/lint/duplicate_methods'
require_relative 'rubocop/cop/lint/duplicate_regexp_character_class_element'
require_relative 'rubocop/cop/lint/duplicate_require'
require_relative 'rubocop/cop/lint/duplicate_rescue_exception'
require_relative 'rubocop/cop/lint/duplicate_set_element'
require_relative 'rubocop/cop/lint/each_with_object_argument'
require_relative 'rubocop/cop/lint/else_layout'
require_relative 'rubocop/cop/lint/empty_block'
require_relative 'rubocop/cop/lint/empty_class'
require_relative 'rubocop/cop/lint/empty_conditional_body'
require_relative 'rubocop/cop/lint/empty_ensure'
require_relative 'rubocop/cop/lint/empty_expression'
require_relative 'rubocop/cop/lint/empty_file'
require_relative 'rubocop/cop/lint/empty_in_pattern'
require_relative 'rubocop/cop/lint/empty_interpolation'
require_relative 'rubocop/cop/lint/empty_when'
require_relative 'rubocop/cop/lint/ensure_return'
require_relative 'rubocop/cop/lint/shared_mutable_default'
require_relative 'rubocop/cop/lint/erb_new_arguments'
require_relative 'rubocop/cop/lint/flip_flop'
require_relative 'rubocop/cop/lint/float_comparison'
require_relative 'rubocop/cop/lint/float_out_of_range'
require_relative 'rubocop/cop/lint/format_parameter_mismatch'
require_relative 'rubocop/cop/lint/hash_compare_by_identity'
require_relative 'rubocop/cop/lint/hash_new_with_keyword_arguments_as_default'
require_relative 'rubocop/cop/lint/heredoc_method_call_position'
require_relative 'rubocop/cop/lint/identity_comparison'
require_relative 'rubocop/cop/lint/implicit_string_concatenation'
require_relative 'rubocop/cop/lint/incompatible_io_select_with_fiber_scheduler'
require_relative 'rubocop/cop/lint/ineffective_access_modifier'
require_relative 'rubocop/cop/lint/inherit_exception'
require_relative 'rubocop/cop/lint/interpolation_check'
require_relative 'rubocop/cop/lint/it_without_arguments_in_block'
require_relative 'rubocop/cop/lint/lambda_without_literal_block'
require_relative 'rubocop/cop/lint/literal_as_condition'
require_relative 'rubocop/cop/lint/literal_assignment_in_condition'
require_relative 'rubocop/cop/lint/literal_in_interpolation'
require_relative 'rubocop/cop/lint/loop'
require_relative 'rubocop/cop/lint/missing_cop_enable_directive'
require_relative 'rubocop/cop/lint/missing_super'
require_relative 'rubocop/cop/lint/mixed_case_range'
require_relative 'rubocop/cop/lint/mixed_regexp_capture_types'
require_relative 'rubocop/cop/lint/multiple_comparison'
require_relative 'rubocop/cop/lint/nested_method_definition'
require_relative 'rubocop/cop/lint/nested_percent_literal'
require_relative 'rubocop/cop/lint/next_without_accumulator'
require_relative 'rubocop/cop/lint/no_return_in_begin_end_blocks'
require_relative 'rubocop/cop/lint/non_atomic_file_operation'
require_relative 'rubocop/cop/lint/non_deterministic_require_order'
require_relative 'rubocop/cop/lint/non_local_exit_from_iterator'
require_relative 'rubocop/cop/lint/number_conversion'
require_relative 'rubocop/cop/lint/numbered_parameter_assignment'
require_relative 'rubocop/cop/lint/numeric_operation_with_constant_result'
require_relative 'rubocop/cop/lint/or_assignment_to_constant'
require_relative 'rubocop/cop/lint/ordered_magic_comments'
require_relative 'rubocop/cop/lint/out_of_range_regexp_ref'
require_relative 'rubocop/cop/lint/parentheses_as_grouped_expression'
require_relative 'rubocop/cop/lint/percent_string_array'
require_relative 'rubocop/cop/lint/percent_symbol_array'
require_relative 'rubocop/cop/lint/raise_exception'
require_relative 'rubocop/cop/lint/rand_one'
require_relative 'rubocop/cop/lint/redundant_cop_disable_directive'
require_relative 'rubocop/cop/lint/redundant_cop_enable_directive'
require_relative 'rubocop/cop/lint/redundant_dir_glob_sort'
require_relative 'rubocop/cop/lint/redundant_regexp_quantifiers'
require_relative 'rubocop/cop/lint/redundant_require_statement'
require_relative 'rubocop/cop/lint/redundant_safe_navigation'
require_relative 'rubocop/cop/lint/redundant_splat_expansion'
require_relative 'rubocop/cop/lint/redundant_string_coercion'
require_relative 'rubocop/cop/lint/redundant_type_conversion'
require_relative 'rubocop/cop/lint/redundant_with_index'
require_relative 'rubocop/cop/lint/redundant_with_object'
require_relative 'rubocop/cop/lint/refinement_import_methods'
require_relative 'rubocop/cop/lint/regexp_as_condition'
require_relative 'rubocop/cop/lint/require_parentheses'
require_relative 'rubocop/cop/lint/require_range_parentheses'
require_relative 'rubocop/cop/lint/require_relative_self_path'
require_relative 'rubocop/cop/lint/rescue_exception'
require_relative 'rubocop/cop/lint/rescue_type'
require_relative 'rubocop/cop/lint/return_in_void_context'
require_relative 'rubocop/cop/lint/safe_navigation_consistency'
require_relative 'rubocop/cop/lint/safe_navigation_chain'
require_relative 'rubocop/cop/lint/safe_navigation_with_empty'
require_relative 'rubocop/cop/lint/script_permission'
require_relative 'rubocop/cop/lint/self_assignment'
require_relative 'rubocop/cop/lint/send_with_mixin_argument'
require_relative 'rubocop/cop/lint/shadowed_argument'
require_relative 'rubocop/cop/lint/shadowed_exception'
require_relative 'rubocop/cop/lint/shadowing_outer_local_variable'
require_relative 'rubocop/cop/lint/struct_new_override'
require_relative 'rubocop/cop/lint/suppressed_exception'
require_relative 'rubocop/cop/lint/suppressed_exception_in_number_conversion'
require_relative 'rubocop/cop/lint/symbol_conversion'
require_relative 'rubocop/cop/lint/syntax'
require_relative 'rubocop/cop/lint/to_enum_arguments'
require_relative 'rubocop/cop/lint/to_json'
require_relative 'rubocop/cop/lint/top_level_return_with_argument'
require_relative 'rubocop/cop/lint/trailing_comma_in_attribute_declaration'
require_relative 'rubocop/cop/lint/triple_quotes'
require_relative 'rubocop/cop/lint/underscore_prefixed_variable_name'
require_relative 'rubocop/cop/lint/unescaped_bracket_in_regexp'
require_relative 'rubocop/cop/lint/unexpected_block_arity'
require_relative 'rubocop/cop/lint/unified_integer'
require_relative 'rubocop/cop/lint/unmodified_reduce_accumulator'
require_relative 'rubocop/cop/lint/unreachable_code'
require_relative 'rubocop/cop/lint/unreachable_loop'
require_relative 'rubocop/cop/lint/unused_block_argument'
require_relative 'rubocop/cop/lint/unused_method_argument'
require_relative 'rubocop/cop/lint/uri_escape_unescape'
require_relative 'rubocop/cop/lint/uri_regexp'
require_relative 'rubocop/cop/lint/useless_access_modifier'
require_relative 'rubocop/cop/lint/useless_assignment'
require_relative 'rubocop/cop/lint/useless_constant_scoping'
require_relative 'rubocop/cop/lint/useless_default_value_argument'
require_relative 'rubocop/cop/lint/useless_defined'
require_relative 'rubocop/cop/lint/useless_else_without_rescue'
require_relative 'rubocop/cop/lint/useless_method_definition'
require_relative 'rubocop/cop/lint/useless_numeric_operation'
require_relative 'rubocop/cop/lint/useless_or'
require_relative 'rubocop/cop/lint/useless_rescue'
require_relative 'rubocop/cop/lint/useless_ruby2_keywords'
require_relative 'rubocop/cop/lint/useless_setter_call'
require_relative 'rubocop/cop/lint/useless_times'
require_relative 'rubocop/cop/lint/void'
require_relative 'rubocop/cop/metrics/utils/iterating_block'
require_relative 'rubocop/cop/metrics/cyclomatic_complexity'
# relies on cyclomatic_complexity
require_relative 'rubocop/cop/metrics/utils/abc_size_calculator'
require_relative 'rubocop/cop/metrics/utils/code_length_calculator'
require_relative 'rubocop/cop/metrics/abc_size'
require_relative 'rubocop/cop/metrics/block_length'
require_relative 'rubocop/cop/metrics/block_nesting'
require_relative 'rubocop/cop/metrics/class_length'
require_relative 'rubocop/cop/metrics/collection_literal_length'
require_relative 'rubocop/cop/metrics/method_length'
require_relative 'rubocop/cop/metrics/module_length'
require_relative 'rubocop/cop/metrics/parameter_lists'
require_relative 'rubocop/cop/metrics/perceived_complexity'
require_relative 'rubocop/cop/naming/accessor_method_name'
require_relative 'rubocop/cop/naming/ascii_identifiers'
require_relative 'rubocop/cop/naming/block_forwarding'
require_relative 'rubocop/cop/naming/block_parameter_name'
require_relative 'rubocop/cop/naming/class_and_module_camel_case'
require_relative 'rubocop/cop/naming/constant_name'
require_relative 'rubocop/cop/naming/file_name'
require_relative 'rubocop/cop/naming/heredoc_delimiter_case'
require_relative 'rubocop/cop/naming/heredoc_delimiter_naming'
require_relative 'rubocop/cop/naming/inclusive_language'
require_relative 'rubocop/cop/naming/memoized_instance_variable_name'
require_relative 'rubocop/cop/naming/method_name'
require_relative 'rubocop/cop/naming/method_parameter_name'
require_relative 'rubocop/cop/naming/binary_operator_parameter_name'
require_relative 'rubocop/cop/naming/predicate_method'
require_relative 'rubocop/cop/naming/predicate_prefix'
require_relative 'rubocop/cop/naming/rescued_exceptions_variable_name'
require_relative 'rubocop/cop/naming/variable_name'
require_relative 'rubocop/cop/naming/variable_number'
require_relative 'rubocop/cop/style/access_modifier_declarations'
require_relative 'rubocop/cop/style/accessor_grouping'
require_relative 'rubocop/cop/style/alias'
require_relative 'rubocop/cop/style/ambiguous_endless_method_definition'
require_relative 'rubocop/cop/style/and_or'
require_relative 'rubocop/cop/style/arguments_forwarding'
require_relative 'rubocop/cop/style/array_coercion'
require_relative 'rubocop/cop/style/array_first_last'
require_relative 'rubocop/cop/style/array_intersect'
require_relative 'rubocop/cop/style/array_intersect_with_single_element'
require_relative 'rubocop/cop/style/array_join'
require_relative 'rubocop/cop/style/ascii_comments'
require_relative 'rubocop/cop/style/attr'
require_relative 'rubocop/cop/style/auto_resource_cleanup'
require_relative 'rubocop/cop/style/bare_percent_literals'
require_relative 'rubocop/cop/style/begin_block'
require_relative 'rubocop/cop/style/bisected_attr_accessor'
require_relative 'rubocop/cop/style/bitwise_predicate'
require_relative 'rubocop/cop/style/block_comments'
require_relative 'rubocop/cop/style/block_delimiters'
require_relative 'rubocop/cop/style/case_equality'
require_relative 'rubocop/cop/style/case_like_if'
require_relative 'rubocop/cop/style/character_literal'
require_relative 'rubocop/cop/style/class_and_module_children'
require_relative 'rubocop/cop/style/class_check'
require_relative 'rubocop/cop/style/class_equality_comparison'
require_relative 'rubocop/cop/style/class_methods'
require_relative 'rubocop/cop/style/class_methods_definitions'
require_relative 'rubocop/cop/style/class_vars'
require_relative 'rubocop/cop/style/collection_compact'
require_relative 'rubocop/cop/style/collection_methods'
require_relative 'rubocop/cop/style/collection_querying'
require_relative 'rubocop/cop/style/colon_method_call'
require_relative 'rubocop/cop/style/colon_method_definition'
require_relative 'rubocop/cop/style/combinable_defined'
require_relative 'rubocop/cop/style/combinable_loops'
require_relative 'rubocop/cop/style/command_literal'
require_relative 'rubocop/cop/style/comment_annotation'
require_relative 'rubocop/cop/style/commented_keyword'
require_relative 'rubocop/cop/style/comparable_between'
require_relative 'rubocop/cop/style/comparable_clamp'
require_relative 'rubocop/cop/style/concat_array_literals'
require_relative 'rubocop/cop/style/conditional_assignment'
require_relative 'rubocop/cop/style/constant_visibility'
require_relative 'rubocop/cop/style/copyright'
require_relative 'rubocop/cop/style/data_inheritance'
require_relative 'rubocop/cop/style/date_time'
require_relative 'rubocop/cop/style/def_with_parentheses'
require_relative 'rubocop/cop/style/dig_chain'
require_relative 'rubocop/cop/style/dir'
require_relative 'rubocop/cop/style/dir_empty'
require_relative 'rubocop/cop/style/disable_cops_within_source_code_directive'
require_relative 'rubocop/cop/style/documentation_method'
require_relative 'rubocop/cop/style/documentation'
require_relative 'rubocop/cop/style/document_dynamic_eval_definition'
require_relative 'rubocop/cop/style/double_cop_disable_directive'
require_relative 'rubocop/cop/style/double_negation'
require_relative 'rubocop/cop/style/each_for_simple_loop'
require_relative 'rubocop/cop/style/each_with_object'
require_relative 'rubocop/cop/style/empty_block_parameter'
require_relative 'rubocop/cop/style/empty_case_condition'
require_relative 'rubocop/cop/style/empty_else'
require_relative 'rubocop/cop/style/empty_heredoc'
require_relative 'rubocop/cop/style/empty_lambda_parameter'
require_relative 'rubocop/cop/style/empty_literal'
require_relative 'rubocop/cop/style/empty_method'
require_relative 'rubocop/cop/style/empty_string_inside_interpolation'
require_relative 'rubocop/cop/style/endless_method'
require_relative 'rubocop/cop/style/encoding'
require_relative 'rubocop/cop/style/end_block'
require_relative 'rubocop/cop/style/env_home'
require_relative 'rubocop/cop/style/eval_with_location'
require_relative 'rubocop/cop/style/even_odd'
require_relative 'rubocop/cop/style/exact_regexp_match'
require_relative 'rubocop/cop/style/expand_path_arguments'
require_relative 'rubocop/cop/style/explicit_block_argument'
require_relative 'rubocop/cop/style/exponential_notation'
require_relative 'rubocop/cop/style/fetch_env_var'
require_relative 'rubocop/cop/style/file_empty'
require_relative 'rubocop/cop/style/file_null'
require_relative 'rubocop/cop/style/file_read'
require_relative 'rubocop/cop/style/file_touch'
require_relative 'rubocop/cop/style/file_write'
require_relative 'rubocop/cop/style/float_division'
require_relative 'rubocop/cop/style/for'
require_relative 'rubocop/cop/style/format_string'
require_relative 'rubocop/cop/style/format_string_token'
require_relative 'rubocop/cop/style/frozen_string_literal_comment'
require_relative 'rubocop/cop/style/global_std_stream'
require_relative 'rubocop/cop/style/global_vars'
require_relative 'rubocop/cop/style/guard_clause'
require_relative 'rubocop/cop/style/hash_as_last_array_item'
require_relative 'rubocop/cop/style/hash_conversion'
require_relative 'rubocop/cop/style/hash_each_methods'
require_relative 'rubocop/cop/style/hash_except'
require_relative 'rubocop/cop/style/hash_fetch_chain'
require_relative 'rubocop/cop/style/hash_like_case'
require_relative 'rubocop/cop/style/hash_slice'
require_relative 'rubocop/cop/style/hash_syntax'
require_relative 'rubocop/cop/style/hash_transform_keys'
require_relative 'rubocop/cop/style/hash_transform_values'
require_relative 'rubocop/cop/style/identical_conditional_branches'
require_relative 'rubocop/cop/style/if_inside_else'
require_relative 'rubocop/cop/style/if_unless_modifier'
require_relative 'rubocop/cop/style/if_unless_modifier_of_if_unless'
require_relative 'rubocop/cop/style/if_with_boolean_literal_branches'
require_relative 'rubocop/cop/style/if_with_semicolon'
require_relative 'rubocop/cop/style/implicit_runtime_error'
require_relative 'rubocop/cop/style/in_pattern_then'
require_relative 'rubocop/cop/style/infinite_loop'
require_relative 'rubocop/cop/style/inverse_methods'
require_relative 'rubocop/cop/style/inline_comment'
require_relative 'rubocop/cop/style/invertible_unless_condition'
require_relative 'rubocop/cop/style/ip_addresses'
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | true |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/feature_loader.rb | lib/rubocop/feature_loader.rb | # frozen_string_literal: true
module RuboCop
# This class handles loading files (a.k.a. features in Ruby) specified
# by `--require` command line option and `require` directive in the config.
#
# Normally, the given string is directly passed to `require`. If a string
# beginning with `.` is given, it is assumed to be relative to the given
# directory.
#
# If a string containing `-` is given, it will be used as is, but if we
# cannot find the file to load, we will replace `-` with `/` and try it
# again as when Bundler loads gems.
#
# @api private
class FeatureLoader
class << self
# @param [String] config_directory_path
# @param [String] feature
def load(config_directory_path:, feature:)
new(config_directory_path: config_directory_path, feature: feature).load
end
end
# @param [String] config_directory_path
# @param [String] feature
def initialize(config_directory_path:, feature:)
@config_directory_path = config_directory_path
@feature = feature
end
def load
# Don't use `::Kernel.require(target)` to prevent the following error:
# https://github.com/rubocop/rubocop/issues/10893
require(target)
rescue ::LoadError => e
raise if e.path != target
begin
# Don't use `::Kernel.require(target)` to prevent the following error:
# https://github.com/rubocop/rubocop/issues/10893
require(namespaced_target)
rescue ::LoadError => error_for_namespaced_target
# NOTE: This wrap is necessary due to JRuby 9.3.4.0 incompatibility:
# https://github.com/jruby/jruby/issues/7316
raise LoadError, e if error_for_namespaced_target.path == namespaced_target
raise error_for_namespaced_target
end
end
private
# @return [String]
def namespaced_feature
@feature.tr('-', '/')
end
# @return [String]
def namespaced_target
if relative?
relative(namespaced_feature)
else
namespaced_feature
end
end
# @param [String]
# @return [String]
def relative(feature)
::File.join(@config_directory_path, feature)
end
# @return [Boolean]
def relative?
@feature.start_with?('.')
end
# @param [LoadError] error
# @return [Boolean]
def seems_cannot_load_such_file_error?(error)
error.path == target
end
# @return [String]
def target
if relative?
relative(@feature)
else
@feature
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/platform.rb | lib/rubocop/platform.rb | # frozen_string_literal: true
module RuboCop
# This module provides information on the platform that RuboCop is being run
# on.
module Platform
def self.windows?
/cygwin|mswin|mingw|bccwin|wince|emx/.match?(RbConfig::CONFIG['host_os'])
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/arguments_env.rb | lib/rubocop/arguments_env.rb | # frozen_string_literal: true
module RuboCop
# This is a class that reads optional command line arguments to rubocop from environment variable.
# @api private
class ArgumentsEnv
def self.read_as_arguments
if (arguments = ENV.fetch('RUBOCOP_OPTS', '')).empty?
[]
else
require 'shellwords'
Shellwords.split(arguments)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/remote_config.rb | lib/rubocop/remote_config.rb | # frozen_string_literal: true
require 'net/http'
require 'time'
module RuboCop
# Common methods and behaviors for dealing with remote config files.
# @api private
class RemoteConfig
attr_reader :uri
CACHE_LIFETIME = 24 * 60 * 60
def initialize(url, cache_root)
begin
@uri = URI.parse(url)
rescue URI::InvalidURIError
raise ConfigNotFoundError, "Failed to resolve configuration: '#{url}' is not a valid URI"
end
@cache_root = cache_root
end
def file
return cache_path unless cache_path_expired?
request do |response|
next if response.is_a?(Net::HTTPNotModified)
next if response.is_a?(SocketError)
FileUtils.mkdir_p(File.dirname(cache_path))
File.write(cache_path, response.body)
end
cache_path
end
def inherit_from_remote(file)
new_uri = @uri.dup
new_uri.path.gsub!(%r{/[^/]*$}, "/#{file.delete_prefix('./')}")
RemoteConfig.new(new_uri.to_s, @cache_root)
end
private
def request(uri = @uri, limit = 10, &block)
raise ArgumentError, 'HTTP redirect too deep' if limit.zero?
http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = uri.instance_of?(URI::HTTPS)
generate_request(uri) do |request|
handle_response(http.request(request), limit, &block)
rescue SocketError => e
handle_response(e, limit, &block)
end
end
def generate_request(uri)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth(uri.user, uri.password) if uri.user
request['If-Modified-Since'] = File.stat(cache_path).mtime.rfc2822 if cache_path_exists?
yield request
end
def handle_response(response, limit, &block)
case response
when Net::HTTPSuccess, Net::HTTPNotModified, SocketError
yield response
when Net::HTTPRedirection
request(URI.parse(response['location']), limit - 1, &block)
else
begin
response.error!
rescue StandardError => e
message = "#{e.message} while downloading remote config file #{cloned_url}"
raise e, message
end
end
end
def cache_path
@cache_path ||= File.expand_path(".rubocop-remote-#{cache_name_from_uri}", @cache_root)
end
def cache_path_exists?
@cache_path_exists ||= File.exist?(cache_path)
end
def cache_path_expired?
return true unless cache_path_exists?
@cache_path_expired ||= begin
file_age = (Time.now - File.stat(cache_path).mtime).to_f
(file_age / CACHE_LIFETIME) > 1
end
end
def cache_name_from_uri
"#{Digest::MD5.hexdigest(@uri.to_s)}.yml"
end
def cloned_url
uri = @uri.clone
uri.user = nil if uri.user
uri.password = nil if uri.password
uri
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/version.rb | lib/rubocop/version.rb | # frozen_string_literal: true
module RuboCop
# This module holds the RuboCop version information.
module Version
STRING = '1.82.1'
MSG = '%<version>s (using %<parser_version>s, ' \
'rubocop-ast %<rubocop_ast_version>s, ' \
'analyzing as Ruby %<target_ruby_version>s, ' \
'running on %<ruby_engine>s %<ruby_version>s)%<server_mode>s [%<ruby_platform>s]'
MINIMUM_PARSABLE_PRISM_VERSION = 3.3
CANONICAL_FEATURE_NAMES = {
'Rspec' => 'RSpec', 'Graphql' => 'GraphQL', 'Md' => 'Markdown', 'Factory_bot' => 'FactoryBot',
'Thread_safety' => 'ThreadSafety', 'Rspec_rails' => 'RSpecRails'
}.freeze
EXTENSION_PATH_NAMES = {
'rubocop-md' => 'markdown', 'rubocop-factory_bot' => 'factory_bot'
}.freeze
# NOTE: Marked as private but used by gems like standard.
# @api private
# rubocop:disable Metrics/MethodLength
def self.version(debug: false, env: nil)
if debug
target_ruby_version = target_ruby_version(env)
verbose_version = format(MSG, version: STRING,
parser_version: parser_version(target_ruby_version),
rubocop_ast_version: RuboCop::AST::Version::STRING,
target_ruby_version: target_ruby_version,
ruby_engine: RUBY_ENGINE, ruby_version: RUBY_VERSION,
server_mode: server_mode,
ruby_platform: RUBY_PLATFORM)
return verbose_version unless env
extension_versions = extension_versions(env)
return verbose_version if extension_versions.empty?
<<~VERSIONS
#{verbose_version}
#{extension_versions.join("\n")}
VERSIONS
else
STRING
end
end
# rubocop:enable Metrics/MethodLength
# @api private
def self.verbose(env: nil)
version(debug: true, env: env)
end
# @api private
def self.parser_version(target_ruby_version)
config_path = ConfigFinder.find_config_path(Dir.pwd)
yaml = Util.silence_warnings do
ConfigLoader.load_yaml_configuration(config_path)
end
parser_engine = yaml.dig('AllCops', 'ParserEngine')
parser_engine_text = ", #{parser_engine}" if parser_engine
if target_ruby_version >= MINIMUM_PARSABLE_PRISM_VERSION
"Parser #{Parser::VERSION}, Prism #{Prism::VERSION}#{parser_engine_text}"
else
"Parser #{Parser::VERSION}"
end
end
# @api private
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
def self.extension_versions(env)
plugins = config_for_pwd(env).loaded_plugins
plugin_versions = plugins.filter_map do |plugin|
next if Plugin::BUILTIN_INTERNAL_PLUGINS.key?(plugin.about.name)
next unless (plugin_name = plugin.about.name)
" - #{plugin_name} #{plugin.about.version}"
end
# TODO: It needs to be maintained for a while to ensure compatibility with extensions that
# don't support plugins. It should be removed in future once the old style becomes obsolete.
features = config_for_pwd(env).loaded_features.sort
features -= plugins.map { |plugin| plugin.about.name }
feature_versions = features.filter_map do |loaded_feature|
next unless (match = loaded_feature.match(/rubocop-(?<feature>.*)/))
# Get the expected name of the folder containing the extension code.
# Usually it would be the same as the extension name. but sometimes authors
# can choose slightly different name for their gems, e.g. rubocop-md instead of
# rubocop-markdown.
feature = EXTENSION_PATH_NAMES.fetch(loaded_feature, match[:feature])
begin
require "rubocop/#{feature}/version"
rescue LoadError
# Not worth mentioning libs that are not installed
end
next unless (feature_version = feature_version(feature))
" - #{loaded_feature} #{feature_version}"
end
plugin_versions + feature_versions
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
# @api private
def self.target_ruby_version(env)
if env
config_for_pwd(env).target_ruby_version
else
TargetRuby.new(Config.new).version
end
end
# @api private
def self.config_for_pwd(env)
Util.silence_warnings do
# Suppress any config issues when loading the config (ie. deprecations,
# pending cops, etc.).
env.config_store.unvalidated.for_pwd
end
end
# Returns feature version in one of two ways:
#
# * Find by RuboCop core version style (e.g. rubocop-performance, rubocop-rspec)
# * Find by `bundle gem` version style (e.g. rubocop-rake)
#
# @api private
def self.feature_version(feature)
capitalized_feature = feature.capitalize
extension_name = CANONICAL_FEATURE_NAMES.fetch(capitalized_feature, capitalized_feature)
# Find by RuboCop core version style (e.g. rubocop-performance, rubocop-rspec)
RuboCop.const_get(extension_name)::Version::STRING
rescue NameError
begin
# Find by `bundle gem` version style (e.g. rubocop-rake, rubocop-packaging)
RuboCop.const_get(extension_name)::VERSION
rescue NameError
# noop
end
end
# @api private
def self.document_version
STRING.match('\d+\.\d+').to_s
end
# @api private
def self.server_mode
RuboCop.const_defined?(:Server) && Server.running? ? ' +server' : ''
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_loader_resolver.rb | lib/rubocop/config_loader_resolver.rb | # frozen_string_literal: true
require 'pathname'
require 'yaml'
require_relative 'plugin'
module RuboCop
# A help class for ConfigLoader that handles configuration resolution.
# @api private
class ConfigLoaderResolver # rubocop:disable Metrics/ClassLength
def resolve_plugins(rubocop_config, plugins)
plugins = Array(plugins) - ConfigLoader.loaded_plugins.map { |plugin| plugin.about.name }
return if plugins.empty?
Plugin.integrate_plugins(rubocop_config, plugins)
end
def resolve_requires(path, hash)
config_dir = File.dirname(path)
hash.delete('require').tap do |loaded_features|
Array(loaded_features).each do |feature|
if Plugin.plugin_capable?(feature)
# NOTE: Compatibility for before plugins style.
warn Rainbow(<<~MESSAGE).yellow
#{feature} extension supports plugin, specify `plugins: #{feature}` instead of `require: #{feature}` in #{path}.
For more information, see https://docs.rubocop.org/rubocop/plugin_migration_guide.html.
MESSAGE
rubocop_config = Config.create(hash, path, check: false)
resolve_plugins(rubocop_config, feature)
else
FeatureLoader.load(config_directory_path: config_dir, feature: feature)
end
end
end
end
def resolve_inheritance(path, hash, file, debug) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
inherited_files = Array(hash['inherit_from'])
base_configs(path, inherited_files, file)
.each_with_index.reverse_each do |base_config, index|
override_department_setting_for_cops(base_config, hash)
override_enabled_for_disabled_departments(base_config, hash)
base_config.each do |k, v|
next unless v.is_a?(Hash)
if hash.key?(k)
v = merge(v, hash[k],
cop_name: k, file: file, debug: debug,
inherited_file: inherited_files[index],
inherit_mode: determine_inherit_mode(hash, k))
end
hash[k] = v
fix_include_paths(base_config.loaded_path, hash, path, k, v) if v.key?('Include')
end
end
end
# When one .rubocop.yml file inherits from another .rubocop.yml file, the Include paths in the
# base configuration are relative to the directory where the base configuration file is. For the
# derived configuration, we need to make those paths relative to where the derived configuration
# file is.
def fix_include_paths(base_config_path, hash, path, key, value)
return unless File.basename(base_config_path).start_with?('.rubocop')
base_dir = File.dirname(base_config_path)
derived_dir = File.dirname(path)
hash[key]['Include'] = value['Include'].map do |include_path|
PathUtil.relative_path(File.join(base_dir, include_path), derived_dir)
end
end
def resolve_inheritance_from_gems(hash)
gems = hash.delete('inherit_gem')
(gems || {}).each_pair do |gem_name, config_path|
if gem_name == 'rubocop'
raise ArgumentError, "can't inherit configuration from the rubocop gem"
end
hash['inherit_from'] = Array(hash['inherit_from'])
Array(config_path).reverse_each do |path|
# Put gem configuration first so local configuration overrides it.
hash['inherit_from'].unshift gem_config_path(gem_name, path)
end
end
end
# Merges the given configuration with the default one. If
# AllCops:DisabledByDefault is true, it changes the Enabled params so that
# only cops from user configuration are enabled. If
# AllCops:EnabledByDefault is true, it changes the Enabled params so that
# only cops explicitly disabled in user configuration are disabled.
def merge_with_default(config, config_file, unset_nil:)
default_configuration = ConfigLoader.default_configuration
disabled_by_default = config.for_all_cops['DisabledByDefault']
enabled_by_default = config.for_all_cops['EnabledByDefault']
if disabled_by_default || enabled_by_default
default_configuration = transform(default_configuration) do |params|
params.merge('Enabled' => !disabled_by_default)
end
end
config = handle_disabled_by_default(config, default_configuration) if disabled_by_default
override_enabled_for_disabled_departments(default_configuration, config)
opts = { inherit_mode: config['inherit_mode'] || {}, unset_nil: unset_nil }
Config.new(merge(default_configuration, config, **opts), config_file)
end
# Return a recursive merge of two hashes. That is, a normal hash merge,
# with the addition that any value that is a hash, and occurs in both
# arguments, will also be merged. And so on.
#
# rubocop:disable Metrics/AbcSize
def merge(base_hash, derived_hash, **opts)
result = base_hash.merge(derived_hash)
keys_appearing_in_both = base_hash.keys & derived_hash.keys
keys_appearing_in_both.each do |key|
if opts[:unset_nil] && derived_hash[key].nil?
result.delete(key)
elsif merge_hashes?(base_hash, derived_hash, key)
result[key] = merge(base_hash[key], derived_hash[key], **opts)
elsif should_union?(derived_hash, base_hash, opts[:inherit_mode], key)
result[key] = Array(base_hash[key]) | Array(derived_hash[key])
elsif opts[:debug]
warn_on_duplicate_setting(base_hash, derived_hash, key, **opts)
end
end
result
end
# rubocop:enable Metrics/AbcSize
# An `Enabled: true` setting in user configuration for a cop overrides an
# `Enabled: false` setting for its department.
def override_department_setting_for_cops(base_hash, derived_hash)
derived_hash.each_key do |key|
next unless key =~ %r{(.*)/.*}
department = Regexp.last_match(1)
next unless disabled?(derived_hash, department) || disabled?(base_hash, department)
# The `override_department` setting for the `Enabled` parameter is an
# internal setting that's not documented in the manual. It will cause a
# cop to be enabled later, when logic surrounding enabled/disabled it
# run, even though its department is disabled.
derived_hash[key]['Enabled'] = 'override_department' if derived_hash[key]['Enabled']
end
end
# If a cop was previously explicitly enabled, but then superseded by the
# department being disabled, disable it.
def override_enabled_for_disabled_departments(base_hash, derived_hash)
cops_to_disable = derived_hash.each_key.with_object([]) do |key, cops|
next unless disabled?(derived_hash, key)
cops.concat(base_hash.keys.grep(Regexp.new("^#{key}/")))
end
cops_to_disable.each do |cop_name|
next unless base_hash.dig(cop_name, 'Enabled') == true
derived_hash.replace(merge({ cop_name => { 'Enabled' => false } }, derived_hash))
end
end
private
def disabled?(hash, department)
hash[department].is_a?(Hash) && hash[department]['Enabled'] == false
end
def duplicate_setting?(base_hash, derived_hash, key, inherited_file)
return false if inherited_file.nil? # Not inheritance resolving merge
return false if inherited_file.start_with?('..') # Legitimate override
return false if base_hash[key] == derived_hash[key] # Same value
return false if PathUtil.remote_file?(inherited_file) # Can't change
Gem.path.none? { |dir| inherited_file.start_with?(dir) } # Can change?
end
def warn_on_duplicate_setting(base_hash, derived_hash, key, **opts)
# If the file being considered is remote, don't bother checking for duplicates
return if remote_config?(opts[:file])
return unless duplicate_setting?(base_hash, derived_hash, key, opts[:inherited_file])
inherit_mode = opts[:inherit_mode]['merge'] || opts[:inherit_mode]['override']
return if base_hash[key].is_a?(Array) && inherit_mode&.include?(key)
puts duplicate_setting_warning(opts, key)
end
def duplicate_setting_warning(opts, key)
"#{PathUtil.smart_path(opts[:file])}: " \
"#{opts[:cop_name]}:#{key} overrides " \
"the same parameter in #{opts[:inherited_file]}"
end
def determine_inherit_mode(hash, key)
cop_cfg = hash[key]
local_inherit = cop_cfg['inherit_mode'] if cop_cfg.is_a?(Hash)
local_inherit || hash['inherit_mode'] || {}
end
def should_union?(derived_hash, base_hash, root_mode, key)
return false unless base_hash[key].is_a?(Array) || derived_hash[key].is_a?(Array)
derived_mode = derived_hash['inherit_mode']
return false if should_override?(derived_mode, key)
return true if should_merge?(derived_mode, key)
base_mode = base_hash['inherit_mode']
return false if should_override?(base_mode, key)
return true if should_merge?(base_mode, key)
should_merge?(root_mode, key)
end
def should_merge?(mode, key)
mode && mode['merge']&.include?(key)
end
def should_override?(mode, key)
mode && mode['override']&.include?(key)
end
def merge_hashes?(base_hash, derived_hash, key)
base_hash[key].is_a?(Hash) && derived_hash[key].is_a?(Hash)
end
def base_configs(path, inherit_from, file)
inherit_froms = Array(inherit_from).compact.flat_map do |f|
PathUtil.glob?(f) ? Dir.glob(f) : f
end
configs = inherit_froms.map do |f|
ConfigLoader.load_file(inherited_file(path, f, file))
end
configs.compact
end
def inherited_file(path, inherit_from, file)
if PathUtil.remote_file?(inherit_from)
# A remote configuration, e.g. `inherit_from: http://example.com/rubocop.yml`.
RemoteConfig.new(inherit_from, ConfigLoader.cache_root)
elsif Pathname.new(inherit_from).absolute?
# An absolute path to a config, e.g. `inherit_from: /Users/me/rubocop.yml`.
# The path may come from `inherit_gem` option, where a gem name is expanded
# to an absolute path to that gem.
print 'Inheriting ' if ConfigLoader.debug?
inherit_from
elsif file.is_a?(RemoteConfig)
# A path relative to a URL, e.g. `inherit_from: configs/default.yml`
# in a config included with `inherit_from: http://example.com/rubocop.yml`
file.inherit_from_remote(inherit_from)
else
# A local relative path, e.g. `inherit_from: default.yml`
print 'Inheriting ' if ConfigLoader.debug?
File.expand_path(inherit_from, File.dirname(path))
end
end
def remote_config?(file)
file.is_a?(RemoteConfig)
end
def handle_disabled_by_default(config, new_default_configuration)
department_config = config.to_hash.reject { |cop| cop.include?('/') }
department_config.each do |dept, dept_params|
next unless dept_params['Enabled']
new_default_configuration.each do |cop, params|
next unless cop.start_with?("#{dept}/")
# Retain original default configuration for cops in the department.
params['Enabled'] = ConfigLoader.default_configuration[cop]['Enabled']
end
end
transform(config) do |params|
{ 'Enabled' => true }.merge(params) # Set true if not set.
end
end
def transform(config, &block)
config.transform_values(&block)
end
def gem_config_path(gem_name, relative_config_path)
if defined?(Bundler)
begin
gem = Bundler.load.specs[gem_name].first
gem_path = gem.full_gem_path if gem
rescue StandardError
# The Gemfile has a problem, which could be one of:
# - No Gemfile found. Bundler may be loaded manually
# - The Gemfile exists but contains an uninstalled git source
# - The Gemfile exists but cannot be loaded for some other reason
end
end
gem_path ||= Gem::Specification.find_by_name(gem_name).gem_dir
File.join(gem_path, relative_config_path)
rescue Gem::LoadError => e
raise Gem::LoadError, "Unable to find gem #{gem_name}; is the gem installed? #{e}"
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_regeneration.rb | lib/rubocop/config_regeneration.rb | # frozen_string_literal: true
module RuboCop
# This class handles collecting the options for regenerating a TODO file.
# @api private
class ConfigRegeneration
AUTO_GENERATED_FILE = RuboCop::CLI::Command::AutoGenerateConfig::AUTO_GENERATED_FILE
COMMAND_REGEX = /(?<=`rubocop )(.*?)(?=`)/.freeze
DEFAULT_OPTIONS = { auto_gen_config: true }.freeze
# Get options from the comment in the TODO file, and parse them as options
def options
# If there's no existing TODO file, generate one
return DEFAULT_OPTIONS unless todo_exists?
match = generation_command.match(COMMAND_REGEX)
return DEFAULT_OPTIONS unless match
options = match[1].split
Options.new.parse(options).first
end
private
def todo_exists?
File.exist?(AUTO_GENERATED_FILE) && !File.empty?(AUTO_GENERATED_FILE)
end
def generation_command
File.foreach(AUTO_GENERATED_FILE).take(2).last
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lockfile.rb | lib/rubocop/lockfile.rb | # frozen_string_literal: true
begin
# We might not be running with `bundle exec`, so we need to pull in Bundler ourselves,
# in order to use `Bundler::LockfileParser`.
require 'bundler'
rescue LoadError
nil
end
module RuboCop
# Encapsulation of a lockfile for use when checking for gems.
# Does not actually resolve gems, just parses the lockfile.
# @api private
class Lockfile
# @param [String, Pathname, nil] lockfile_path
def initialize(lockfile_path = nil)
lockfile_path ||= begin
::Bundler.default_lockfile if use_bundler_lock_parser?
rescue ::Bundler::GemfileNotFound
nil # We might not be a folder with a Gemfile, but that's okay.
end
@lockfile_path = lockfile_path
end
# Gems that the bundle directly depends on.
# @return [Array<Bundler::Dependency>, nil]
def dependencies
return [] unless parser
parser.dependencies.values
end
# All activated gems, including transitive dependencies.
# @return [Array<Bundler::Dependency>, nil]
def gems
return [] unless parser
# `Bundler::LockfileParser` returns `Bundler::LazySpecification` objects
# which are not resolved, so extract the dependencies from them
parser.dependencies.values.concat(parser.specs.flat_map(&:dependencies))
end
# Returns the locked versions of gems from this lockfile.
# @param [Boolean] include_transitive_dependencies: When false, only direct dependencies
# are returned, i.e. those listed explicitly in the `Gemfile`.
# @returns [Hash{String => Gem::Version}] The locked gem versions, keyed by the gems' names.
def gem_versions(include_transitive_dependencies: true)
return {} unless parser
all_gem_versions = parser.specs.to_h { |spec| [spec.name, spec.version] }
if include_transitive_dependencies
all_gem_versions
else
direct_dep_names = parser.dependencies.keys
all_gem_versions.slice(*direct_dep_names)
end
end
# Whether this lockfile includes the named gem, directly or indirectly.
# @param [String] name
# @return [Boolean]
def includes_gem?(name)
gems.any? { |gem| gem.name == name }
end
private
# @return [Bundler::LockfileParser, nil]
def parser
return @parser if defined?(@parser)
@parser = if @lockfile_path && File.exist?(@lockfile_path) && use_bundler_lock_parser?
begin
lockfile = ::Bundler.read_file(@lockfile_path)
::Bundler::LockfileParser.new(lockfile) if lockfile
rescue ::Bundler::BundlerError
nil
end
end
end
def use_bundler_lock_parser?
return false unless Object.const_defined?(:Bundler)
Bundler.const_defined?(:LockfileParser) && Bundler::VERSION >= '2.0'
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_validator.rb | lib/rubocop/config_validator.rb | # frozen_string_literal: true
module RuboCop
# Handles validation of configuration, for example cop names, parameter
# names, and Ruby versions.
# rubocop:disable Metrics/ClassLength
class ConfigValidator
extend SimpleForwardable
# @api private
COMMON_PARAMS = %w[Exclude Include Severity inherit_mode AutoCorrect StyleGuide Details
Enabled Reference References].freeze
# @api private
INTERNAL_PARAMS = %w[Description StyleGuide
VersionAdded VersionChanged VersionRemoved
Reference References Safe SafeAutoCorrect].freeze
# @api private
NEW_COPS_VALUES = %w[pending disable enable].freeze
# @api private
CONFIG_CHECK_KEYS = %w[Enabled Safe SafeAutoCorrect AutoCorrect References].to_set.freeze
CONFIG_CHECK_DEPARTMENTS = %w[pending override_department].freeze
CONFIG_CHECK_AUTOCORRECTS = %w[always contextual disabled].freeze
private_constant :CONFIG_CHECK_KEYS, :CONFIG_CHECK_DEPARTMENTS
def_delegators :@config, :smart_loaded_path, :for_all_cops
def initialize(config)
@config = config
@config_obsoletion = ConfigObsoletion.new(config)
@target_ruby = TargetRuby.new(config)
end
def validate
check_cop_config_value(@config)
reject_conflicting_safe_settings
# Don't validate RuboCop's own files further. Avoids infinite recursion.
return if @config.internal?
valid_cop_names, invalid_cop_names = @config.keys.partition do |key|
ConfigLoader.default_configuration.key?(key)
end
validate_parameter_shape(valid_cop_names)
check_obsoletions
alert_about_unrecognized_cops(invalid_cop_names)
validate_new_cops_parameter
validate_parameter_names(valid_cop_names)
validate_enforced_styles(valid_cop_names)
validate_syntax_cop
reject_mutually_exclusive_defaults
end
# Validations that should only be run after all config resolving has
# taken place:
# * The target ruby version is only checked once the entire inheritance
# chain has been loaded so that only the final value is validated, and
# any obsolete but overridden values are ignored.
def validate_after_resolution
check_target_ruby
end
def target_ruby_version
target_ruby.version
end
private
attr_reader :target_ruby
def check_obsoletions
@config_obsoletion.reject_obsolete!
return unless @config_obsoletion.warnings.any?
warn Rainbow("Warning: #{@config_obsoletion.warnings.join("\n")}").yellow
end
def check_target_ruby
return if target_ruby.supported?
source = target_ruby.source
last_version = target_ruby.rubocop_version_with_support
msg = if last_version
"RuboCop found unsupported Ruby version #{target_ruby_version} " \
"in #{source}. #{target_ruby_version}-compatible " \
"analysis was dropped after version #{last_version}."
else
'RuboCop found unknown Ruby version ' \
"#{target_ruby_version.inspect} in #{source}."
end
msg += "\nSupported versions: #{TargetRuby.supported_versions.join(', ')}"
raise ValidationError, msg
end
def alert_about_unrecognized_cops(invalid_cop_names)
unknown_cops = list_unknown_cops(invalid_cop_names)
return if unknown_cops.empty?
if ConfigLoader.ignore_unrecognized_cops
warn Rainbow('The following cops or departments are not ' \
'recognized and will be ignored:').yellow
warn unknown_cops.join("\n")
return
end
raise ValidationError, unknown_cops.join("\n")
end
def list_unknown_cops(invalid_cop_names)
unknown_cops = []
invalid_cop_names.each do |name|
# There could be a custom cop with this name. If so, don't warn
next if Cop::Registry.global.contains_cop_matching?([name])
next if ConfigObsoletion.deprecated_cop_name?(name)
# Special case for inherit_mode, which is a directive that we keep in
# the configuration (even though it's not a cop), because it's easier
# to do so than to pass the value around to various methods.
next if name == 'inherit_mode'
message = <<~MESSAGE.rstrip
unrecognized cop or department #{name} found in #{smart_loaded_path}
#{suggestion(name)}
MESSAGE
unknown_cops << message
end
unknown_cops
end
def suggestion(name)
registry = Cop::Registry.global
departments = registry.departments.map(&:to_s)
suggestions = NameSimilarity.find_similar_names(name, departments + registry.map(&:cop_name))
if suggestions.any?
"Did you mean `#{suggestions.join('`, `')}`?"
else
# Department names can contain slashes, e.g. Chef/Correctness, but there's no support for
# the concept of higher level departments in RuboCop. It's a flat structure. So if the user
# tries to configure a "top level department", we hint that it's the bottom level
# departments that should be configured.
suggestions = departments.select { |department| department.start_with?("#{name}/") }
"#{name} is not a department. Use `#{suggestions.join('`, `')}`." if suggestions.any?
end
end
def validate_syntax_cop
syntax_config = @config['Lint/Syntax']
default_config = ConfigLoader.default_configuration['Lint/Syntax']
return unless syntax_config && default_config.merge(syntax_config) != default_config
raise ValidationError,
"configuration for Lint/Syntax cop found in #{smart_loaded_path}\n" \
'It\'s not possible to disable this cop.'
end
def validate_new_cops_parameter
new_cop_parameter = @config.for_all_cops['NewCops']
return if new_cop_parameter.nil? || NEW_COPS_VALUES.include?(new_cop_parameter)
message = "invalid #{new_cop_parameter} for `NewCops` found in" \
"#{smart_loaded_path}\n" \
"Valid choices are: #{NEW_COPS_VALUES.join(', ')}"
raise ValidationError, message
end
def validate_parameter_shape(valid_cop_names)
valid_cop_names.each do |name|
if @config[name].nil?
raise ValidationError, "empty section #{name.inspect} found in #{smart_loaded_path}"
elsif !@config[name].is_a?(Hash)
raise ValidationError, <<~MESSAGE
The configuration for #{name.inspect} in #{smart_loaded_path} is not a Hash.
Found: #{@config[name].inspect}
MESSAGE
end
end
end
def validate_parameter_names(valid_cop_names)
valid_cop_names.each do |name|
each_invalid_parameter(name) do |param, supported_params|
warn Rainbow(<<~MESSAGE).yellow
Warning: #{name} does not support #{param} parameter.
Supported parameters are:
- #{supported_params.join("\n - ")}
MESSAGE
end
end
end
def each_invalid_parameter(cop_name)
default_config = ConfigLoader.default_configuration[cop_name]
@config[cop_name].each_key do |param|
next if COMMON_PARAMS.include?(param) || default_config.key?(param)
supported_params = default_config.keys - INTERNAL_PARAMS
yield param, supported_params
end
end
def validate_enforced_styles(valid_cop_names) # rubocop:todo Metrics/AbcSize
valid_cop_names.each do |name|
styles = @config[name].select { |key, _| key.start_with?('Enforced') }
styles.each do |style_name, style|
supported_key = RuboCop::Cop::Util.to_supported_styles(style_name)
valid = ConfigLoader.default_configuration[name][supported_key]
next unless valid
next if valid.include?(style)
next if validate_support_and_has_list(name, style, valid)
msg = "invalid #{style_name} '#{style}' for #{name} found in " \
"#{smart_loaded_path}\n" \
"Valid choices are: #{valid.join(', ')}"
raise ValidationError, msg
end
end
end
def validate_support_and_has_list(name, formats, valid)
ConfigLoader.default_configuration[name]['AllowMultipleStyles'] &&
formats.is_a?(Array) &&
formats.all? { |format| valid.include?(format) }
end
def reject_mutually_exclusive_defaults
disabled_by_default = for_all_cops['DisabledByDefault']
enabled_by_default = for_all_cops['EnabledByDefault']
return unless disabled_by_default && enabled_by_default
msg = 'Cops cannot be both enabled by default and disabled by default'
raise ValidationError, msg
end
def reject_conflicting_safe_settings
@config.each do |name, cop_config|
next unless cop_config.is_a?(Hash)
next unless cop_config['Safe'] == false && cop_config['SafeAutoCorrect'] == true
msg = 'Unsafe cops cannot have a safe autocorrection ' \
"(section #{name} in #{smart_loaded_path})"
raise ValidationError, msg
end
end
def check_cop_config_value(hash, parent = nil) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
hash.each do |key, value|
check_cop_config_value(value, key) if value.is_a?(Hash)
next unless CONFIG_CHECK_KEYS.include?(key) && value.is_a?(String)
if key == 'Enabled' && !CONFIG_CHECK_DEPARTMENTS.include?(value)
supposed_values = 'a boolean'
elsif key == 'AutoCorrect' && !CONFIG_CHECK_AUTOCORRECTS.include?(value)
supposed_values = '`always`, `contextual`, `disabled`, or a boolean'
elsif key == 'References'
supposed_values = 'an array of strings'
else
next
end
raise ValidationError, param_error_message(parent, key, value, supposed_values)
end
end
# FIXME: Handling colors in exception messages like this is ugly.
def param_error_message(parent, key, value, supposed_values)
"#{Rainbow('').reset}" \
"Property #{Rainbow(key).yellow} of #{Rainbow(parent).yellow} cop " \
"is supposed to be #{supposed_values} and #{Rainbow(value).yellow} is not."
end
end
# rubocop:enable Metrics/ClassLength
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/options.rb | lib/rubocop/options.rb | # frozen_string_literal: true
require 'optparse'
require_relative 'arguments_env'
require_relative 'arguments_file'
module RuboCop
class IncorrectCopNameError < StandardError; end
class OptionArgumentError < StandardError; end
# This class handles command line options.
# @api private
class Options
E_STDIN_NO_PATH = '-s/--stdin requires exactly one path, relative to the ' \
'root of the project. RuboCop will use this path to determine which ' \
'cops are enabled (via eg. Include/Exclude), and so that certain cops ' \
'like Naming/FileName can be checked.'
EXITING_OPTIONS = %i[version verbose_version show_cops show_docs_url lsp].freeze
DEFAULT_MAXIMUM_EXCLUSION_ITEMS = 15
def initialize
@options = {}
@validator = OptionsValidator.new(@options)
end
def parse(command_line_args)
args_from_file = ArgumentsFile.read_as_arguments
args_from_env = ArgumentsEnv.read_as_arguments
args = args_from_file.concat(args_from_env).concat(command_line_args)
define_options.parse!(args)
@validator.validate_compatibility
if @options[:stdin]
# The parser will put the file name given after --stdin into
# @options[:stdin]. If it did, then the args array should be empty.
raise OptionArgumentError, E_STDIN_NO_PATH if args.any?
# We want the STDIN contents in @options[:stdin] and the file name in
# args to simplify the rest of the processing.
args = [@options[:stdin]]
@options[:stdin] = $stdin.binmode.read
end
[@options, args]
end
private
# rubocop:disable Metrics/AbcSize
def define_options
OptionParser.new do |opts|
opts.banner = rainbow.wrap('Usage: rubocop [options] [file1, file2, ...]').bright
add_check_options(opts)
add_cache_options(opts)
add_lsp_option(opts)
add_server_options(opts)
add_output_options(opts)
add_autocorrection_options(opts)
add_config_generation_options(opts)
add_additional_modes(opts)
add_general_options(opts)
# `stackprof` is not supported on JRuby and Windows.
add_profile_options(opts) if RUBY_ENGINE == 'ruby' && !Platform.windows?
end
end
# rubocop:enable Metrics/AbcSize
def add_check_options(opts) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
section(opts, 'Basic Options') do # rubocop:disable Metrics/BlockLength
option(opts, '-l', '--lint') do
@options[:only] ||= []
@options[:only] << 'Lint'
end
option(opts, '-x', '--fix-layout') do
@options[:only] ||= []
@options[:only] << 'Layout'
@options[:autocorrect] = true
end
option(opts, '--safe')
add_cop_selection_csv_option('except', opts)
add_cop_selection_csv_option('only', opts)
option(opts, '--only-guide-cops')
option(opts, '-F', '--fail-fast')
option(opts, '--disable-pending-cops')
option(opts, '--enable-pending-cops')
option(opts, '--ignore-disable-comments')
option(opts, '--force-exclusion')
option(opts, '--only-recognized-file-types')
option(opts, '--ignore-parent-exclusion')
option(opts, '--ignore-unrecognized-cops')
option(opts, '--force-default-config')
option(opts, '-s', '--stdin FILE')
option(opts, '--editor-mode')
option(opts, '-P', '--[no-]parallel')
option(opts, '--raise-cop-error')
add_severity_option(opts)
end
end
def add_output_options(opts) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
section(opts, 'Output Options') do
option(opts, '-f', '--format FORMATTER') do |key|
@options[:formatters] ||= []
@options[:formatters] << [key]
end
option(opts, '-D', '--[no-]display-cop-names')
option(opts, '-E', '--extra-details')
option(opts, '-S', '--display-style-guide')
option(opts, '-o', '--out FILE') do |path|
if @options[:formatters]
@options[:formatters].last << path
else
@options[:output_path] = path
end
end
option(opts, '--stderr')
option(opts, '--display-time')
option(opts, '--display-only-failed')
option(opts, '--display-only-fail-level-offenses')
option(opts, '--display-only-correctable')
option(opts, '--display-only-safe-correctable')
end
end
# rubocop:todo Naming/InclusiveLanguage
# the autocorrect command-line arguments map to the autocorrect @options values like so:
# :fix_layout :autocorrect :safe_autocorrect :autocorrect_all
# -x, --fix-layout true true - -
# -a, --auto-correct - true true -
# --safe-auto-correct - true true -
# -A, --auto-correct-all - true - true
def add_autocorrection_options(opts) # rubocop:disable Metrics/MethodLength
section(opts, 'Autocorrection') do
option(opts, '-a', '--autocorrect') { @options[:safe_autocorrect] = true }
option(opts, '--auto-correct') do
handle_deprecated_option('--auto-correct', '--autocorrect')
@options[:safe_autocorrect] = true
end
option(opts, '--safe-auto-correct') do
handle_deprecated_option('--safe-auto-correct', '--autocorrect')
@options[:safe_autocorrect] = true
end
option(opts, '-A', '--autocorrect-all') { @options[:autocorrect] = true }
option(opts, '--auto-correct-all') do
handle_deprecated_option('--auto-correct-all', '--autocorrect-all')
@options[:autocorrect] = true
end
option(opts, '--disable-uncorrectable')
end
end
# rubocop:enable Naming/InclusiveLanguage
def add_config_generation_options(opts)
section(opts, 'Config Generation') do
option(opts, '--auto-gen-config')
option(opts, '--regenerate-todo') do
@options.replace(ConfigRegeneration.new.options.merge(@options))
end
option(opts, '--exclude-limit COUNT') { @validator.validate_exclude_limit_option }
option(opts, '--no-exclude-limit')
option(opts, '--[no-]offense-counts')
option(opts, '--[no-]auto-gen-only-exclude')
option(opts, '--[no-]auto-gen-timestamp')
option(opts, '--[no-]auto-gen-enforced-style')
end
end
def add_cop_selection_csv_option(option, opts)
option(opts, "--#{option} [COP1,COP2,...]") do |list|
unless list
message = "--#{option} argument should be [COP1,COP2,...]."
raise OptionArgumentError, message
end
cop_names = list.empty? ? [''] : list.split(',')
cop_names.unshift('Lint/Syntax') if option == 'only' && !cop_names.include?('Lint/Syntax')
@options[:"#{option}"] = cop_names
end
end
def add_severity_option(opts)
table = RuboCop::Cop::Severity::CODE_TABLE.merge(A: :autocorrect)
option(opts, '--fail-level SEVERITY',
RuboCop::Cop::Severity::NAMES + [:autocorrect],
table) do |severity|
@options[:fail_level] = severity
end
end
def add_cache_options(opts)
section(opts, 'Caching') do
option(opts, '-C', '--cache FLAG')
option(opts, '--cache-root DIR') { @validator.validate_cache_enabled_for_cache_root }
end
end
def add_lsp_option(opts)
section(opts, 'LSP Option') do
option(opts, '--lsp')
end
end
def add_server_options(opts)
section(opts, 'Server Options') do
option(opts, '--[no-]server')
option(opts, '--restart-server')
option(opts, '--start-server')
option(opts, '--stop-server')
option(opts, '--server-status')
option(opts, '--no-detach')
end
end
def add_additional_modes(opts)
section(opts, 'Additional Modes') do
option(opts, '-L', '--list-target-files')
option(opts, '--show-cops [COP1,COP2,...]') do |list|
@options[:show_cops] = list.nil? ? [] : list.split(',')
end
option(opts, '--show-docs-url [COP1,COP2,...]') do |list|
@options[:show_docs_url] = list.nil? ? [] : list.split(',')
end
end
end
def add_general_options(opts)
section(opts, 'General Options') do
option(opts, '--init')
option(opts, '-c', '--config FILE')
option(opts, '-d', '--debug')
option(opts, '--plugin FILE') { |f| plugin_feature(f) }
option(opts, '-r', '--require FILE') { |f| require_feature(f) }
option(opts, '--[no-]color')
option(opts, '-v', '--version')
option(opts, '-V', '--verbose-version')
end
end
def add_profile_options(opts)
section(opts, 'Profiling Options') do
option(opts, '--profile') do
@options[:profile] = true
@options[:cache] = 'false' unless @options.key?(:cache)
end
option(opts, '--memory')
end
end
def handle_deprecated_option(old_option, new_option)
warn rainbow.wrap("#{old_option} is deprecated; use #{new_option} instead.").yellow
@options[long_opt_symbol([new_option])] = @options.delete(long_opt_symbol([old_option]))
end
def rainbow
@rainbow ||= begin
rainbow = Rainbow.new
rainbow.enabled = false if ARGV.include?('--no-color')
rainbow
end
end
# Creates a section of options in order to separate them visually when
# using `--help`.
def section(opts, heading, &_block)
heading = rainbow.wrap(heading).bright
opts.separator("\n#{heading}:\n")
yield
end
# Sets a value in the @options hash, based on the given long option and its
# value, in addition to calling the block if a block is given.
def option(opts, *args)
long_opt_symbol = long_opt_symbol(args)
args += Array(OptionsHelp::TEXT[long_opt_symbol])
opts.on(*args) do |arg|
@options[long_opt_symbol] = arg
yield arg if block_given?
end
end
# Finds the option in `args` starting with -- and converts it to a symbol,
# e.g. [..., '--autocorrect', ...] to :autocorrect.
def long_opt_symbol(args)
long_opt = args.find { |arg| arg.start_with?('--') }
long_opt[2..].sub('[no-]', '').sub(/ .*/, '').tr('-', '_').gsub(/[\[\]]/, '').to_sym
end
def plugin_feature(file)
# If any features were added on the CLI from `--plugin`,
# add them to the config.
ConfigLoaderResolver.new.resolve_plugins(Config.new, file)
end
def require_feature(file)
if Plugin.plugin_capable?(file)
# NOTE: Compatibility for before plugins style.
warn Rainbow(<<~MESSAGE).yellow
#{file} gem supports plugin, use `--plugin` instead of `--require`.
MESSAGE
plugin_feature(file)
else
# If any features were added on the CLI from `--require`,
# add them to the config.
require file
ConfigLoader.add_loaded_features(file)
end
end
end
# Validates option arguments and the options' compatibility with each other.
# @api private
class OptionsValidator
class << self
SYNTAX_DEPARTMENTS = %w[Syntax Lint/Syntax].freeze
private_constant :SYNTAX_DEPARTMENTS
# Cop name validation must be done later than option parsing, so it's not
# called from within Options.
def validate_cop_list(names)
return unless names
cop_names = Cop::Registry.global.names
departments = Cop::Registry.global.departments.map(&:to_s)
names.each do |name|
next if cop_names.include?(name)
next if departments.include?(name)
next if SYNTAX_DEPARTMENTS.include?(name)
raise IncorrectCopNameError, format_message_from(name, cop_names)
end
end
private
def format_message_from(name, cop_names)
message = 'Unrecognized cop or department: %<name>s.'
message_with_candidate = "%<message>s\nDid you mean? %<candidate>s"
corrections = NameSimilarity.find_similar_names(name, cop_names)
if corrections.empty?
format(message, name: name)
else
format(message_with_candidate, message: format(message, name: name),
candidate: corrections.join(', '))
end
end
end
def initialize(options)
@options = options
end
def validate_cop_options
%i[only except].each { |opt| OptionsValidator.validate_cop_list(@options[opt]) }
end
# rubocop:disable Metrics/AbcSize
def validate_compatibility # rubocop:disable Metrics/MethodLength
if only_includes_redundant_disable?
raise OptionArgumentError, 'Lint/RedundantCopDisableDirective cannot be used with --only.'
end
raise OptionArgumentError, 'Syntax checking cannot be turned off.' if except_syntax?
unless boolean_or_empty_cache?
raise OptionArgumentError, '-C/--cache argument must be true or false'
end
validate_auto_gen_config
validate_autocorrect
validate_display_only_failed
validate_display_only_failed_and_display_only_correctable
validate_display_only_correctable_and_autocorrect
validate_lsp_and_editor_mode
disable_parallel_when_invalid_option_combo
return if incompatible_options.size <= 1
raise OptionArgumentError, "Incompatible cli options: #{incompatible_options.inspect}"
end
# rubocop:enable Metrics/AbcSize
def validate_auto_gen_config
return if @options.key?(:auto_gen_config)
message = '--%<flag>s can only be used together with --auto-gen-config.'
%i[exclude_limit offense_counts auto_gen_timestamp
auto_gen_only_exclude].each do |option|
if @options.key?(option)
raise OptionArgumentError, format(message, flag: option.to_s.tr('_', '-'))
end
end
end
def validate_display_only_failed
return unless @options.key?(:display_only_failed)
return if @options[:format] == 'junit'
raise OptionArgumentError,
'--display-only-failed can only be used together with --format junit.'
end
def validate_display_only_correctable_and_autocorrect
return unless @options.key?(:autocorrect)
return if !@options.key?(:display_only_correctable) &&
!@options.key?(:display_only_safe_correctable)
raise OptionArgumentError,
'--autocorrect cannot be used with --display-only-[safe-]correctable.'
end
def validate_display_only_failed_and_display_only_correctable
return unless @options.key?(:display_only_failed)
return if !@options.key?(:display_only_correctable) &&
!@options.key?(:display_only_safe_correctable)
raise OptionArgumentError,
'--display-only-failed cannot be used together with other display options.'
end
def validate_lsp_and_editor_mode
return if !@options.key?(:lsp) || !@options.key?(:editor_mode)
raise OptionArgumentError, 'Do not specify `--editor-mode` as it is redundant in `--lsp`.'
end
def validate_autocorrect
if @options.key?(:safe_autocorrect) && @options.key?(:autocorrect_all)
message = Rainbow(<<~MESSAGE).red
Error: Both safe and unsafe autocorrect options are specified, use only one.
MESSAGE
raise OptionArgumentError, message
end
return if @options.key?(:autocorrect)
return unless @options.key?(:disable_uncorrectable)
raise OptionArgumentError,
'--disable-uncorrectable can only be used together with --autocorrect.'
end
def disable_parallel_when_invalid_option_combo
return unless @options.key?(:parallel)
invalid_flags = invalid_arguments_for_parallel
return if invalid_flags.empty?
@options.delete(:parallel)
puts '-P/--parallel is being ignored because ' \
"it is not compatible with #{invalid_flags.join(', ')}."
end
def invalid_arguments_for_parallel
[('--auto-gen-config' if @options.key?(:auto_gen_config)),
('-F/--fail-fast' if @options.key?(:fail_fast)),
('--profile' if @options[:profile]),
('--memory' if @options[:memory]),
('--cache false' if @options > { cache: 'false' })].compact
end
def only_includes_redundant_disable?
@options.key?(:only) &&
(@options[:only] & %w[Lint/RedundantCopDisableDirective RedundantCopDisableDirective]).any?
end
def except_syntax?
@options.key?(:except) && (@options[:except] & %w[Lint/Syntax Syntax]).any?
end
def boolean_or_empty_cache?
!@options.key?(:cache) || %w[true false].include?(@options[:cache])
end
def incompatible_options
@incompatible_options ||= @options.keys & Options::EXITING_OPTIONS
end
def validate_exclude_limit_option
return if /^\d+$/.match?(@options[:exclude_limit])
# Emulate OptionParser's behavior to make failures consistent regardless
# of option order.
raise OptionParser::MissingArgument
end
def validate_cache_enabled_for_cache_root
return unless @options[:cache] == 'false'
raise OptionArgumentError, '--cache-root cannot be used with --cache false'
end
end
# This module contains help texts for command line options.
# @api private
# rubocop:disable Metrics/ModuleLength
module OptionsHelp
MAX_EXCL = RuboCop::Options::DEFAULT_MAXIMUM_EXCLUSION_ITEMS.to_s
FORMATTER_OPTION_LIST = RuboCop::Formatter::FormatterSet::BUILTIN_FORMATTERS_FOR_KEYS.keys
TEXT = {
only: 'Run only the given cop(s).',
only_guide_cops: ['Run only cops for rules that link to a',
'style guide.'],
except: 'Exclude the given cop(s).',
plugin: 'Load a RuboCop plugin.',
require: 'Require Ruby file.',
config: 'Specify configuration file.',
auto_gen_config: ['Generate a configuration file acting as a',
'TODO list.'],
regenerate_todo: ['Regenerate the TODO configuration file using',
'the last configuration. If there is no existing',
'TODO file, acts like --auto-gen-config.'],
offense_counts: ['Include offense counts in configuration',
'file generated by --auto-gen-config.',
'Default is true.'],
auto_gen_timestamp:
['Include the date and time when the --auto-gen-config',
'was run in the file it generates. Default is true.'],
auto_gen_enforced_style:
['Add a setting to the TODO configuration file to enforce',
'the style used, rather than a per-file exclusion',
'if one style is used in all files for cop with',
'EnforcedStyle as a configurable option',
'when the --auto-gen-config was run',
'in the file it generates. Default is true.'],
auto_gen_only_exclude:
['Generate only Exclude parameters and not Max',
'when running --auto-gen-config, except if the',
'number of files with offenses is bigger than',
'exclude-limit. Default is false.'],
exclude_limit: ['Set the limit for how many files to explicitly exclude.',
'If there are more files than the limit, the cop will',
"be disabled instead. Default is #{MAX_EXCL}."],
disable_uncorrectable: ['Used with --autocorrect to annotate any',
'offenses that do not support autocorrect',
'with `rubocop:todo` comments.'],
no_exclude_limit: ['Do not set the limit for how many files to exclude.'],
force_exclusion: ['Any files excluded by `Exclude` in configuration',
'files will be excluded, even if given explicitly',
'as arguments.'],
only_recognized_file_types: ['Inspect files given on the command line only if',
'they are listed in `AllCops/Include` parameters',
'of user configuration or default configuration.'],
ignore_disable_comments: ['Report offenses even if they have been manually disabled',
'with a `rubocop:disable` or `rubocop:todo` directive.'],
ignore_parent_exclusion: ['Prevent from inheriting `AllCops/Exclude` from',
'parent folders.'],
ignore_unrecognized_cops: ['Ignore unrecognized cops or departments in the config.'],
force_default_config: ['Use default configuration even if configuration',
'files are present in the directory tree.'],
format: ['Choose an output formatter. This option',
'can be specified multiple times to enable',
'multiple formatters at the same time.',
*FORMATTER_OPTION_LIST.map do |item|
" #{item}#{' (default)' if item == '[p]rogress'}"
end,
' custom formatter class name'],
out: ['Write output to a file instead of STDOUT.',
'This option applies to the previously',
'specified --format, or the default format',
'if no format is specified.'],
fail_level: ['Minimum severity for exit with error code.',
' [A] autocorrect',
' [I] info',
' [R] refactor',
' [C] convention',
' [W] warning',
' [E] error',
' [F] fatal'],
display_time: 'Display elapsed time in seconds.',
display_only_failed: ['Only output offense messages. Omit passing',
'cops. Only valid for --format junit.'],
display_only_fail_level_offenses:
['Only output offense messages at',
'the specified --fail-level or above.'],
display_only_correctable: ['Only output correctable offense messages.'],
display_only_safe_correctable: ['Only output safe-correctable offense messages',
'when combined with --display-only-correctable.'],
show_cops: ['Shows the given cops, or all cops by',
'default, and their configurations for the',
'current directory.',
'You can use `*` as a wildcard.'],
show_docs_url: ['Display url to documentation for the given',
'cops, or base url by default.'],
fail_fast: ['Inspect files in order of modification',
'time and stop after the first file',
'containing offenses.'],
cache: ["Use result caching (FLAG=true) or don't",
'(FLAG=false), default determined by',
'configuration parameter AllCops: UseCache.'],
cache_root: ['Set the cache root directory.',
'Takes precedence over the configuration',
'parameter AllCops: CacheRootDirectory and',
'the $RUBOCOP_CACHE_ROOT environment variable.'],
debug: 'Display debug info.',
display_cop_names: ['Display cop names in offense messages.',
'Default is true.'],
disable_pending_cops: 'Run without pending cops.',
display_style_guide: 'Display style guide URLs in offense messages.',
enable_pending_cops: 'Run with pending cops.',
extra_details: 'Display extra details in offense messages.',
lint: 'Run only lint cops.',
safe: 'Run only safe cops.',
stderr: ['Write all output to stderr except for the',
'autocorrected source. This is especially useful',
'when combined with --autocorrect and --stdin.'],
list_target_files: 'List all files RuboCop will inspect.',
autocorrect: 'Autocorrect offenses (only when it\'s safe).',
auto_correct: '(same, deprecated)',
safe_auto_correct: '(same, deprecated)',
autocorrect_all: 'Autocorrect offenses (safe and unsafe).',
auto_correct_all: '(same, deprecated)',
fix_layout: 'Run only layout cops, with autocorrect on.',
color: 'Force color output on or off.',
version: 'Display version.',
verbose_version: 'Display verbose version.',
parallel: ['Use available CPUs to execute inspection in',
'parallel. Default is true.',
'You can specify the number of parallel processes using',
'the $PARALLEL_PROCESSOR_COUNT environment variable.'],
stdin: ['Pipe source from STDIN, using FILE in offense',
'reports. This is useful for editor integration.'],
editor_mode: ['Optimize real-time feedback in editors,',
'adjusting behaviors for editing experience.'],
init: 'Generate a .rubocop.yml file in the current directory.',
server: ['If a server process has not been started yet, start',
'the server process and execute inspection with server.',
'Default is false.',
'You can specify the server host and port with the',
'$RUBOCOP_SERVER_HOST and the $RUBOCOP_SERVER_PORT',
'environment variables.'],
restart_server: 'Restart server process.',
start_server: 'Start server process.',
stop_server: 'Stop server process.',
server_status: 'Show server status.',
no_detach: 'Run the server process in the foreground.',
lsp: 'Start a language server listening on STDIN.',
raise_cop_error: ['Raise cop-related errors with cause and location.',
'This is used to prevent cops from failing silently.',
'Default is false.'],
profile: 'Profile rubocop.',
memory: 'Profile rubocop memory usage.'
}.freeze
end
# rubocop:enable Metrics/ModuleLength
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion.rb | lib/rubocop/config_obsoletion.rb | # frozen_string_literal: true
module RuboCop
# This class handles obsolete configuration.
# @api private
class ConfigObsoletion
DEFAULT_RULES_FILE = File.join(ConfigLoader::RUBOCOP_HOME, 'config', 'obsoletion.yml')
COP_RULE_CLASSES = {
'renamed' => RenamedCop,
'removed' => RemovedCop,
'split' => SplitCop,
'extracted' => ExtractedCop
}.freeze
PARAMETER_RULE_CLASSES = {
'changed_parameters' => ChangedParameter,
'changed_enforced_styles' => ChangedEnforcedStyles
}.freeze
LOAD_RULES_CACHE = {} # rubocop:disable Style/MutableConstant
private_constant :LOAD_RULES_CACHE
attr_reader :rules, :warnings
class << self
attr_accessor :files
def global
@global ||= new(Config.new)
end
def reset!
@global = nil
@deprecated_names = {}
LOAD_RULES_CACHE[rules_cache_key] = nil
end
def rules_cache_key
files.hash
end
def legacy_cop_names
# Used by DepartmentName#qualified_legacy_cop_name
global.legacy_cop_names
end
def deprecated_cop_name?(name)
global.deprecated_cop_name?(name)
end
def deprecated_names_for(cop)
@deprecated_names ||= {}
return @deprecated_names[cop] if @deprecated_names.key?(cop)
@deprecated_names[cop] = global.rules.filter_map do |rule|
next unless rule.cop_rule?
next unless rule.respond_to?(:new_name)
next unless rule.new_name == cop
rule.old_name
end
end
end
# Can be extended by extension libraries to add their own obsoletions
self.files = [DEFAULT_RULES_FILE]
def initialize(config)
@config = config
@rules = load_rules
@warnings = []
end
def reject_obsolete!
messages = obsoletions.flatten.compact
return if messages.empty?
raise ValidationError, messages.join("\n")
end
def legacy_cop_names
# Used by DepartmentName#qualified_legacy_cop_name
cop_rules.map(&:old_name)
end
def deprecated_cop_name?(name)
legacy_cop_names.include?(name)
end
private
# Default rules for obsoletions are in config/obsoletion.yml
# Additional rules files can be added with `RuboCop::ConfigObsoletion.files << filename`
def load_rules # rubocop:disable Metrics/AbcSize
rules = LOAD_RULES_CACHE[self.class.rules_cache_key] ||=
self.class.files.each_with_object({}) do |filename, hash|
hash.merge!(YAML.safe_load(File.read(filename)) || {}) do |_key, first, second|
case first
when Hash
first.merge(second)
when Array
first.concat(second)
end
end
end
cop_rules = rules.slice(*COP_RULE_CLASSES.keys)
parameter_rules = rules.slice(*PARAMETER_RULE_CLASSES.keys)
load_cop_rules(cop_rules).concat(load_parameter_rules(parameter_rules))
end
# Cop rules are keyed by the name of the original cop
def load_cop_rules(rules)
rules.flat_map do |rule_type, data|
data.filter_map do |cop_name, configuration|
next unless configuration # allow configurations to be disabled with `CopName: ~`
COP_RULE_CLASSES[rule_type].new(@config, cop_name, configuration)
end
end
end
# Parameter rules may apply to multiple cops and multiple parameters
# and are given as an array. Each combination is turned into a separate
# rule object.
def load_parameter_rules(rules)
rules.flat_map do |rule_type, data|
data.flat_map do |configuration|
cops = Array(configuration['cops'])
parameters = Array(configuration['parameters'])
cops.product(parameters).map do |cop, parameter|
PARAMETER_RULE_CLASSES[rule_type].new(@config, cop, parameter, configuration)
end
end
end
end
def obsoletions
rules.map do |rule|
next unless rule.violated?
if rule.warning?
@warnings.push(rule.message)
next
end
rule.message
end
end
def cop_rules
rules.select(&:cop_rule?)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/file_finder.rb | lib/rubocop/file_finder.rb | # frozen_string_literal: true
require 'pathname'
module RuboCop
# Common methods for finding files.
# @api private
module FileFinder
class << self
attr_accessor :root_level
end
def find_file_upwards(filename, start_dir, stop_dir = nil)
traverse_files_upwards(filename, start_dir, stop_dir) do |file|
# minimize iteration for performance
return file if file
end
end
def find_last_file_upwards(filename, start_dir, stop_dir = nil)
last_file = nil
traverse_files_upwards(filename, start_dir, stop_dir) { |file| last_file = file }
last_file
end
def traverse_directories_upwards(start_dir, stop_dir = nil)
Pathname.new(start_dir).expand_path.ascend do |dir|
yield(dir)
dir = dir.to_s
break if dir == stop_dir || dir == FileFinder.root_level
end
end
private
def traverse_files_upwards(filename, start_dir, stop_dir)
traverse_directories_upwards(start_dir, stop_dir) do |dir|
file = dir + filename
yield(file.to_s) if file.exist?
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp.rb | lib/rubocop/lsp.rb | # frozen_string_literal: true
module RuboCop
# The RuboCop's built-in LSP module.
module LSP
module_function
# Returns true when LSP is enabled, false when disabled.
#
# @return [Boolean]
def enabled?
@enabled ||= false
end
# Enable LSP.
#
# @return [void]
def enable
@enabled = true
end
# Disable LSP.
#
# @return [void]
def disable(&block)
if block
original = @enabled
@enabled = false
yield
@enabled = original
else
@enabled = false
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_loader.rb | lib/rubocop/config_loader.rb | # frozen_string_literal: true
require 'erb'
require 'yaml'
require_relative 'config_finder'
module RuboCop
# Raised when a RuboCop configuration file is not found.
class ConfigNotFoundError < Error
end
# This class represents the configuration of the RuboCop application
# and all its cops. A Config is associated with a YAML configuration
# file from which it was read. Several different Configs can be used
# during a run of the rubocop program, if files in several
# directories are inspected.
class ConfigLoader
DOTFILE = ConfigFinder::DOTFILE
RUBOCOP_HOME = File.realpath(File.join(File.dirname(__FILE__), '..', '..'))
DEFAULT_FILE = File.join(RUBOCOP_HOME, 'config', 'default.yml')
class << self
include FileFinder
attr_accessor :debug, :ignore_parent_exclusion, :disable_pending_cops, :enable_pending_cops,
:ignore_unrecognized_cops, :cache_root
attr_writer :default_configuration
attr_reader :loaded_plugins, :loaded_features
alias debug? debug
alias ignore_parent_exclusion? ignore_parent_exclusion
def clear_options
@debug = nil
@loaded_plugins = Set.new
@loaded_features = Set.new
@disable_pending_cops = nil
@enable_pending_cops = nil
@ignore_parent_exclusion = nil
@ignore_unrecognized_cops = nil
@cache_root = nil
FileFinder.root_level = nil
end
# rubocop:disable Metrics/AbcSize
def load_file(file, check: true)
path = file_path(file)
hash = load_yaml_configuration(path)
rubocop_config = Config.create(hash, path, check: false)
plugins = hash.delete('plugins')
loaded_plugins = resolver.resolve_plugins(rubocop_config, plugins)
add_loaded_plugins(loaded_plugins)
loaded_features = resolver.resolve_requires(path, hash)
add_loaded_features(loaded_features)
resolver.resolve_inheritance_from_gems(hash)
resolver.resolve_inheritance(path, hash, file, debug?)
hash.delete('inherit_from')
# Adding missing namespaces only after resolving requires & inheritance,
# since both can introduce new cops that need to be considered here.
add_missing_namespaces(path, hash)
Config.create(hash, path, check: check)
end
# rubocop:enable Metrics/AbcSize
def load_yaml_configuration(absolute_path)
file_contents = read_file(absolute_path)
yaml_code = Dir.chdir(File.dirname(absolute_path)) { ERB.new(file_contents).result }
yaml_tree = check_duplication(yaml_code, absolute_path)
hash = yaml_tree_to_hash(yaml_tree) || {}
puts "configuration from #{absolute_path}" if debug?
unless hash.is_a?(Hash)
raise(ValidationError, "Malformed configuration in #{absolute_path}")
end
hash
end
def add_missing_namespaces(path, hash)
# Using `hash.each_key` will cause the
# `can't add a new key into hash during iteration` error
obsoletion = ConfigObsoletion.new(hash)
hash_keys = hash.keys
hash_keys.each do |key|
next if obsoletion.deprecated_cop_name?(key)
q = Cop::Registry.qualified_cop_name(key, path)
next if q == key
hash[q] = hash.delete(key)
end
end
# Return a recursive merge of two hashes. That is, a normal hash merge,
# with the addition that any value that is a hash, and occurs in both
# arguments, will also be merged. And so on.
def merge(base_hash, derived_hash)
resolver.merge(base_hash, derived_hash)
end
# Returns the path of .rubocop.yml searching upwards in the
# directory structure starting at the given directory where the
# inspected file is. If no .rubocop.yml is found there, the
# user's home directory is checked. If there's no .rubocop.yml
# there either, the path to the default file is returned.
def configuration_file_for(target_dir)
ConfigFinder.find_config_path(target_dir)
end
def configuration_from_file(config_file, check: true)
return default_configuration if config_file == DEFAULT_FILE
config = load_file(config_file, check: check)
config.validate_after_resolution if check
if ignore_parent_exclusion?
print 'Ignoring AllCops/Exclude from parent folders' if debug?
else
add_excludes_from_files(config, config_file)
end
merge_with_default(config, config_file)
end
def add_excludes_from_files(config, config_file)
exclusion_file = find_last_file_upwards(DOTFILE, config_file, ConfigFinder.project_root)
return unless exclusion_file
return if PathUtil.relative_path(exclusion_file) == PathUtil.relative_path(config_file)
print 'AllCops/Exclude ' if debug?
config.add_excludes_from_higher_level(load_file(exclusion_file))
end
def default_configuration
@default_configuration ||= begin
print 'Default ' if debug?
load_file(DEFAULT_FILE)
end
end
# This API is primarily intended for testing and documenting plugins.
# When testing a plugin using `rubocop/rspec/support`, the plugin is loaded automatically,
# so this API is usually not needed. It is intended to be used only when implementing tests
# that do not use `rubocop/rspec/support`.
# rubocop:disable Metrics/MethodLength
def inject_defaults!(config_yml_path)
if Pathname(config_yml_path).directory?
# TODO: Since the warning noise is expected to be high until some time after the release,
# warnings will only be issued when `RUBYOPT=-w` is specified.
# To proceed step by step, the next step is to remove `$VERBOSE` and always issue warning.
# Eventually, `project_root` will no longer be accepted.
if $VERBOSE
warn Rainbow(<<~MESSAGE).yellow, uplevel: 1
Use config YAML file path instead of project root directory.
e.g., `path/to/config/default.yml`
MESSAGE
end
# NOTE: For compatibility.
project_root = config_yml_path
path = File.join(project_root, 'config', 'default.yml')
config = load_file(path)
else
hash = ConfigLoader.load_yaml_configuration(config_yml_path.to_s)
config = Config.new(hash, config_yml_path).tap(&:make_excludes_absolute)
end
@default_configuration = ConfigLoader.merge_with_default(config, path)
end
# rubocop:enable Metrics/MethodLength
# Returns the path RuboCop inferred as the root of the project. No file
# searches will go past this directory.
# @deprecated Use `RuboCop::ConfigFinder.project_root` instead.
def project_root
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`RuboCop::ConfigLoader.project_root` is deprecated and will be removed in RuboCop 2.0. \
Use `RuboCop::ConfigFinder.project_root` instead.
WARNING
ConfigFinder.project_root
end
# Merges the given configuration with the default one.
def merge_with_default(config, config_file, unset_nil: true)
resolver.merge_with_default(config, config_file, unset_nil: unset_nil)
end
# @api private
# Used to add plugins that were required inside a config or from
# the CLI using `--plugin`.
def add_loaded_plugins(loaded_plugins)
@loaded_plugins.merge(Array(loaded_plugins))
end
# @api private
# Used to add features that were required inside a config or from
# the CLI using `--require`.
def add_loaded_features(loaded_features)
@loaded_features.merge(Array(loaded_features))
end
private
def file_path(file)
File.absolute_path(file.is_a?(RemoteConfig) ? file.file : file)
end
def resolver
@resolver ||= ConfigLoaderResolver.new
end
def check_duplication(yaml_code, absolute_path)
smart_path = PathUtil.smart_path(absolute_path)
YAMLDuplicationChecker.check(yaml_code, absolute_path) do |key1, key2|
value = key1.value
# .start_line is only available since ruby 2.5 / psych 3.0
message = if key1.respond_to? :start_line
line1 = key1.start_line + 1
line2 = key2.start_line + 1
"#{smart_path}:#{line1}: " \
"`#{value}` is concealed by line #{line2}"
else
"#{smart_path}: `#{value}` is concealed by duplicate"
end
warn Rainbow(message).yellow
end
end
# Read the specified file, or exit with a friendly, concise message on
# stderr. Care is taken to use the standard OS exit code for a "file not
# found" error.
def read_file(absolute_path)
File.read(absolute_path, encoding: Encoding::UTF_8)
rescue Errno::ENOENT
raise ConfigNotFoundError, "Configuration file not found: #{absolute_path}"
end
def yaml_tree_to_hash(yaml_tree)
yaml_tree_to_hash!(yaml_tree)
rescue ::StandardError
if defined?(::SafeYAML)
raise 'SafeYAML is unmaintained, no longer needed and should be removed'
end
raise
end
def yaml_tree_to_hash!(yaml_tree)
return nil unless yaml_tree
# Optimization: Because we checked for duplicate keys, we already have the
# yaml tree and don't need to parse it again.
# Also see https://github.com/ruby/psych/blob/v5.1.2/lib/psych.rb#L322-L336
class_loader = YAML::ClassLoader::Restricted.new(%w[Regexp Symbol], [])
scanner = YAML::ScalarScanner.new(class_loader)
visitor = YAML::Visitors::ToRuby.new(scanner, class_loader)
visitor.accept(yaml_tree)
end
end
# Initializing class ivars
clear_options
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/pending_cops_reporter.rb | lib/rubocop/pending_cops_reporter.rb | # frozen_string_literal: true
module RuboCop
# Reports information about pending cops that are not explicitly configured.
#
# This class is responsible for displaying warnings when new cops have been added to RuboCop
# but have not yet been enabled or disabled in the user's configuration.
# It provides a centralized way to determine whether such warnings should be shown,
# based on global flags or configuration settings.
class PendingCopsReporter
class << self
PENDING_BANNER = <<~BANNER
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file.
Please also note that you can opt-in to new cops by default by adding this to your config:
AllCops:
NewCops: enable
BANNER
attr_accessor :disable_pending_cops, :enable_pending_cops
def warn_if_needed(config)
return if possible_new_cops?(config)
pending_cops = pending_cops_only_qualified(config.pending_cops)
warn_on_pending_cops(pending_cops) unless pending_cops.empty?
end
private
def pending_cops_only_qualified(pending_cops)
pending_cops.select { |cop| Cop::Registry.qualified_cop?(cop.name) }
end
def possible_new_cops?(config)
disable_pending_cops || enable_pending_cops ||
config.disabled_new_cops? || config.enabled_new_cops?
end
def warn_on_pending_cops(pending_cops)
warn Rainbow(PENDING_BANNER).yellow
pending_cops.each { |cop| warn_pending_cop cop }
warn Rainbow('For more information: https://docs.rubocop.org/rubocop/versioning.html').yellow
end
def warn_pending_cop(cop)
version = cop.metadata['VersionAdded'] || 'N/A'
warn Rainbow("#{cop.name}: # new in #{version}").yellow
warn Rainbow(' Enabled: true').yellow
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/path_util.rb | lib/rubocop/path_util.rb | # frozen_string_literal: true
module RuboCop
# Common methods and behaviors for dealing with paths.
module PathUtil
class << self
attr_accessor :relative_paths_cache
end
self.relative_paths_cache = Hash.new { |hash, key| hash[key] = {} }
module_function
def relative_path(path, base_dir = Dir.pwd)
PathUtil.relative_paths_cache[base_dir][path] ||=
# Optimization for the common case where path begins with the base
# dir. Just cut off the first part.
if path.start_with?(base_dir)
base_dir_length = base_dir.length
result_length = path.length - base_dir_length - 1
path[base_dir_length + 1, result_length]
else
path_name = Pathname.new(File.expand_path(path))
begin
path_name.relative_path_from(Pathname.new(base_dir)).to_s
rescue ArgumentError
path
end
end
end
def remote_file?(uri)
uri.start_with?('http://', 'https://')
end
SMART_PATH_CACHE = {} # rubocop:disable Style/MutableConstant
private_constant :SMART_PATH_CACHE
def smart_path(path)
SMART_PATH_CACHE[path] ||=
if path.is_a?(RemoteConfig)
path.uri.to_s
else
# Ideally, we calculate this relative to the project root.
base_dir = Dir.pwd
if path.start_with? base_dir
relative_path(path, base_dir)
else
path
end
end
end
# rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def match_path?(pattern, path)
case pattern
when String
matches =
if pattern == path
true
elsif glob?(pattern)
# File name matching doesn't really work with relative patterns that start with "..". We
# get around that problem by converting the pattern to an absolute path.
pattern = File.expand_path(pattern) if pattern.start_with?('..')
File.fnmatch?(pattern, path, File::FNM_PATHNAME | File::FNM_EXTGLOB)
end
matches || hidden_file_in_not_hidden_dir?(pattern, path)
when Regexp
begin
pattern.match?(path)
rescue ArgumentError => e
return false if e.message.start_with?('invalid byte sequence')
raise e
end
end
end
# rubocop:enable Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# Returns true for an absolute Unix or Windows path.
def absolute?(path)
%r{\A([A-Z]:)?/}i.match?(path)
end
# Returns true for a glob
def glob?(path)
path.match?(/[*{\[?]/)
end
def hidden_file_in_not_hidden_dir?(pattern, path)
hidden_file?(path) &&
File.fnmatch?(
pattern, path,
File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
) &&
!hidden_dir?(path)
end
def hidden_file?(path)
maybe_hidden_file?(path) && File.basename(path).start_with?('.')
end
HIDDEN_FILE_PATTERN = "#{File::SEPARATOR}."
# Loose check to reduce memory allocations
def maybe_hidden_file?(path)
return false unless path.include?(HIDDEN_FILE_PATTERN)
separator_index = path.rindex(File::SEPARATOR)
return false unless separator_index
dot_index = path.index('.', separator_index + 1)
dot_index == separator_index + 1
end
def hidden_dir?(path)
File.dirname(path).split(File::SEPARATOR).any? { |dir| dir.start_with?('.') }
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.