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/lint/number_conversion_spec.rb
spec/rubocop/cop/lint/number_conversion_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NumberConversion, :config do context 'registers an offense' do it 'when using `#to_i`' do expect_offense(<<~RUBY) "10".to_i ^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `"10".to_i`, use stricter `Integer("10", 10)`. RUBY expect_correction(<<~RUBY) Integer("10", 10) RUBY end it 'when using `&.to_i`' do expect_offense(<<~RUBY) "10"&.to_i ^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `"10".to_i`, use stricter `Integer("10", 10)`. RUBY expect_correction(<<~RUBY) Integer("10", 10) RUBY end it 'when using `#to_f`' do expect_offense(<<~RUBY) "10.2".to_f ^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `"10.2".to_f`, use stricter `Float("10.2")`. RUBY expect_correction(<<~RUBY) Float("10.2") RUBY end it 'when using `#to_c`' do expect_offense(<<~RUBY) "10".to_c ^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `"10".to_c`, use stricter `Complex("10")`. RUBY expect_correction(<<~RUBY) Complex("10") RUBY end it 'when using `#to_r`' do expect_offense(<<~RUBY) "1/3".to_r ^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `"1/3".to_r`, use stricter `Rational("1/3")`. RUBY expect_correction(<<~RUBY) Rational("1/3") RUBY end it 'when using `#to_i` for number literals' do expect_no_offenses(<<~RUBY) 42.to_i 42.0.to_i RUBY end it 'when using `#to_f` for number literals' do expect_no_offenses(<<~RUBY) 42.to_f 42.0.to_f RUBY end it 'when using `#to_c` for number literals' do expect_no_offenses(<<~RUBY) 42.to_c 42.0.to_c RUBY end it 'when using `#to_r` for number literals' do expect_no_offenses(<<~RUBY) 42.to_r 42.0.to_r RUBY end it 'when `#to_i` called on a variable' do expect_offense(<<~RUBY) string_value = '10' string_value.to_i ^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `string_value.to_i`, use stricter `Integer(string_value, 10)`. RUBY expect_correction(<<~RUBY) string_value = '10' Integer(string_value, 10) RUBY end it 'when `#to_i` called on a hash value' do expect_offense(<<~RUBY) params = { id: 10 } params[:id].to_i ^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `params[:id].to_i`, use stricter `Integer(params[:id], 10)`. RUBY expect_correction(<<~RUBY) params = { id: 10 } Integer(params[:id], 10) RUBY end it 'when `#to_i` called on a variable on an array' do expect_offense(<<~RUBY) args = [1,2,3] args[0].to_i ^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `args[0].to_i`, use stricter `Integer(args[0], 10)`. RUBY expect_correction(<<~RUBY) args = [1,2,3] Integer(args[0], 10) RUBY end it 'when `#to_i` called on a variable on a hash' do expect_offense(<<~RUBY) params[:field].to_i ^^^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `params[:field].to_i`, use stricter `Integer(params[:field], 10)`. RUBY expect_correction(<<~RUBY) Integer(params[:field], 10) RUBY end end context 'does not register an offense' do it 'when using Integer() with integer' do expect_no_offenses(<<~RUBY) Integer(10) RUBY end it 'when using Float()' do expect_no_offenses(<<~RUBY) Float('10') RUBY end it 'when using Complex()' do expect_no_offenses(<<~RUBY) Complex('10') RUBY end it 'when `#to_i` called without a receiver' do expect_no_offenses(<<~RUBY) to_i RUBY end it 'when `:to_f` is one of multiple method arguments' do expect_no_offenses(<<~RUBY) delegate :to_f, to: :description, allow_nil: true RUBY end end context 'to_method in symbol form' do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY) "1,2,3,foo,5,6,7,8".split(',').map(&:to_i) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `&:to_i`, use stricter `{ |i| Integer(i, 10) }`. RUBY expect_correction(<<~RUBY) "1,2,3,foo,5,6,7,8".split(',').map { |i| Integer(i, 10) } RUBY end it 'registers an offense and autocorrects when using safe navigation operator' do expect_offense(<<~RUBY) "1,2,3,foo,5,6,7,8".split(',')&.map(&:to_i) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `&:to_i`, use stricter `{ |i| Integer(i, 10) }`. RUBY expect_correction(<<~RUBY) "1,2,3,foo,5,6,7,8".split(',')&.map { |i| Integer(i, 10) } RUBY end it 'registers an offense and autocorrects without parentheses' do expect_offense(<<~RUBY) "1,2,3,foo,5,6,7,8".split(',').map &:to_i ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `&:to_i`, use stricter `{ |i| Integer(i, 10) }`. RUBY expect_correction(<<~RUBY) "1,2,3,foo,5,6,7,8".split(',').map { |i| Integer(i, 10) } RUBY end it 'registers an offense with try' do expect_offense(<<~RUBY) "foo".try(:to_f) ^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `:to_f`, use stricter `{ |i| Float(i) }`. RUBY expect_correction(<<~RUBY) "foo".try { |i| Float(i) } RUBY end it 'registers an offense with `&.try`' do expect_offense(<<~RUBY) "foo"&.try(:to_f) ^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `:to_f`, use stricter `{ |i| Float(i) }`. RUBY expect_correction(<<~RUBY) "foo"&.try { |i| Float(i) } RUBY end it 'registers an offense when using nested number conversion methods' do expect_offense(<<~RUBY) var.to_i.to_f ^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `var.to_i`, use stricter `Integer(var, 10)`. RUBY expect_correction(<<~RUBY) Integer(var, 10).to_f RUBY end it 'registers an offense when using multiple number conversion methods' do expect_offense(<<~RUBY) case foo.to_f ^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `foo.to_f`, use stricter `Float(foo)`. ^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `case foo.to_f[...] when 0.0 bar else baz end.to_i RUBY expect_correction(<<~RUBY) Integer(case foo.to_f when 0.0 bar else baz end, 10) RUBY end it 'does not register an offense when using `Integer` constructor' do expect_no_offenses(<<~RUBY) Integer(var, 10).to_f RUBY end it 'does not register an offense when using `Float` constructor' do expect_no_offenses(<<~RUBY) Float(var).to_i RUBY end it 'does not register an offense when using `Complex` constructor' do expect_no_offenses(<<~RUBY) Complex(var).to_f RUBY end it 'registers an offense with send' do expect_offense(<<~RUBY) "foo".send(:to_c) ^^^^^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `:to_c`, use stricter `{ |i| Complex(i) }`. RUBY expect_correction(<<~RUBY) "foo".send { |i| Complex(i) } RUBY end end context 'IgnoredClasses' do let(:cop_config) { { 'IgnoredClasses' => %w[Time DateTime] } } it 'when using Time' do expect_no_offenses(<<~RUBY) Time.now.to_i Time.now.to_f Time.strptime("2000-10-31", "%Y-%m-%d").to_i Time.httpdate("Thu, 06 Oct 2011 02:26:12 GMT").to_f Time.now.to_datetime.to_i RUBY end it 'when using DateTime' do expect_no_offenses(<<~RUBY) DateTime.new(2012, 8, 29, 22, 35, 0).to_i DateTime.new(2012, 8, 29, 22, 35, 0).to_f RUBY end it 'when using Time/DateTime with multiple method calls' do expect_no_offenses(<<~RUBY) Time.now.to_datetime.to_i DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc.to_f Time.zone.now.to_datetime.to_f DateTime.new(2012, 8, 29, 22, 35, 0) .change(day: 1) .change(month: 1) .change(year: 2020) .to_i RUBY end end context 'AllowedMethods' do let(:cop_config) { { 'AllowedMethods' => %w[minutes] } } it 'does not register an offense for an allowed method' do expect_no_offenses(<<~RUBY) 10.minutes.to_i RUBY end it 'registers an offense for other methods' do expect_offense(<<~RUBY) 10.hours.to_i ^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `10.hours.to_i`, use stricter `Integer(10.hours, 10)`. RUBY end end context 'AllowedPatterns' do let(:cop_config) { { 'AllowedPatterns' => [/min/] } } it 'does not register an offense for an allowed method' do expect_no_offenses(<<~RUBY) 10.minutes.to_i RUBY end it 'registers an offense for other methods' do expect_offense(<<~RUBY) 10.hours.to_i ^^^^^^^^^^^^^ Replace unsafe number conversion with number class parsing, instead of using `10.hours.to_i`, use stricter `Integer(10.hours, 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/lint/useless_method_definition_spec.rb
spec/rubocop/cop/lint/useless_method_definition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessMethodDefinition, :config do it 'does not register an offense for empty constructor' do expect_no_offenses(<<~RUBY) class Foo def initialize(arg1, arg2) end end RUBY end it 'does not register an offense for constructor with only comments' do expect_no_offenses(<<~RUBY) def initialize(arg) # Comment. end RUBY end it 'does not register an offense for constructor containing additional code to `super`' do expect_no_offenses(<<~RUBY) def initialize(arg) super do_something end RUBY end it 'does not register an offense for empty class level `initialize` method' do expect_no_offenses(<<~RUBY) def self.initialize end RUBY end it 'registers an offense and corrects for method containing only `super` call' do expect_offense(<<~RUBY) class Foo def useful_instance_method do_something end def instance_method ^^^^^^^^^^^^^^^^^^^ Useless method definition detected. super end def instance_method_with_args(arg) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless method definition detected. super(arg) end def self.useful_class_method do_something end def self.class_method ^^^^^^^^^^^^^^^^^^^^^ Useless method definition detected. super end def self.class_method_with_args(arg) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless method definition detected. super(arg) end class << self def self.other_useful_class_method do_something end def other_class_method ^^^^^^^^^^^^^^^^^^^^^^ Useless method definition detected. super end def other_class_method_with_parens ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless method definition detected. super() end def other_class_method_with_args(arg) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless method definition detected. super(arg) end end end RUBY expect_correction(<<~RUBY) class Foo def useful_instance_method do_something end #{trailing_whitespace} #{trailing_whitespace} def self.useful_class_method do_something end #{trailing_whitespace} #{trailing_whitespace} class << self def self.other_useful_class_method do_something end #{trailing_whitespace} #{trailing_whitespace} #{trailing_whitespace} end end RUBY end it 'registers an offense and corrects when method definition with `public` access modifier containing only `super` call' do expect_offense(<<~RUBY) public def method ^^^^^^^^^^ Useless method definition detected. super end RUBY expect_correction("\n") end it 'registers an offense and corrects when method definition with `protected` access modifier containing only `super` call' do expect_offense(<<~RUBY) protected def method ^^^^^^^^^^ Useless method definition detected. super end RUBY expect_correction("\n") end it 'registers an offense and corrects when method definition with `private` access modifier containing only `super` call' do expect_offense(<<~RUBY) private def method ^^^^^^^^^^ Useless method definition detected. super end RUBY expect_correction("\n") end it 'registers an offense and corrects when method definition with `module_function` access modifier containing only `super` call' do expect_offense(<<~RUBY) module_function def method ^^^^^^^^^^ Useless method definition detected. super end RUBY expect_correction("\n") end it 'does not register an offense for method containing additional code to `super`' do expect_no_offenses(<<~RUBY) def method super do_something end RUBY end it 'does not register an offense when `super` arguments differ from method arguments' do expect_no_offenses(<<~RUBY) def method1(foo) super(bar) end def method2(foo, bar) super(bar, foo) end def method3(foo, bar) super() end RUBY end it 'does not register an offense when method definition contains rest arguments' do expect_no_offenses(<<~RUBY) def method(*args) super end RUBY end it 'does not register an offense when method definition contains optional argument' do expect_no_offenses(<<~RUBY) def method(x = 1) super end RUBY end it 'does not register an offense when method definition contains optional keyword argument' do expect_no_offenses(<<~RUBY) def method(x: 1) super end RUBY end it 'does not register an offense when method definition with generic method macro containing only `super` call' do expect_no_offenses(<<~RUBY) do_something def method super end RUBY end it 'does not register an offense when non-constructor contains only comments' do expect_no_offenses(<<~RUBY) def non_constructor # Comment. 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/lint/redundant_cop_enable_directive_spec.rb
spec/rubocop/cop/lint/redundant_cop_enable_directive_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantCopEnableDirective, :config do describe 'when cop is disabled in the configuration' do let(:other_cops) { { 'Layout/LineLength' => { 'Enabled' => false } } } it 'registers no offense when enabling the cop' do expect_no_offenses(<<~RUBY) foo # rubocop:enable Layout/LineLength RUBY end it 'registers an offense if enabling it twice' do expect_offense(<<~RUBY) foo # rubocop:enable Layout/LineLength # rubocop:enable Layout/LineLength ^^^^^^^^^^^^^^^^^ Unnecessary enabling of Layout/LineLength. RUBY end end it 'registers an offense and corrects unnecessary enable' do expect_offense(<<~RUBY) foo # rubocop:enable Layout/LineLength ^^^^^^^^^^^^^^^^^ Unnecessary enabling of Layout/LineLength. RUBY expect_correction(<<~RUBY) foo RUBY end it 'registers an offense and corrects when the first cop is unnecessarily enabled' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Metrics/AbcSize, Layout/LineLength ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Layout/LineLength RUBY end it 'registers multiple offenses and corrects the same comment' do expect_offense(<<~RUBY) foo # rubocop:enable Metrics/ModuleLength, Metrics/AbcSize ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. ^^^^^^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/ModuleLength. bar RUBY expect_correction(<<~RUBY) foo bar RUBY end it 'registers correct offense when combined with necessary enable' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Metrics/AbcSize, Layout/LineLength ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. bar RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout/LineLength bar RUBY end it 'registers correct offense when combined with necessary enable, no white-space after comma' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Metrics/AbcSize,Layout/LineLength ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. bar RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout/LineLength bar RUBY end it 'registers an offense and corrects redundant enabling of same cop' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout/LineLength bar # rubocop:enable Layout/LineLength ^^^^^^^^^^^^^^^^^ Unnecessary enabling of Layout/LineLength. bar RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout/LineLength bar bar RUBY end context 'all switch' do it 'registers an offense and corrects unnecessary enable all' do expect_offense(<<~RUBY) foo # rubocop:enable all ^^^ Unnecessary enabling of all cops. RUBY expect_correction(<<~RUBY) foo RUBY end context 'when at least one cop was disabled' do it 'does not register offense' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout/LineLength foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo # rubocop:enable all RUBY end end end context 'when last cop is unnecessarily enabled' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Layout/LineLength, Metrics/AbcSize ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Layout/LineLength RUBY end it 'registers an offense and corrects when there is no space between the cops and the comma' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Layout/LineLength,Metrics/AbcSize ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Layout/LineLength RUBY end end context 'when middle cop is unnecessarily enabled' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength, Lint/Debugger foo # rubocop:enable Layout/LineLength, Metrics/AbcSize, Lint/Debugger ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength, Lint/Debugger foo # rubocop:enable Layout/LineLength, Lint/Debugger RUBY end it 'registers an offense and corrects when there is extra white space' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength, Lint/Debugger foo # rubocop:enable Layout/LineLength, Metrics/AbcSize, Lint/Debugger ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength, Lint/Debugger foo # rubocop:enable Layout/LineLength, Lint/Debugger RUBY end end context 'when all cops are unnecessarily enabled' do context 'on the same line' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo # rubocop:enable Layout/LineLength, Metrics/AbcSize, Lint/Debugger ^^^^^^^^^^^^^ Unnecessary enabling of Lint/Debugger. ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. ^^^^^^^^^^^^^^^^^ Unnecessary enabling of Layout/LineLength. RUBY expect_correction(<<~RUBY) foo RUBY end end context 'on separate lines' do it 'registers an offense and corrects when there is extra white space' do expect_offense(<<~RUBY) foo # rubocop:enable Metrics/ModuleSize ^^^^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/ModuleSize. # rubocop:enable Layout/LineLength, Metrics/ClassSize ^^^^^^^^^^^^^^^^^ Unnecessary enabling of Layout/LineLength. ^^^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/ClassSize. # rubocop:enable Metrics/AbcSize, Lint/Debugger ^^^^^^^^^^^^^ Unnecessary enabling of Lint/Debugger. ^^^^^^^^^^^^^^^ Unnecessary enabling of Metrics/AbcSize. RUBY expect_correction(<<~RUBY) foo RUBY end end end context 'when all department enabled' do it 'registers an offense and corrects unnecessary enable' do expect_offense(<<~RUBY) foo # rubocop:enable Layout ^^^^^^ Unnecessary enabling of Layout. RUBY expect_correction(<<~RUBY) foo RUBY end it 'registers an offense and corrects when the first department is unnecessarily enabled' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Metrics, Layout/LineLength ^^^^^^^ Unnecessary enabling of Metrics. RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength foo # rubocop:enable Layout/LineLength RUBY end it 'registers multiple offenses and corrects the same comment' do expect_offense(<<~RUBY) foo # rubocop:enable Metrics, Layout ^^^^^^ Unnecessary enabling of Layout. ^^^^^^^ Unnecessary enabling of Metrics. bar RUBY expect_correction(<<~RUBY) foo bar RUBY end it 'registers correct offense when combined with necessary enable' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Metrics, Layout/LineLength ^^^^^^^ Unnecessary enabling of Metrics. bar RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout/LineLength bar RUBY end it 'registers an offense and corrects redundant enabling of same department' do expect_offense(<<~RUBY) # rubocop:disable Layout fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout bar # rubocop:enable Layout ^^^^^^ Unnecessary enabling of Layout. bar RUBY expect_correction(<<~RUBY) # rubocop:disable Layout fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout bar bar RUBY end it 'registers an offense and corrects redundant enabling of cop of same department' do expect_offense(<<~RUBY) # rubocop:disable Layout fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout, Layout/LineLength ^^^^^^^^^^^^^^^^^ Unnecessary enabling of Layout/LineLength. RUBY expect_correction(<<~RUBY) # rubocop:disable Layout fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout RUBY end it 'registers an offense and corrects redundant enabling of department of same cop' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr # rubocop:enable Layout ^^^^^^ Unnecessary enabling of Layout. some_code RUBY expect_correction(<<~RUBY) # rubocop:disable Layout/LineLength fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo = barrrrrrrrrrrrrrrrrrrrrrrrrr some_code 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/lint/shared_mutable_default_spec.rb
spec/rubocop/cop/lint/shared_mutable_default_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SharedMutableDefault, :config do context 'when line is unrelated' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) [] {} Array.new Hash.new Hash.new { |h, k| h[k] = [] } Hash.new { |h, k| h[k] = {} } Hash.new { 0 } Hash.new { Array.new } Hash.new { Hash.new } Hash.new { {} } Hash.new { [] } Hash.new(0) Hash.new(false) Hash.new(true) Hash.new(nil) Hash.new(BigDecimal(0)) Hash.new(BigDecimal(0.0)) Hash.new(0.0) Hash.new(0.0.to_d) RUBY end end context 'when default literal is frozen' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Hash.new([].freeze) Hash.new({}.freeze) Hash.new(Array.new.freeze) Hash.new(Hash.new.freeze) RUBY end end context 'when `capacity` keyword argument is used' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Hash.new(capacity: 42) RUBY end end context 'when Hash is initialized with an array' do it 'registers an offense' do expect_offense(<<~RUBY) Hash.new([]) ^^^^^^^^^^^^ Do not create a Hash with a mutable default value [...] Hash.new Array.new ^^^^^^^^^^^^^^^^^^ Do not create a Hash with a mutable default value [...] RUBY end end context 'when Hash is initialized with a hash' do it 'registers an offense' do expect_offense(<<~RUBY) Hash.new({}) ^^^^^^^^^^^^ Do not create a Hash with a mutable default value [...] Hash.new(Hash.new) ^^^^^^^^^^^^^^^^^^ Do not create a Hash with a mutable default value [...] RUBY end end context 'when Hash is initialized with a Hash and `capacity` keyword argument' do it 'registers an offense' do expect_offense(<<~RUBY) Hash.new({}, capacity: 42) ^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not create a Hash with a mutable default value [...] 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/lint/numeric_operation_with_constant_result_spec.rb
spec/rubocop/cop/lint/numeric_operation_with_constant_result_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NumericOperationWithConstantResult, :config do it 'registers an offense when a variable is multiplied by 0' do expect_offense(<<~RUBY) x * 0 ^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) 0 RUBY end it 'registers an offense when a variable is divided by itself' do expect_offense(<<~RUBY) x / x ^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) 1 RUBY end it 'registers an offense when a variable is raised to the power of 0' do expect_offense(<<~RUBY) x ** 0 ^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) 1 RUBY end it 'registers an offense when a variable is multiplied by 0 via abbreviated assignment' do expect_offense(<<~RUBY) x *= 0 ^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) x = 0 RUBY end it 'registers an offense when a variable is divided by itself via abbreviated assignment' do expect_offense(<<~RUBY) x /= x ^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) x = 1 RUBY end it 'registers an offense when a variable is raised to the power of 0 via abbreviated assignment' do expect_offense(<<~RUBY) x **= 0 ^^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) x = 1 RUBY end [ 'x - x', 'x -= x', 'x % x', 'x %= x', 'x % 1', 'x %= 1' ].each do |expression| it "registers no offense for `#{expression}`" do expect_no_offenses(expression) end end it 'registers an offense when a variable is multiplied by 0 using dot notation' do expect_offense(<<~RUBY) x.*(0) ^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) 0 RUBY end it 'registers an offense when a variable is divided by using dot notation' do expect_offense(<<~RUBY) x./(x) ^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) 1 RUBY end it 'registers an offense when a variable is multiplied by 0 using safe navigation' do expect_offense(<<~RUBY) x&.*(0) ^^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) 0 RUBY end it 'registers an offense when a variable is divided by using safe navigation' do expect_offense(<<~RUBY) x&./(x) ^^^^^^^ Numeric operation with a constant result detected. RUBY expect_correction(<<~RUBY) 1 RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/shadowed_argument_spec.rb
spec/rubocop/cop/lint/shadowed_argument_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ShadowedArgument, :config do let(:cop_config) { { 'IgnoreImplicitReferences' => false } } describe 'method argument shadowing' do context 'when a single argument is shadowed' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(foo) foo = 42 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. puts foo end RUBY end context 'when zsuper is used' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(foo) foo = 42 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. super end RUBY end context 'when argument was shadowed by zsuper' do it 'registers an offense' do expect_offense(<<~RUBY) def select_fields(query, current_time) query = super ^^^^^^^^^^^^^ Argument `query` was shadowed by a local variable before it was used. query.select('*') end RUBY end end context 'when IgnoreImplicitReferences config option is set to true' do let(:cop_config) { { 'IgnoreImplicitReferences' => true } } it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) foo = 42 super end RUBY end context 'when argument was shadowed by zsuper' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def select_fields(query, current_time) query = super query.select('*') end RUBY end end end end context 'when argument was used in shorthand assignment' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def do_something(bar) bar = 'baz' if foo bar ||= {} end RUBY end end context 'when a splat argument is shadowed' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(*items) *items, last = [42, 42] ^^^^^ Argument `items` was shadowed by a local variable before it was used. puts items end RUBY end end context 'when reassigning to splat variable' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def do_something(*items) *items, last = items puts items end RUBY end end context 'when self assigning to a block argument in `for`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) for item in items do_something { |arg| arg = arg } end RUBY end end context 'when binding is used' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(foo) foo = 42 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. binding end RUBY end context 'when IgnoreImplicitReferences config option is set to true' do let(:cop_config) { { 'IgnoreImplicitReferences' => true } } it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) foo = 42 binding end RUBY end end end context 'and the argument is not used' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) puts 'done something' end RUBY end end context 'and shadowed within a conditional' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) def do_something(foo) ^^^ Argument `foo` was shadowed by a local variable before it was used. if bar foo = 43 end foo = 42 puts foo end RUBY end context 'and was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) if bar puts foo foo = 43 end foo = 42 puts foo end RUBY end end context 'and the argument was not shadowed outside the conditional' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) if bar foo = 42 end puts foo end RUBY end end context 'and the conditional occurs after the reassignment' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(foo) foo = 43 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. if bar foo = 42 end puts foo end RUBY end end context 'and the conditional is nested within a conditional' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) def do_something(foo) ^^^ Argument `foo` was shadowed by a local variable before it was used. if bar if baz foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) if bar puts foo if baz foo = 43 end end foo = 42 puts foo end RUBY end end end context 'and the conditional is nested within a lambda' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) def do_something(foo) ^^^ Argument `foo` was shadowed by a local variable before it was used. lambda do if baz foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) lambda do puts foo if baz foo = 43 end end foo = 42 puts foo end RUBY end end end end context 'and shadowed within a block' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) def do_something(foo) ^^^ Argument `foo` was shadowed by a local variable before it was used. something { foo = 43 } foo = 42 puts foo end RUBY end context 'and was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) lambda do puts foo foo = 43 end foo = 42 puts foo end RUBY end end context 'and the argument was not shadowed outside the block' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) something { foo = 43 } puts foo end RUBY end end context 'and the block occurs after the reassignment' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(foo) foo = 43 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. something { foo = 42 } puts foo end RUBY end end context 'and the block is nested within a block' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) def do_something(foo) ^^^ Argument `foo` was shadowed by a local variable before it was used. something do lambda do foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) lambda do puts foo something do foo = 43 end end foo = 42 puts foo end RUBY end end end context 'and the block is nested within a conditional' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) def do_something(foo) ^^^ Argument `foo` was shadowed by a local variable before it was used. if baz lambda do foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) def do_something(foo) if baz puts foo lambda do foo = 43 end end foo = 42 puts foo end RUBY end end end end context 'and shadowed within `rescue`' do context 'and assigned before the `rescue`' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(foo) foo = bar ^^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. begin rescue foo = baz end puts foo end RUBY end end context 'and the argument was not shadowed outside the `rescue`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) def do_something(foo) begin rescue foo = bar end puts foo end RUBY end end end end context 'when multiple arguments are shadowed' do context 'and one of them shadowed within a lambda while another is shadowed outside' do it 'registers an offense' do expect_offense(<<~RUBY) def do_something(foo, bar) lambda do bar = 42 end foo = 43 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. puts(foo, bar) end RUBY end end end end describe 'block argument shadowing' do context 'when a block local variable is assigned but no argument is shadowed' do it 'accepts' do expect_no_offenses(<<~RUBY) numbers = [1, 2, 3] numbers.each do |i; j| j = i * 2 puts j end RUBY end end context 'when a single argument is shadowed' do it 'registers an offense' do expect_offense(<<~RUBY) do_something do |foo| foo = 42 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. puts foo end RUBY end context 'when zsuper is used' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| foo = 42 super end RUBY end end context 'when binding is used' do it 'registers an offense' do expect_offense(<<~RUBY) do_something do |foo| foo = 42 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. binding end RUBY end context 'when IgnoreImplicitReferences config option is set to true' do let(:cop_config) { { 'IgnoreImplicitReferences' => true } } it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| foo = 42 binding end RUBY end end end context 'and the argument is not used' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| puts 'done something' end RUBY end end context 'and shadowed within a conditional' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) do_something do |foo| ^^^ Argument `foo` was shadowed by a local variable before it was used. if bar foo = 43 end foo = 42 puts foo end RUBY end context 'and was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| if bar puts foo foo = 43 end foo = 42 puts foo end RUBY end end context 'and the argument was not shadowed outside the conditional' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| if bar foo = 42 end puts foo end RUBY end end context 'and the conditional occurs after the reassignment' do it 'registers an offense' do expect_offense(<<~RUBY) do_something do |foo| foo = 43 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. if bar foo = 42 end puts foo end RUBY end end context 'and the conditional is nested within a conditional' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) do_something do |foo| ^^^ Argument `foo` was shadowed by a local variable before it was used. if bar if baz foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| if bar puts foo if baz foo = 43 end end foo = 42 puts foo end RUBY end end end context 'and the conditional is nested within a lambda' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) do_something do |foo| ^^^ Argument `foo` was shadowed by a local variable before it was used. lambda do if baz foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| lambda do puts foo if baz foo = 43 end end foo = 42 puts foo end RUBY end end end end context 'and shadowed within a block' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) do_something do |foo| ^^^ Argument `foo` was shadowed by a local variable before it was used. something { foo = 43 } foo = 42 puts foo end RUBY end context 'and was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| lambda do puts foo foo = 43 end foo = 42 puts foo end RUBY end end context 'and the argument was not shadowed outside the block' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| something { foo = 43 } puts foo end RUBY end end context 'and the block occurs after the reassignment' do it 'registers an offense' do expect_offense(<<~RUBY) do_something do |foo| foo = 43 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. something { foo = 42 } puts foo end RUBY end end context 'and the block is nested within a block' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) do_something do |foo| ^^^ Argument `foo` was shadowed by a local variable before it was used. something do lambda do foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| lambda do puts foo something do foo = 43 end end foo = 42 puts foo end RUBY end end end context 'and the block is nested within a conditional' do it 'registers an offense without specifying where the reassignment took place' do expect_offense(<<~RUBY) do_something do |foo| ^^^ Argument `foo` was shadowed by a local variable before it was used. if baz lambda do foo = 43 end end foo = 42 puts foo end RUBY end context 'and the argument was used before shadowing' do it 'accepts' do expect_no_offenses(<<~RUBY) do_something do |foo| if baz puts foo lambda do foo = 43 end end foo = 42 puts foo end RUBY end end end end end context 'when multiple arguments are shadowed' do context 'and one of them shadowed within a lambda while another is shadowed outside' do it 'registers an offense' do expect_offense(<<~RUBY) do_something do |foo, bar| lambda do bar = 42 end foo = 43 ^^^^^^^^ Argument `foo` was shadowed by a local variable before it was used. puts(foo, bar) 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/lint/identity_comparison_spec.rb
spec/rubocop/cop/lint/identity_comparison_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::IdentityComparison, :config do it 'registers an offense and corrects when using `==` for comparison between `object_id`s' do expect_offense(<<~RUBY) foo.object_id == bar.object_id ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `equal?` instead of `==` when comparing `object_id`. RUBY expect_correction(<<~RUBY) foo.equal?(bar) RUBY end it 'registers an offense and corrects when using `!=` for comparison between `object_id`s' do expect_offense(<<~RUBY) foo.object_id != bar.object_id ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!equal?` instead of `!=` when comparing `object_id`. RUBY expect_correction(<<~RUBY) !foo.equal?(bar) RUBY end it 'does not register an offense when using `==` for comparison between `object_id` and other' do expect_no_offenses(<<~RUBY) foo.object_id == bar.do_something RUBY end it 'does not register an offense when using `!=` for comparison between `object_id` and other' do expect_no_offenses(<<~RUBY) foo.object_id != bar.do_something RUBY end it 'does not register an offense when a receiver that is not `object_id` uses `==`' do expect_no_offenses(<<~RUBY) foo.do_something == bar.object_id RUBY end it 'does not register an offense when a receiver that is not `object_id` uses `!=`' do expect_no_offenses(<<~RUBY) foo.do_something != bar.object_id RUBY end it 'does not register an offense when using `equal?`' do expect_no_offenses(<<~RUBY) foo.equal?(bar) RUBY end it 'does not register an offense when using `!equal?`' do expect_no_offenses(<<~RUBY) !foo.equal?(bar) RUBY end it 'does not register an offense when lhs is `object_id` without receiver when using `==`' do expect_no_offenses(<<~RUBY) object_id == bar.object_id RUBY end it 'does not register an offense when lhs is `object_id` without receiver when using `!=`' do expect_no_offenses(<<~RUBY) object_id != bar.object_id RUBY end it 'does not register an offense when rhs is `object_id` without receiver when using `==`' do expect_no_offenses(<<~RUBY) foo.object_id == object_id RUBY end it 'does not register an offense when rhs is `object_id` without receiver when using `!=`' do expect_no_offenses(<<~RUBY) foo.object_id != object_id 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/lint/duplicate_hash_key_spec.rb
spec/rubocop/cop/lint/duplicate_hash_key_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateHashKey, :config do context 'when there is a duplicated key in the hash literal' do it 'registers an offense' do expect_offense(<<~RUBY) hash = { 'otherkey' => 'value', 'key' => 'value', 'key' => 'hi' } ^^^^^ Duplicated key in hash literal. RUBY end end context 'when there is a duplicated constant key in the hash literal' do it 'registers an offense' do expect_offense(<<~RUBY) hash = { 'otherkey' => 'value', KEY => 'value', KEY => 'hi' } ^^^ Duplicated key in hash literal. RUBY end end context 'when there are two duplicated keys in a hash' do it 'registers two offenses' do expect_offense(<<~RUBY) hash = { fruit: 'apple', veg: 'kale', veg: 'cuke', fruit: 'orange' } ^^^ Duplicated key in hash literal. ^^^^^ Duplicated key in hash literal. RUBY end end context 'When a key is duplicated three times in a hash literal' do it 'registers two offenses' do expect_offense(<<~RUBY) hash = { 1 => 2, 1 => 3, 1 => 4 } ^ Duplicated key in hash literal. ^ Duplicated key in hash literal. RUBY end end context 'When there is no duplicated key in the hash' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) hash = { ['one', 'two'] => ['hello, bye'], ['two'] => ['yes, no'] } RUBY end end shared_examples 'duplicated literal key' do |key| it "registers an offense for duplicated `#{key}` hash keys" do expect_offense(<<~RUBY, key: key) hash = { %{key} => 1, %{key} => 4} _{key} ^{key} Duplicated key in hash literal. RUBY end end it_behaves_like 'duplicated literal key', '!true' it_behaves_like 'duplicated literal key', '"#{2}"' it_behaves_like 'duplicated literal key', '(1)' it_behaves_like 'duplicated literal key', '(false && true)' it_behaves_like 'duplicated literal key', '(false <=> true)' it_behaves_like 'duplicated literal key', '(false or true)' it_behaves_like 'duplicated literal key', '[1, 2, 3]' it_behaves_like 'duplicated literal key', '{ :a => 1, :b => 2 }' it_behaves_like 'duplicated literal key', '{ a: 1, b: 2 }' it_behaves_like 'duplicated literal key', '/./' it_behaves_like 'duplicated literal key', '%r{abx}ixo' it_behaves_like 'duplicated literal key', '1.0' it_behaves_like 'duplicated literal key', '1' it_behaves_like 'duplicated literal key', 'false' it_behaves_like 'duplicated literal key', 'nil' it_behaves_like 'duplicated literal key', "'str'" context 'target ruby version >= 2.6', :ruby26 do it_behaves_like 'duplicated literal key', '(42..)' end shared_examples 'duplicated non literal key' do |key| it "does not register an offense for duplicated `#{key}` hash keys" do expect_no_offenses(<<~RUBY) hash = { #{key} => 1, #{key} => 4} RUBY end end it_behaves_like 'duplicated non literal key', '"#{some_method_call}"' it_behaves_like 'duplicated non literal key', '(x && false)' it_behaves_like 'duplicated non literal key', '(x == false)' it_behaves_like 'duplicated non literal key', '(x or false)' it_behaves_like 'duplicated non literal key', '[some_method_call]' it_behaves_like 'duplicated non literal key', '{ :sym => some_method_call }' it_behaves_like 'duplicated non literal key', '{ some_method_call => :sym }' it_behaves_like 'duplicated non literal key', '/.#{some_method_call}/' it_behaves_like 'duplicated non literal key', '%r{abx#{foo}}ixo' it_behaves_like 'duplicated non literal key', 'some_method_call' it_behaves_like 'duplicated non literal key', 'some_method_call(x, y)' end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/each_with_object_argument_spec.rb
spec/rubocop/cop/lint/each_with_object_argument_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EachWithObjectArgument, :config do it 'registers an offense for fixnum argument' do expect_offense(<<~RUBY) collection.each_with_object(0) { |e, a| a + e } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The argument to each_with_object cannot be immutable. RUBY end it 'registers an offense for float argument' do expect_offense(<<~RUBY) collection.each_with_object(0.1) { |e, a| a + e } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The argument to each_with_object cannot be immutable. RUBY end it 'registers an offense for bignum argument' do expect_offense(<<~RUBY) c.each_with_object(100000000000000000000) { |e, o| o + e } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The argument to each_with_object cannot be immutable. RUBY end it 'accepts a variable argument' do expect_no_offenses('collection.each_with_object(x) { |e, a| a.add(e) }') end it 'accepts two arguments' do # Two arguments would indicate that this is not Enumerable#each_with_object. expect_no_offenses('collection.each_with_object(1, 2) { |e, a| a.add(e) }') end it 'accepts a string argument' do expect_no_offenses("collection.each_with_object('') { |e, a| a << e.to_s }") end context 'when using safe navigation operator' do it 'registers an offense for fixnum argument' do expect_offense(<<~RUBY) collection&.each_with_object(0) { |e, a| a + e } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The argument to each_with_object cannot be immutable. 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/lint/non_deterministic_require_order_spec.rb
spec/rubocop/cop/lint/non_deterministic_require_order_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NonDeterministicRequireOrder, :config do context 'when requiring files' do context 'when Ruby 3.0 or higher', :ruby30 do context 'with `Dir[]`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir["./lib/**/*.rb"].each do |file| require file end RUBY end context 'with extra logic' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir["./lib/**/*.rb"].each do |file| if file.start_with?('_') puts "Not required." else require file end end RUBY end end context 'with require block passed as parameter' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir["./lib/**/*.rb"].each(&method(:require)) RUBY end end context 'with top-level ::Dir' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) ::Dir["./lib/**/*.rb"].each do |file| require file end RUBY end end end context 'with `Dir.glob`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), File::FNM_DOTMATCH).each do |file| require file end RUBY end context 'with require block passed as parameter' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb')).each(&method(:require)) RUBY end end context 'with top-level ::Dir' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) ::Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), ::File::FNM_DOTMATCH).each do |file| require file end RUBY end end context 'with `sort: false` keyword option' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb'), sort: false).each(&method(:require)) RUBY end end end context 'with direct block glob' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir.glob("./lib/**/*.rb") do |file| require file end RUBY end context 'with require block passed as parameter' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir.glob( Rails.root.join('./lib/**/*.rb'), File::FNM_DOTMATCH, &method(:require) ) RUBY end end context 'with top-level ::Dir' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) ::Dir.glob("./lib/**/*.rb") do |file| require file end RUBY end end end end context 'when Ruby 2.7 or lower', :ruby27, unsupported_on: :prism do context 'with unsorted index' do it 'registers an offense and autocorrects to add .sort when the block has `require`' do expect_offense(<<~RUBY) Dir["./lib/**/*.rb"].each do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require file end RUBY expect_correction(<<~RUBY) Dir["./lib/**/*.rb"].sort.each do |file| require file end RUBY end it 'registers an offense and autocorrects to add .sort when the numblock has `require`' do expect_offense(<<~RUBY) Dir["./lib/**/*.rb"].each do ^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require _1 end RUBY expect_correction(<<~RUBY) Dir["./lib/**/*.rb"].sort.each do require _1 end RUBY end it 'registers an offense and autocorrects to add .sort when the block has `require_relative`' do expect_offense(<<~RUBY) Dir["./lib/**/*.rb"].each do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require_relative file end RUBY expect_correction(<<~RUBY) Dir["./lib/**/*.rb"].sort.each do |file| require_relative file end RUBY end it 'registers an offense with extra logic' do expect_offense(<<~RUBY) Dir["./lib/**/*.rb"].each do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. if file.start_with?('_') puts "Not required." else require file end end RUBY expect_correction(<<~RUBY) Dir["./lib/**/*.rb"].sort.each do |file| if file.start_with?('_') puts "Not required." else require file end end RUBY end context 'with require block passed as parameter' do it 'registers an offense and autocorrects to add sort' do expect_offense(<<~RUBY) Dir["./lib/**/*.rb"].each(&method(:require)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. RUBY expect_correction(<<~RUBY) Dir["./lib/**/*.rb"].sort.each(&method(:require)) RUBY end end context 'with require_relative block passed as parameter' do it 'registers an offense and autocorrects to add sort' do expect_offense(<<~RUBY) Dir["./lib/**/*.rb"].each(&method(:require_relative)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. RUBY expect_correction(<<~RUBY) Dir["./lib/**/*.rb"].sort.each(&method(:require_relative)) RUBY end end context 'with top-level ::Dir' do it 'registers an offense and corrects to add .sort' do expect_offense(<<~RUBY) ::Dir["./lib/**/*.rb"].each do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require file end RUBY expect_correction(<<~RUBY) ::Dir["./lib/**/*.rb"].sort.each do |file| require file end RUBY end end end context 'with unsorted glob' do it 'registers an offense and autocorrects to add .sort' do expect_offense(<<~RUBY) Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), File::FNM_DOTMATCH).each do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require file end RUBY expect_correction(<<~RUBY) Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), File::FNM_DOTMATCH).sort.each do |file| require file end RUBY end context 'with require block passed as parameter' do it 'registers an offense and autocorrects to add sort' do expect_offense(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb')).each(&method(:require)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. RUBY expect_correction(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb')).sort.each(&method(:require)) RUBY end end context 'with top-level ::Dir' do it 'registers an offense and corrects to add .sort' do expect_offense(<<~RUBY) ::Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), ::File::FNM_DOTMATCH).each do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require file end RUBY expect_correction(<<~RUBY) ::Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), ::File::FNM_DOTMATCH).sort.each do |file| require file end RUBY end end end context 'with direct block glob' do it 'registers an offense and autocorrects to add .sort.each' do expect_offense(<<~RUBY) Dir.glob("./lib/**/*.rb") do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require file end RUBY expect_correction(<<~RUBY) Dir.glob("./lib/**/*.rb").sort.each do |file| require file end RUBY end context 'with require block passed as parameter' do it 'registers an offense and autocorrects to add sort' do expect_offense(<<~RUBY) Dir.glob( ^^^^^^^^^ Sort files before requiring them. Rails.root.join('./lib/**/*.rb'), File::FNM_DOTMATCH, &method(:require) ) RUBY expect_correction(<<~RUBY) Dir.glob( Rails.root.join('./lib/**/*.rb'), File::FNM_DOTMATCH ).sort.each(&method(:require)) RUBY end end context 'with require_relative block passed as parameter' do it 'registers an offense and autocorrects to add sort' do expect_offense(<<~RUBY) Dir.glob( ^^^^^^^^^ Sort files before requiring them. Rails.root.join('./lib/**/*.rb'), File::FNM_DOTMATCH, &method(:require_relative) ) RUBY expect_correction(<<~RUBY) Dir.glob( Rails.root.join('./lib/**/*.rb'), File::FNM_DOTMATCH ).sort.each(&method(:require_relative)) RUBY end end context 'with top-level ::Dir' do it 'registers an offense and corrects to add .sort.each' do expect_offense(<<~RUBY) ::Dir.glob("./lib/**/*.rb") do |file| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sort files before requiring them. require file end RUBY expect_correction(<<~RUBY) ::Dir.glob("./lib/**/*.rb").sort.each do |file| require file end RUBY end end end end context 'with sorted index' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir["./lib/**/*.rb"].sort.each do |file| require file end RUBY end end context 'with sorted glob' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), File::FNM_DOTMATCH).sort.each do |file| require file end RUBY end end end context 'when not requiring files' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Dir["./lib/**/*.rb"].each do |file| puts file 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/lint/constant_overwritten_in_rescue_spec.rb
spec/rubocop/cop/lint/constant_overwritten_in_rescue_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ConstantOverwrittenInRescue, :config do it 'registers an offense when overriding an exception with an exception result' do expect_offense(<<~RUBY) begin something rescue => StandardError ^^ `StandardError` is overwritten by `rescue =>`. end RUBY expect_correction(<<~RUBY) begin something rescue StandardError end RUBY end it 'registers an offense when overriding a fully-qualified constant' do expect_offense(<<~RUBY) begin something rescue => ::StandardError ^^ `::StandardError` is overwritten by `rescue =>`. end RUBY expect_correction(<<~RUBY) begin something rescue ::StandardError end RUBY end it 'registers an offense when overriding a constant with a method call receiver' do expect_offense(<<~RUBY) begin something rescue => foo.class::RESCUABLE_EXCEPTIONS ^^ `foo.class::RESCUABLE_EXCEPTIONS` is overwritten by `rescue =>`. end RUBY expect_correction(<<~RUBY) begin something rescue foo.class::RESCUABLE_EXCEPTIONS end RUBY end it 'registers an offense when overriding a constant with a variable receiver' do expect_offense(<<~RUBY) var = Object begin something rescue => var::StandardError ^^ `var::StandardError` is overwritten by `rescue =>`. end RUBY expect_correction(<<~RUBY) var = Object begin something rescue var::StandardError end RUBY end it 'registers an offense when overriding a nested constant' do expect_offense(<<~RUBY) begin something rescue => MyNamespace::MyException ^^ `MyNamespace::MyException` is overwritten by `rescue =>`. end RUBY expect_correction(<<~RUBY) begin something rescue MyNamespace::MyException end RUBY end it 'registers an offense when overriding a fully qualified nested constant' do expect_offense(<<~RUBY) begin something rescue => ::MyNamespace::MyException ^^ `::MyNamespace::MyException` is overwritten by `rescue =>`. end RUBY expect_correction(<<~RUBY) begin something rescue ::MyNamespace::MyException end RUBY end it 'does not register an offense when not overriding an exception with an exception result' do expect_no_offenses(<<~RUBY) begin something rescue StandardError end RUBY end it 'does not register an offense when using `=>` but correctly assigning to variables' do expect_no_offenses(<<~RUBY) begin something rescue StandardError => e 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/lint/redundant_require_statement_spec.rb
spec/rubocop/cop/lint/redundant_require_statement_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantRequireStatement, :config do it 'registers an offense when using requiring `enumerator`' do expect_offense(<<~RUBY) require 'enumerator' ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' RUBY end it 'registers an offense when using requiring `enumerator` with modifier form' do expect_offense(<<~RUBY) require 'enumerator' if condition ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) if condition end require 'uri' RUBY end it 'registers an offense when using requiring `enumerator` in condition' do expect_offense(<<~RUBY) if condition require 'enumerator' ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. end require 'uri' RUBY expect_correction(<<~RUBY) if condition end require 'uri' RUBY end context 'target ruby version <= 2.0', :ruby20, unsupported_on: :prism do it 'does not register an offense when using requiring `thread`' do expect_no_offenses(<<~RUBY) require 'thread' RUBY end end context 'target ruby version >= 2.1', :ruby21 do it 'registers an offense and corrects when using requiring `thread` or already redundant features' do expect_offense(<<~RUBY) require 'enumerator' ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'thread' ^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' RUBY end end context 'target ruby version <= 2.1', :ruby21, unsupported_on: :prism do it 'does not register an offense when using requiring `rational`, `complex`' do expect_no_offenses(<<~RUBY) require 'rational' require 'complex' RUBY end end context 'target ruby version >= 2.2', :ruby22 do it 'registers an offense when using requiring `rational`, `complex`' do expect_offense(<<~RUBY) require 'enumerator' ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'rational' ^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'complex' ^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'thread' ^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' RUBY end end context 'target ruby version >= 2.5', :ruby25 do it 'registers an offense and corrects when requiring redundant features' do expect_offense(<<~RUBY) require 'enumerator' ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'rational' ^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'complex' ^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'thread' ^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' RUBY end it 'registers no offense when requiring "pp"' do expect_no_offenses(<<~RUBY) require 'pp' # Imagine this code to be in a different file than the require. foo.pretty_inspect RUBY end end context 'target ruby version <= 2.6', :ruby26, unsupported_on: :prism do it 'does not register an offense when using requiring `ruby2_keywords`' do expect_no_offenses(<<~RUBY) require 'ruby2_keywords' RUBY end end context 'target ruby version >= 2.7', :ruby27 do it 'registers an offense when using requiring `ruby2_keywords` or already redundant features' do expect_offense(<<~RUBY) require 'enumerator' ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'rational' ^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'complex' ^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'thread' ^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'ruby2_keywords' ^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' RUBY end end context 'target ruby version < 3.1', :ruby30, unsupported_on: :prism do it 'does not register an offense when using requiring `fiber`' do expect_no_offenses(<<~RUBY) require 'fiber' RUBY end end context 'target ruby version >= 3.1', :ruby31 do it 'registers an offense and corrects when using requiring `fiber` or already redundant features' do expect_offense(<<~RUBY) require 'enumerator' ^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'rational' ^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'complex' ^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'thread' ^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'ruby2_keywords' ^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'fiber' ^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' RUBY end context 'target ruby version >= 3.2', :ruby32 do it 'registers an offense and corrects when using requiring `set`' do expect_offense(<<~RUBY) require 'set' ^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' RUBY end end context 'target ruby version >= 4.0', :ruby40 do it 'registers an offense and corrects when requiring `pathname`' do expect_offense(<<~RUBY) require 'pathname' ^^^^^^^^^^^^^^^^^^ Remove unnecessary `require` statement. require 'uri' RUBY expect_correction(<<~RUBY) require 'uri' 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/lint/percent_string_array_spec.rb
spec/rubocop/cop/lint/percent_string_array_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::PercentStringArray, :config do context 'detecting quotes or commas in a %w/%W string' do %w[w W].each do |char| it 'accepts tokens without quotes or commas' do expect_no_offenses("%#{char}(foo bar baz)") end [ %(%#{char}(' ")), %(%#{char}(' " ! = # ,)), ':"#{a}"', %(%#{char}(\#{a} b)) ].each do |false_positive| it "accepts likely false positive #{false_positive}" do expect_no_offenses(false_positive) end end it 'adds an offense and corrects when tokens contain quotes and are comma separated' do expect_offense(<<~RUBY) %#{char}('foo', 'bar', 'baz') ^^^^^^^^^^^^^^^^^^^^^^^ Within `%w`/`%W`, quotes and ',' are unnecessary and may be unwanted in the resulting strings. RUBY expect_correction(<<~RUBY) %#{char}(foo bar baz) RUBY end it 'adds an offense and corrects when tokens contain both types of quotes' do expect_offense(<<~RUBY) %#{char}('foo' "bar" 'baz') ^^^^^^^^^^^^^^^^^^^^^ Within `%w`/`%W`, quotes and ',' are unnecessary and may be unwanted in the resulting strings. RUBY expect_correction(<<~RUBY) %#{char}(foo bar baz) RUBY end it 'adds an offense and corrects when one token is quoted but there are no commas' do expect_offense(<<~RUBY) %#{char}('foo' bar baz) ^^^^^^^^^^^^^^^^^ Within `%w`/`%W`, quotes and ',' are unnecessary and may be unwanted in the resulting strings. RUBY expect_correction(<<~RUBY) %#{char}(foo bar baz) RUBY end it 'adds an offense and corrects when there are no quotes but one comma' do expect_offense(<<~RUBY) %#{char}(foo, bar baz) ^^^^^^^^^^^^^^^^ Within `%w`/`%W`, quotes and ',' are unnecessary and may be unwanted in the resulting strings. RUBY expect_correction(<<~RUBY) %#{char}(foo bar baz) RUBY end end end context 'with invalid byte sequence in UTF-8' do it 'adds an offense and corrects when tokens contain quotes' do expect_offense(<<~RUBY) %W("a\\255\\255") ^^^^^^^^^^^^^^^ Within `%w`/`%W`, quotes and ',' are unnecessary and may be unwanted in the resulting strings. RUBY expect_correction(<<~RUBY) %W(a\\255\\255) RUBY end it 'accepts if tokens contain invalid byte sequence only' do expect_no_offenses('%W(\255)') end end context 'with binary encoded source' do it 'adds an offense and corrects when tokens contain quotes' do expect_offense(<<~RUBY.b) # encoding: BINARY %W[\xC0 "foo"] ^^^^^^^^^^^ Within `%w`/`%W`, quotes and ',' are unnecessary and may be unwanted in the resulting strings. RUBY expect_correction(<<~RUBY.b) # encoding: BINARY %W[\xC0 foo] RUBY end it 'accepts if tokens contain no quotes' do expect_no_offenses(<<~RUBY.b) # encoding: BINARY %W[\xC0 \xC1] 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/lint/circular_argument_reference_spec.rb
spec/rubocop/cop/lint/circular_argument_reference_spec.rb
# frozen_string_literal: true # Run test with Ruby 3.4 because this cop cannot handle invalid syntax between Ruby 2.7 and 3.3. RSpec.describe RuboCop::Cop::Lint::CircularArgumentReference, :config, :ruby34 do describe 'circular argument references in ordinal arguments' do context 'when the method contains a circular argument reference' do it 'registers an offense' do expect_offense(<<~RUBY) def omg_wow(msg = msg) ^^^ Circular argument reference - `msg`. puts msg end RUBY end end context 'when the method contains a triple circular argument reference' do it 'registers an offense' do expect_offense(<<~RUBY) def omg_wow(msg = msg = msg) ^^^ Circular argument reference - `msg`. puts msg end RUBY end end context 'when the method contains a circular argument reference with intermediate argument' do it 'registers an offense' do expect_offense(<<~RUBY) def omg_wow(msg = foo = msg) ^^^ Circular argument reference - `msg`. puts msg end RUBY end end context 'when the method contains a circular argument reference with two intermediate arguments' do it 'registers an offense' do expect_offense(<<~RUBY) def omg_wow(msg = foo = msg2 = foo) ^^^ Circular argument reference - `msg`. puts msg end RUBY end end context 'when the method does not contain a circular argument among assignments' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def omg_wow(msg = foo = self.msg) puts msg end RUBY end end context 'when the method does not contain a circular argument reference' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def omg_wow(msg) puts msg end RUBY end end context 'when the seemingly-circular default value is a method call' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def omg_wow(msg = self.msg) puts msg end RUBY end end end describe 'circular argument references in keyword arguments' do context 'when the keyword argument is not circular' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method(some_arg: nil) puts some_arg end RUBY end end context 'when the keyword argument is not circular, and calls a method' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method(some_arg: some_method) puts some_arg end RUBY end end context 'when there is one circular argument reference' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(some_arg: some_arg) ^^^^^^^^ Circular argument reference - `some_arg`. puts some_arg end RUBY end end context 'when the keyword argument is not circular, but calls a method ' \ 'of its own class with a self specification' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def puts_value(value: self.class.value, smile: self.smile) puts value end RUBY end end context 'when the keyword argument is not circular, but calls a method ' \ 'of some other object with the same name' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def puts_length(length: mystring.length) puts length end RUBY end end context 'when there are multiple offensive keyword arguments' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(some_arg: some_arg, other_arg: other_arg) ^^^^^^^^ Circular argument reference - `some_arg`. ^^^^^^^^^ Circular argument reference - `other_arg`. puts [some_arg, other_arg] 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/lint/unexpected_block_arity_spec.rb
spec/rubocop/cop/lint/unexpected_block_arity_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnexpectedBlockArity, :config do let(:cop_config) { { 'Methods' => { 'reduce' => 2, 'inject' => 2 } } } context 'with a block' do context 'when given two parameters' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { |a, b| a + b } RUBY end end context 'when given three parameters' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { |a, b, c| a + b } RUBY end end context 'when given a splat parameter' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { |*x| x } RUBY end end context 'when given no parameters' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { } ^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 0. RUBY end end context 'when given one parameter' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { |a| a } ^^^^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 1. RUBY end end context 'with keyword args' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { |a:, b:| a + b } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 0. RUBY end end context 'with a keyword splat' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { |**kwargs| kwargs } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 0. RUBY end end context 'when destructuring' do context 'with arity 1' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { |(a, b)| a + b } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 1. RUBY end end context 'with arity 2' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { |(a, b), c| a + b + c } RUBY end end end context 'with optargs' do context 'with arity 1' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { |a = 1| a } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 1. RUBY end end context 'with arity 2' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { |a = 1, b = 2| a + b } RUBY end end end context 'with shadow args' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { |a; b| a + b } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 1. RUBY end end context 'with no receiver' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) reduce { } RUBY end end end context 'with a numblock', :ruby27 do context 'when given no parameters' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { } ^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 0. RUBY end end context 'when given one parameter' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { _1 } ^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 1. RUBY end end context 'when given two parameters' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { _1 + _2 } RUBY end end context 'when given three parameters' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { _1 + _2 + _3 } RUBY end end context 'when using enough parameters, but not all explicitly' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) values.reduce { _2 } RUBY end end context 'with no receiver' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) reduce { _1 } RUBY end end end context 'with an itblock', :ruby34 do context 'when given one parameter' do it 'registers an offense' do expect_offense(<<~RUBY) values.reduce { it } ^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 1. RUBY end end context 'with no receiver' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) reduce { it } RUBY end end end it 'registers multiple offenses' do expect_offense(<<~RUBY) values.reduce { |a| a } ^^^^^^^^^^^^^^^^^^^^^^^ `reduce` expects at least 2 positional arguments, got 1. values.inject { } ^^^^^^^^^^^^^^^^^ `inject` expects at least 2 positional arguments, got 0. 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/lint/duplicate_rescue_exception_spec.rb
spec/rubocop/cop/lint/duplicate_rescue_exception_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateRescueException, :config do it 'registers an offense when duplicate exception exists' do expect_offense(<<~RUBY) begin something rescue FirstError rescue SecondError, FirstError ^^^^^^^^^^ Duplicate `rescue` exception detected. end RUBY end it 'registers an offense when duplicate exception splat exists' do expect_offense(<<~RUBY) begin something rescue *ERRORS rescue SecondError, *ERRORS ^^^^^^^ Duplicate `rescue` exception detected. end RUBY end it 'registers an offense when multiple duplicate exceptions exist' do expect_offense(<<~RUBY) begin something rescue FirstError rescue SecondError rescue FirstError ^^^^^^^^^^ Duplicate `rescue` exception detected. rescue SecondError ^^^^^^^^^^^ Duplicate `rescue` exception detected. end RUBY end it 'registers an offense when duplicate exception exists within rescues with `else` branch' do expect_offense(<<~RUBY) begin something rescue FirstError rescue SecondError, FirstError ^^^^^^^^^^ Duplicate `rescue` exception detected. else end RUBY end it 'registers an offense when duplicate exception exists within rescues with empty `rescue` branch' do expect_offense(<<~RUBY) begin something rescue FirstError rescue SecondError, FirstError ^^^^^^^^^^ Duplicate `rescue` exception detected. rescue end RUBY end it 'does not register an offense when there are no duplicate exceptions' do expect_no_offenses(<<~RUBY) begin something rescue FirstError rescue SecondError 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/lint/percent_symbol_array_spec.rb
spec/rubocop/cop/lint/percent_symbol_array_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::PercentSymbolArray, :config do context 'detecting colons or commas in a %i/%I string' do %w[i I].each do |char| it 'accepts tokens without colons or commas' do expect_no_offenses("%#{char}(foo bar baz)") end it 'accepts likely false positive $,' do expect_no_offenses("%#{char}{$,}") end it 'registers an offense and corrects when symbols contain colons and are comma separated' do expect_offense(<<~RUBY) %#{char}(:foo, :bar, :baz) ^^^^^^^^^^^^^^^^^^^^ Within `%i`/`%I`, ':' and ',' are unnecessary and may be unwanted in the resulting symbols. RUBY expect_correction(<<~RUBY) %#{char}(foo bar baz) RUBY end it 'registers an offense and corrects when one symbol has a colon but there are no commas' do expect_offense(<<~RUBY) %#{char}(:foo bar baz) ^^^^^^^^^^^^^^^^ Within `%i`/`%I`, ':' and ',' are unnecessary and may be unwanted in the resulting symbols. RUBY expect_correction(<<~RUBY) %#{char}(foo bar baz) RUBY end it 'registers an offense and corrects when there are no colons but one comma' do expect_offense(<<~RUBY) %#{char}(foo, bar baz) ^^^^^^^^^^^^^^^^ Within `%i`/`%I`, ':' and ',' are unnecessary and may be unwanted in the resulting symbols. RUBY expect_correction(<<~RUBY) %#{char}(foo bar baz) RUBY end end context 'with binary encoded source' do it 'registers an offense and corrects when tokens contain quotes' do expect_offense(<<~RUBY.b) # encoding: BINARY %i[\xC0 :foo] ^^^^^^^^^^ Within `%i`/`%I`, ':' and ',' are unnecessary and may be unwanted in the resulting symbols. RUBY expect_correction(<<~RUBY.b) # encoding: BINARY %i[\xC0 foo] RUBY end it 'accepts if tokens contain no quotes' do expect_no_offenses(<<~RUBY.b) # encoding: BINARY %i[\xC0 \xC1] 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/lint/mixed_regexp_capture_types_spec.rb
spec/rubocop/cop/lint/mixed_regexp_capture_types_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::MixedRegexpCaptureTypes, :config do it 'registers an offense when both of named and numbered captures are used' do expect_offense(<<~RUBY) /(?<foo>bar)(baz)/ ^^^^^^^^^^^^^^^^^^ Do not mix named captures and numbered captures in a Regexp literal. RUBY end it 'does not register offense to a regexp with named capture only' do expect_no_offenses(<<~RUBY) /(?<foo>foo?<bar>bar)/ RUBY end it 'does not register offense to a regexp with look behind' do expect_no_offenses(<<~RUBY) /(?<=>)(<br>)(?=><)/ RUBY end it 'does not register offense to a regexp with numbered capture only' do expect_no_offenses(<<~RUBY) /(foo)(bar)/ RUBY end it 'does not register offense to a regexp with named capture and non-capturing group' do expect_no_offenses(<<~RUBY) /(?<foo>bar)(?:bar)/ RUBY end # See https://github.com/rubocop/rubocop/issues/8083 it 'does not register offense when using a Regexp cannot be processed by regexp_parser gem' do expect_no_offenses(<<~RUBY) /data = ({"words":.+}}}[^}]*})/m RUBY end # RuboCop does not know a value of variables that it will contain in the regexp literal. # For example, `/(?<foo>#{var}*)` is interpreted as `/(?<foo>*)`. # So it does not offense when variables are used in regexp literals. context 'when containing a non-regexp literal' do it 'does not register an offense when containing a lvar' do expect_no_offenses(<<~'RUBY') var = '(\d+)' /(?<foo>#{var}*)/ RUBY end it 'does not register an offense when containing an ivar' do expect_no_offenses(<<~'RUBY') /(?<foo>#{@var}*)/ RUBY end it 'does not register an offense when containing a cvar' do expect_no_offenses(<<~'RUBY') /(?<foo>#{@@var}*)/ RUBY end it 'does not register an offense when containing a gvar' do expect_no_offenses(<<~'RUBY') /(?<foo>#{$var}*)/ RUBY end it 'does not register an offense when containing a method' do expect_no_offenses(<<~'RUBY') /(?<foo>#{do_something}*)/ RUBY end it 'does not register an offense when containing a constant' do expect_no_offenses(<<~'RUBY') /(?<foo>#{CONST}*)/ 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/lint/format_parameter_mismatch_spec.rb
spec/rubocop/cop/lint/format_parameter_mismatch_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::FormatParameterMismatch, :config do shared_examples 'variables' do |variable| it 'does not register an offense for % called on a variable' do expect_no_offenses(<<~RUBY) #{variable} = '%s' #{variable} % [foo] RUBY end it 'does not register an offense for format called on a variable' do expect_no_offenses(<<~RUBY) #{variable} = '%s' format(#{variable}, foo) RUBY end it 'does not register an offense for format called on a variable' do expect_no_offenses(<<~RUBY) #{variable} = '%s' sprintf(#{variable}, foo) RUBY end end it_behaves_like 'variables', 'CONST' it_behaves_like 'variables', 'var' it_behaves_like 'variables', '@var' it_behaves_like 'variables', '@@var' it_behaves_like 'variables', '$var' it 'registers an offense when calling Kernel.format and the fields do not match' do expect_offense(<<~RUBY) Kernel.format("%s %s", 1) ^^^^^^ Number of arguments (1) to `format` doesn't match the number of fields (2). RUBY end it 'registers an offense when calling Kernel.sprintf and the fields do not match' do expect_offense(<<~RUBY) Kernel.sprintf("%s %s", 1) ^^^^^^^ Number of arguments (1) to `sprintf` doesn't match the number of fields (2). RUBY end it 'registers an offense when there are less arguments than expected' do expect_offense(<<~RUBY) format("%s %s", 1) ^^^^^^ Number of arguments (1) to `format` doesn't match the number of fields (2). RUBY end it 'registers an offense when there are no expected format string' do expect_offense(<<~RUBY) format("something", 1) ^^^^^^ Number of arguments (1) to `format` doesn't match the number of fields (0). RUBY end it 'registers an offense when there are more arguments than expected' do expect_offense(<<~RUBY) format("%s %s", 1, 2, 3) ^^^^^^ Number of arguments (3) to `format` doesn't match the number of fields (2). RUBY end it 'does not register an offense when arguments and fields match' do expect_no_offenses('format("%s %d %i", 1, 2, 3)') end it 'correctly ignores double percent' do expect_no_offenses("format('%s %s %% %s %%%% %%%%%% %%5B', 1, 2, 3)") end it 'constants do not register offenses' do expect_no_offenses('format(A_CONST, 1, 2, 3)') end it 'registers an offense with sprintf' do expect_offense(<<~RUBY) sprintf("%s %s", 1, 2, 3) ^^^^^^^ Number of arguments (3) to `sprintf` doesn't match the number of fields (2). RUBY end it 'correctly parses different sprintf formats' do expect_no_offenses('sprintf("%020x%+g:% g %%%#20.8x %#.0e", 1, 2, 3, 4, 5)') end it 'registers an offense for String#%' do expect_offense(<<~RUBY) "%s %s" % [1, 2, 3] ^ Number of arguments (3) to `String#%` doesn't match the number of fields (2). RUBY end it 'does not register offense for `String#%` when arguments, fields match' do expect_no_offenses('"%s %s" % [1, 2]') end it 'does not register an offense when single argument is a hash' do expect_no_offenses('puts "%s" % {"a" => 1}') end it 'does not register an offense when single argument is not an array' do expect_no_offenses('puts "%s" % CONST') end context 'when splat argument is present' do it 'does not register an offense when args count is less than expected' do expect_no_offenses('sprintf("%s, %s, %s", 1, *arr)') end context 'when args count is more than expected' do it 'registers an offense for `#%`' do expect_offense(<<~RUBY) puts "%s, %s, %s" % [1, 2, 3, 4, *arr] ^ Number of arguments (5) to `String#%` doesn't match the number of fields (3). RUBY end it 'does not register an offense for `#format`' do expect_no_offenses(<<~RUBY) puts format("%s, %s, %s", 1, 2, 3, 4, *arr) RUBY end it 'does not register an offense for `#sprintf`' do expect_no_offenses(<<~RUBY) puts sprintf("%s, %s, %s", 1, 2, 3, 4, *arr) RUBY end end end context 'when multiple arguments are called for' do context 'and a single variable argument is passed' do it 'does not register an offense' do # the variable could evaluate to an array expect_no_offenses('puts "%s %s" % var') end end context 'and a single send node is passed' do it 'does not register an offense' do expect_no_offenses('puts "%s %s" % ("ab".chars)') end end end context 'when using (digit)$ flag' do it 'does not register an offense' do expect_no_offenses("format('%1$s %2$s', 'foo', 'bar')") end it 'does not register an offense when match between the maximum value ' \ 'specified by (digit)$ flag and the number of arguments' do expect_no_offenses("format('%1$s %1$s', 'foo')") end it 'registers an offense when mismatch between the maximum value ' \ 'specified by (digit)$ flag and the number of arguments' do expect_offense(<<~RUBY) format('%1$s %2$s', 'foo', 'bar', 'baz') ^^^^^^ Number of arguments (3) to `format` doesn't match the number of fields (2). RUBY end end context 'when format is not a string literal' do it 'does not register an offense' do expect_no_offenses('puts str % [1, 2]') end end context 'when format is invalid' do it 'registers an offense' do expect_offense(<<~RUBY) format('%s %2$s', 'foo', 'bar') ^^^^^^ Format string is invalid because formatting sequence types (numbered, named or unnumbered) are mixed. RUBY end end # Regression: https://github.com/rubocop/rubocop/issues/3869 context 'when passed an empty array' do it 'does not register an offense' do expect_no_offenses("'%' % []") end end # Regression: https://github.com/rubocop/rubocop/issues/8115 context 'when argument itself contains format characters and ' \ 'formats in format string and argument are not equal' do it 'ignores argument formatting' do expect_no_offenses(%{format('%<t>s', t: '%d')}) end end it 'ignores percent right next to format string' do expect_no_offenses('format("%0.1f%% percent", 22.5)') end it 'accepts an extra argument for dynamic width' do expect_no_offenses('format("%*d", max_width, id)') end it 'registers an offense if extra argument for dynamic width not given' do expect_offense(<<~RUBY) format("%*d", id) ^^^^^^ Number of arguments (1) to `format` doesn't match the number of fields (2). RUBY end it 'accepts an extra arg for dynamic width with other preceding flags' do expect_no_offenses('format("%0*x", max_width, id)') end it 'does not register an offense argument is the result of a message send' do expect_no_offenses('format("%s", "a b c".gsub(" ", "_"))') end it 'does not register an offense when using named parameters' do expect_no_offenses('"foo %{bar} baz" % { bar: 42 }') end it 'does not register an offense when using named parameters with escaped `%`' do expect_no_offenses('format("%%%<hex>02X", hex: 10)') end it 'identifies correctly digits for spacing in format' do expect_no_offenses('"duration: %10.fms" % 42') end it 'finds faults even when the string looks like a HEREDOC' do # heredocs are ignored at the moment expect_offense(<<~RUBY) format("<< %s bleh", 1, 2) ^^^^^^ Number of arguments (2) to `format` doesn't match the number of fields (1). RUBY end it 'does not register an offense for sprintf with splat argument' do expect_no_offenses('sprintf("%d%d", *test)') end it 'does not register an offense for format with splat argument' do expect_no_offenses('format("%d%d", *test)') end it 'does not register an offense for precision with no number' do expect_no_offenses('format("%.d", 0)') end context 'on format with %{} interpolations' do context 'and 1 argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) params = { y: '2015', m: '01', d: '01' } puts format('%{y}-%{m}-%{d}', params) RUBY end end context 'and multiple arguments' do it 'registers an offense' do expect_offense(<<~RUBY) params = { y: '2015', m: '01', d: '01' } puts format('%{y}-%{m}-%{d}', 2015, 1, 1) ^^^^^^ Number of arguments (3) to `format` doesn't match the number of fields (1). RUBY end end end context 'on format with %<> interpolations' do context 'and 1 argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) params = { y: '2015', m: '01', d: '01' } puts format('%<y>d-%<m>d-%<d>d', params) RUBY end end context 'and multiple arguments' do it 'registers an offense' do expect_offense(<<~RUBY) params = { y: '2015', m: '01', d: '01' } puts format('%<y>d-%<m>d-%<d>d', 2015, 1, 1) ^^^^^^ Number of arguments (3) to `format` doesn't match the number of fields (1). RUBY end end end context 'with wildcard' do it 'does not register an offense for width' do expect_no_offenses('format("%*d", 10, 3)') end it 'does not register an offense for precision' do expect_no_offenses('format("%.*f", 2, 20.19)') end it 'does not register an offense for width and precision' do expect_no_offenses('format("%*.*f", 10, 3, 20.19)') end it 'does not register an offense for multiple wildcards' do expect_no_offenses('format("%*.*f %*.*f", 10, 2, 20.19, 5, 1, 11.22)') end end context 'with interpolated string in format string' do it 'registers an offense when the fields do not match' do expect_offense(<<~'RUBY') format("#{foo} %s %s", "bar") ^^^^^^ Number of arguments (1) to `format` doesn't match the number of fields (2). RUBY end it 'does not register an offense when the fields match' do expect_no_offenses('format("#{foo} %s", "bar")') end it 'does not register an offense when only interpolated string' do expect_no_offenses('format("#{foo}", "bar", "baz")') end it 'does not register an offense when using `Kernel.format` with the interpolated number of decimal places fields match' do expect_no_offenses('Kernel.format("%.#{number_of_decimal_places}f", num)') end it 'registers an offense for String#% when the fields do not match' do expect_offense(<<~'RUBY') "%s %s" % ["#{foo}", 1, 2] ^ Number of arguments (3) to `String#%` doesn't match the number of fields (2). RUBY end it 'does not register an offense for String#% when the fields match' do expect_no_offenses('"%s %s" % ["#{foo}", 1]') end it 'does not register an offense for String#% when only interpolated string' do expect_no_offenses('"#{foo}" % [1, 2]') end it 'does not register an offense when an interpolated width' do expect_no_offenses(<<~'RUBY') format("%#{padding}s: %s", prefix, message) RUBY end it 'does not register an offense with a negative interpolated width' do expect_no_offenses(<<~'RUBY') sprintf("| %-#{key_offset}s | %-#{val_offset}s |", key, value) RUBY end end context 'with interpolated string in argument' do it 'registers an offense when the fields do not match' do expect_offense(<<~'RUBY') format("%s %s", "#{foo}") ^^^^^^ Number of arguments (1) to `format` doesn't match the number of fields (2). RUBY end it 'does not register an offense when the fields match' do expect_no_offenses('format("%s", "#{foo}")') end it 'registers an offense for String#% when the fields do not match' do expect_offense(<<~'RUBY') "#{foo} %s %s" % [1, 2, 3] ^ Number of arguments (3) to `String#%` doesn't match the number of fields (2). RUBY end it 'does not register an offense for String#% when the fields match' do expect_no_offenses('"#{foo} %s %s" % [1, 2]') end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/trailing_comma_in_attribute_declaration_spec.rb
spec/rubocop/cop/lint/trailing_comma_in_attribute_declaration_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::TrailingCommaInAttributeDeclaration, :config do it 'registers an offense when using trailing comma' do expect_offense(<<~RUBY) class Foo attr_reader :bar, ^ Avoid leaving a trailing comma in attribute declarations. def baz puts "Qux" end end RUBY expect_correction(<<~RUBY) class Foo attr_reader :bar def baz puts "Qux" end end RUBY end it 'does not register an offense when not using trailing comma' do expect_no_offenses(<<~RUBY) class Foo attr_reader :bar def baz puts "Qux" 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/lint/unreachable_code_spec.rb
spec/rubocop/cop/lint/unreachable_code_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnreachableCode, :config do def wrap(str) head = <<~RUBY def something array.each do |item| RUBY tail = <<~RUBY end end RUBY body = str.each_line.map { |line| " #{line}" }.join head + body + tail end %w[return next break retry redo throw raise fail exit exit! abort].each do |t| # The syntax using `retry` is not supported in Ruby 3.3 and later. next if t == 'retry' && ENV['PARSER_ENGINE'] == 'parser_prism' it "registers an offense for `#{t}` before other statements" do expect_offense(wrap(<<~RUBY)) #{t} bar ^^^ Unreachable code detected. RUBY end it "registers an offense for `#{t}` in `begin`" do expect_offense(wrap(<<~RUBY)) begin #{t} bar ^^^ Unreachable code detected. end RUBY end it "registers an offense for `#{t}` in all `if` branches" do expect_offense(wrap(<<~RUBY)) if cond #{t} else #{t} end bar ^^^ Unreachable code detected. RUBY end it "registers an offense for `#{t}` in all `if` branches with other expressions" do expect_offense(wrap(<<~RUBY)) if cond something #{t} else something2 #{t} end bar ^^^ Unreachable code detected. RUBY end it "registers an offense for `#{t}` in all `if` and `elsif` branches" do expect_offense(wrap(<<~RUBY)) if cond something #{t} elsif cond2 something2 #{t} else something3 #{t} end bar ^^^ Unreachable code detected. RUBY end it "registers an offense for `#{t}` in all `case` branches" do expect_offense(wrap(<<~RUBY)) case cond when 1 something #{t} when 2 something2 #{t} else something3 #{t} end bar ^^^ Unreachable code detected. RUBY end it "registers an offense for `#{t}` in all `case` pattern branches" do expect_offense(wrap(<<~RUBY)) case cond in 1 something #{t} in 2 something2 #{t} else something3 #{t} end bar ^^^ Unreachable code detected. RUBY end it "accepts code with conditional `#{t}`" do expect_no_offenses(wrap(<<~RUBY)) #{t} if cond bar RUBY end it "accepts `#{t}` as the final expression" do expect_no_offenses(wrap(<<~RUBY)) #{t} if cond RUBY end it "accepts `#{t}` is in all `if` branches" do expect_no_offenses(wrap(<<~RUBY)) if cond #{t} else #{t} end RUBY end it "accepts `#{t}` is in `if` branch only" do expect_no_offenses(wrap(<<~RUBY)) if cond something #{t} else something2 end bar RUBY end it "accepts `#{t}` is in `if`, and without `else`" do expect_no_offenses(wrap(<<~RUBY)) if cond something #{t} end bar RUBY end it "accepts `#{t}` is in `else` branch only" do expect_no_offenses(wrap(<<~RUBY)) if cond something else something2 #{t} end bar RUBY end it "accepts `#{t}` is not in `elsif` branch" do expect_no_offenses(wrap(<<~RUBY)) if cond something #{t} elsif cond2 something2 else something3 #{t} end bar RUBY end it "accepts `#{t}` is in `case` branch without else" do expect_no_offenses(wrap(<<~RUBY)) case cond when 1 something #{t} when 2 something2 #{t} end bar RUBY end it "accepts `#{t}` is in `case` pattern branch without else" do expect_no_offenses(wrap(<<~RUBY)) case cond in 1 something #{t} in 2 something2 #{t} end bar RUBY end # These are keywords and cannot be redefined. next if %w[return next break retry redo].include? t it "registers an offense for `#{t}` after `instance_eval`" do expect_offense <<~RUBY class Dummy def #{t}; end end d = Dummy.new d.instance_eval do #{t} bar end #{t} bar ^^^ Unreachable code detected. RUBY end it "registers an offense for `#{t}` with nested redefinition" do expect_offense <<~RUBY def foo def #{t}; end end #{t} bar ^^^ Unreachable code detected. RUBY end it "accepts `#{t}` if redefined" do expect_no_offenses(wrap(<<~RUBY)) def #{t}; end #{t} bar RUBY end it "accepts `#{t}` if redefined even if it's called recursively" do expect_no_offenses(wrap(<<~RUBY)) def #{t} #{t} bar end #{t} bar RUBY end it "registers an offense for `self.#{t}` with nested redefinition" do expect_offense <<~RUBY def foo def self.#{t}; end end #{t} bar ^^^ Unreachable code detected. RUBY end it "accepts `self.#{t}` if redefined" do expect_no_offenses(wrap(<<~RUBY)) def self.#{t}; end #{t} bar RUBY end it "accepts `self.#{t}` if redefined even if it's called recursively" do expect_no_offenses(wrap(<<~RUBY)) def self.#{t} #{t} bar end #{t} bar RUBY end it "accepts `#{t}` if called in `instance_eval`" do expect_no_offenses <<~RUBY class Dummy def #{t}; end end d = Dummy.new d.instance_eval do #{t} bar end RUBY end it "accepts `#{t}` if called in `instance_eval` with numblock" do expect_no_offenses <<~RUBY class Dummy def #{t}; end end d = Dummy.new d.instance_eval do #{t} _1 end RUBY end it "accepts `#{t}` if called in `instance_eval` with itblock", :ruby34 do expect_no_offenses <<~RUBY class Dummy def #{t}; end end d = Dummy.new d.instance_eval do #{t} it end RUBY end it "accepts `#{t}` if called in nested `instance_eval`" do expect_no_offenses <<~RUBY class Dummy def #{t}; end end d = Dummy.new d.instance_eval do d2 = Dummy.new d2.instance_eval do #{t} bar end end RUBY end it "registers an offense for redefined `#{t}` if it is called on Kernel" do expect_offense <<~RUBY def #{t}; end Kernel.#{t} foo ^^^ Unreachable code detected. RUBY end it "accepts redefined `#{t}` if it is called on a class other than Kernel" do expect_no_offenses <<~RUBY def #{t}; end Dummy.#{t} foo RUBY end it "registers an offense for `#{t}` inside `instance_eval` if it is called on Kernel" do expect_offense <<~RUBY class Dummy def #{t}; end end d = Dummy.new d.instance_eval do Kernel.#{t} foo ^^^ Unreachable code detected. end RUBY end it "accepts `#{t}` inside `instance_eval` if it is called on a class other than Kernel" do expect_no_offenses <<~RUBY class Dummy def #{t}; end end d = Dummy.new d.instance_eval do Dummy.#{t} 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/lint/useless_default_value_argument_spec.rb
spec/rubocop/cop/lint/useless_default_value_argument_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessDefaultValueArgument, :config do context 'with `fetch`' do it 'registers an offense for `x.fetch(key, default_value) { block_value }`' do expect_offense(<<~RUBY) x.fetch(key, default_value) { block_value } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) x.fetch(key) { block_value } RUBY end it 'registers an offense for `x.fetch(key, default_value) { |arg| arg }`' do expect_offense(<<~RUBY) x.fetch(key, default_value) { |arg| arg } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) x.fetch(key) { |arg| arg } RUBY end it 'registers an offense for `x&.fetch(key, default_value) { block_value }`' do expect_offense(<<~RUBY) x&.fetch(key, default_value) { block_value } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) x&.fetch(key) { block_value } RUBY end it 'registers an offense for `x&.fetch(key, default_value) { |arg| arg }`' do expect_offense(<<~RUBY) x&.fetch(key, default_value) { |arg| arg } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) x&.fetch(key) { |arg| arg } RUBY end it 'registers an offense for `x.fetch(key, {}) { block_value }`' do expect_offense(<<~RUBY) x.fetch(key, {}) { block_value } ^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) x.fetch(key) { block_value } RUBY end it 'registers an offense for `x.fetch(key, default_value) { _1 }`' do expect_offense(<<~RUBY) x.fetch(key, default_value) { _1 } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) x.fetch(key) { _1 } RUBY end it 'registers an offense for `x.fetch(key, default_value) { it }`' do expect_offense(<<~RUBY) x.fetch(key, default_value) { it } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) x.fetch(key) { it } RUBY end it 'does not register an offense for `x.fetch(key, default: value) { block_value }`' do expect_no_offenses(<<~RUBY) x.fetch(key, default: value) { block_value } RUBY end it 'does not register an offense for `x.fetch(key, default_value)`' do expect_no_offenses(<<~RUBY) x.fetch(key, default_value) RUBY end it 'does not register an offense for `x.fetch(key) { block_value }`' do expect_no_offenses(<<~RUBY) x.fetch(key) { block_value } RUBY end it 'does not register an offense for `x.fetch(key) { |arg1, arg2| block_value }`' do expect_no_offenses(<<~RUBY) x.fetch(key) { |arg1, arg2| block_value } RUBY end it 'does not register an offense for `x.fetch(key, default_value, third_argument) { block_value }`' do expect_no_offenses(<<~RUBY) x.fetch(key, default_value, third_argument) { block_value } RUBY end it 'does not register an offense for `x.fetch(key, **kwarg) { block_value }`' do expect_no_offenses(<<~RUBY) x.fetch(key, **kwarg) { block_value } RUBY end it 'does not register an offense for `fetch(key, default_value) { |arg| arg }`' do expect_no_offenses(<<~RUBY) fetch(key, default_value) { |arg| arg } RUBY end end context 'with `Array.new`' do it 'registers an offense for `Array.new(size, default_value) { block_value }`' do expect_offense(<<~RUBY) Array.new(size, default_value) { block_value } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) Array.new(size) { block_value } RUBY end it 'registers an offense for `::Array.new(size, default_value) { block_value }`' do expect_offense(<<~RUBY) ::Array.new(size, default_value) { block_value } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) ::Array.new(size) { block_value } RUBY end it 'registers an offense for `Array.new(size, default_value) { _1 }`' do expect_offense(<<~RUBY) Array.new(size, default_value) { _1 } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) Array.new(size) { _1 } RUBY end it 'registers an offense for `Array.new(size, default_value) { it }`' do expect_offense(<<~RUBY) Array.new(size, default_value) { it } ^^^^^^^^^^^^^ Block supersedes default value argument. RUBY expect_correction(<<~RUBY) Array.new(size) { it } RUBY end it 'does not register an offense for `Array.new(size, default_value)`' do expect_no_offenses(<<~RUBY) Array.new(size, default_value) RUBY end it 'does not register an offense for `Array.new(size)`' do expect_no_offenses(<<~RUBY) Array.new(size) RUBY end it 'does not register an offense for `Array.new(size) { block_value }`' do expect_no_offenses(<<~RUBY) Array.new(size) { block_value } RUBY end it 'does not register an offense for `Array.new(size) { |arg1, arg2| block_value }`' do expect_no_offenses(<<~RUBY) Array.new(size) { |arg1, arg2| block_value } RUBY end it 'does not register an offense for `Array.new(size, default_value, third_argument) { block_value }`' do expect_no_offenses(<<~RUBY) Array.new(size, default_value, third_argument) { block_value } RUBY end end context "when `AllowedReceivers: ['Rails.cache']`" do let(:cop_config) { { 'AllowedReceivers' => ['Rails.cache'] } } it 'does not register an offense for `Rails.cache.fetch(name, options) { block }`' do expect_no_offenses(<<~RUBY) Rails.cache.fetch(name, options) { block } RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/deprecated_open_ssl_constant_spec.rb
spec/rubocop/cop/lint/deprecated_open_ssl_constant_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DeprecatedOpenSSLConstant, :config do it 'registers an offense with cipher constant and two arguments and corrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::AES.new(128, :GCM) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('aes-128-gcm')` instead of `OpenSSL::Cipher::AES.new(128, :GCM)`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('aes-128-gcm') RUBY end it 'registers an offense with cipher constant and one argument and corrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::AES.new('128-GCM') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('aes-128-gcm')` instead of `OpenSSL::Cipher::AES.new('128-GCM')`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('aes-128-gcm') RUBY end it 'registers an offense with cipher constant and double quoted string argument and corrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::AES128.new("GCM") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('aes-128-gcm')` instead of `OpenSSL::Cipher::AES128.new("GCM")`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('aes-128-gcm') RUBY end it 'registers an offense with cipher constant and `cbc` argument and corrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::DES.new('cbc') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('des-cbc')` instead of `OpenSSL::Cipher::DES.new('cbc')`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('des-cbc') RUBY end it 'registers an offense when the `Cipher` constant appears twice and autocorrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::Cipher.new('AES-256-ECB') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('AES-256-ECB')` instead of `OpenSSL::Cipher::Cipher.new('AES-256-ECB')`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('AES-256-ECB') RUBY end it 'registers an offense with cipher constant and `ecb` argument and corrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::BF.new('ecb') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('bf-ecb')` instead of `OpenSSL::Cipher::BF.new('ecb')`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('bf-ecb') RUBY end it 'registers an offense with AES + blocksize constant and mode argument and corrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::AES128.new(:GCM) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('aes-128-gcm')` instead of `OpenSSL::Cipher::AES128.new(:GCM)`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('aes-128-gcm') RUBY end described_class::NO_ARG_ALGORITHM.each do |algorithm_name| it 'registers an offense with cipher constant and no arguments and corrects' do expect_offense(<<~RUBY, algorithm_name: algorithm_name) OpenSSL::Cipher::#{algorithm_name}.new ^^^^^^^^^^^^^^^^^^{algorithm_name}^^^^ Use `OpenSSL::Cipher.new('#{algorithm_name.downcase}')` instead of `OpenSSL::Cipher::#{algorithm_name}.new`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('#{algorithm_name.downcase}') RUBY end end it 'registers an offense with AES + blocksize constant and corrects' do expect_offense(<<~RUBY) OpenSSL::Cipher::AES128.new ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Cipher.new('aes-128-cbc')` instead of `OpenSSL::Cipher::AES128.new`. RUBY expect_correction(<<~RUBY) OpenSSL::Cipher.new('aes-128-cbc') RUBY end it 'does not register an offense when using cipher with a string' do expect_no_offenses(<<~RUBY) OpenSSL::Cipher.new('aes-128-gcm') RUBY end it 'does not register an offense with cipher constant and argument is a variable' do expect_no_offenses(<<~RUBY) mode = "cbc" OpenSSL::Cipher::AES128.new(mode) RUBY end it 'does not register an offense with cipher constant and argument is a method call' do expect_no_offenses(<<~RUBY) OpenSSL::Cipher::AES128.new(do_something) RUBY end it 'does not register an offense with cipher constant and argument is a safe navigation method call' do expect_no_offenses(<<~RUBY) OpenSSL::Cipher::AES128.new(foo&.bar) RUBY end it 'does not register an offense with cipher constant and argument is a constant' do expect_no_offenses(<<~RUBY) OpenSSL::Cipher::AES128.new(MODE) RUBY end it 'registers an offense when building an instance using a digest constant and corrects' do expect_offense(<<~RUBY) OpenSSL::Digest::SHA256.new ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Digest.new('SHA256')` instead of `OpenSSL::Digest::SHA256.new`. RUBY expect_correction(<<~RUBY) OpenSSL::Digest.new('SHA256') RUBY end it 'registers an offense when using ::Digest class methods on an algorithm constant and corrects' do expect_offense(<<~RUBY) OpenSSL::Digest::SHA256.digest('foo') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Digest.digest('SHA256', 'foo')` instead of `OpenSSL::Digest::SHA256.digest('foo')`. RUBY expect_correction(<<~RUBY) OpenSSL::Digest.digest('SHA256', 'foo') RUBY end it 'registers an offense when using a digest constant with chained methods and corrects' do expect_offense(<<~RUBY) OpenSSL::Digest::SHA256.new.digest('foo') ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Digest.new('SHA256')` instead of `OpenSSL::Digest::SHA256.new`. RUBY expect_correction(<<~RUBY) OpenSSL::Digest.new('SHA256').digest('foo') RUBY end context 'when used in a block' do it 'registers an offense when using ::Digest class methods on an algorithm constant and corrects' do expect_offense(<<~RUBY) do_something do OpenSSL::Digest::SHA1.new ^^^^^^^^^^^^^^^^^^^^^^^^^ Use `OpenSSL::Digest.new('SHA1')` instead of `OpenSSL::Digest::SHA1.new`. end RUBY expect_correction(<<~RUBY) do_something do OpenSSL::Digest.new('SHA1') end RUBY end end it 'does not register an offense when building digest using an algorithm string' do expect_no_offenses(<<~RUBY) OpenSSL::Digest.new('SHA256') RUBY end it 'does not register an offense when building digest using an algorithm string and nested digest constants' do expect_no_offenses(<<~RUBY) OpenSSL::Digest::Digest.new('SHA256') RUBY end it 'does not register an offense when using ::Digest class methods with an algorithm string and value' do expect_no_offenses(<<~RUBY) OpenSSL::Digest.digest('SHA256', 'foo') RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/rescue_exception_spec.rb
spec/rubocop/cop/lint/rescue_exception_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RescueException, :config do it 'registers an offense for rescue from Exception' do expect_offense(<<~RUBY) begin something rescue Exception ^^^^^^^^^^^^^^^^ Avoid rescuing the `Exception` class. Perhaps you meant to rescue `StandardError`? #do nothing end RUBY end it 'registers an offense for rescue with ::Exception' do expect_offense(<<~RUBY) begin something rescue ::Exception ^^^^^^^^^^^^^^^^^^ Avoid rescuing the `Exception` class. Perhaps you meant to rescue `StandardError`? #do nothing end RUBY end it 'registers an offense for rescue with StandardError, Exception' do expect_offense(<<~RUBY) begin something rescue StandardError, Exception ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid rescuing the `Exception` class. Perhaps you meant to rescue `StandardError`? #do nothing end RUBY end it 'registers an offense for rescue with Exception => e' do expect_offense(<<~RUBY) begin something rescue Exception => e ^^^^^^^^^^^^^^^^^^^^^ Avoid rescuing the `Exception` class. Perhaps you meant to rescue `StandardError`? #do nothing end RUBY end it 'does not register an offense for rescue with no class' do expect_no_offenses(<<~RUBY) begin something return rescue file.close end RUBY end it 'does not register an offense for rescue with no class and => e' do expect_no_offenses(<<~RUBY) begin something return rescue => e file.close end RUBY end it 'does not register an offense for rescue with other class' do expect_no_offenses(<<~RUBY) begin something return rescue ArgumentError => e file.close end RUBY end it 'does not register an offense for rescue with other classes' do expect_no_offenses(<<~RUBY) begin something return rescue EOFError, ArgumentError => e file.close end RUBY end it 'does not register an offense for rescue with a module prefix' do expect_no_offenses(<<~RUBY) begin something return rescue Test::Exception => e file.close end RUBY end it 'does not crash when the splat operator is used in a rescue' do expect_no_offenses(<<~RUBY) ERRORS = [Exception] begin a = 3 / 0 rescue *ERRORS puts e end RUBY end it 'does not crash when the namespace of a rescued class is in a local variable' do expect_no_offenses(<<~RUBY) adapter = current_adapter begin rescue adapter::ParseError 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/lint/deprecated_constants_spec.rb
spec/rubocop/cop/lint/deprecated_constants_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DeprecatedConstants, :config do let(:cop_config) do { 'DeprecatedConstants' => { 'NIL' => { 'Alternative' => 'nil', 'DeprecatedVersion' => '2.4' }, 'TRUE' => { 'Alternative' => 'true', 'DeprecatedVersion' => '2.4' }, 'FALSE' => { 'Alternative' => 'false', 'DeprecatedVersion' => '2.4' }, 'Net::HTTPServerException' => { 'Alternative' => 'Net::HTTPClientException', 'DeprecatedVersion' => '2.6' }, 'Random::DEFAULT' => { 'Alternative' => 'Random.new', 'DeprecatedVersion' => '3.0' }, 'Struct::Group' => { 'Alternative' => 'Etc::Group', 'DeprecatedVersion' => '3.0' }, 'Struct::Passwd' => { 'Alternative' => 'Etc::Passwd', 'DeprecatedVersion' => '3.0' }, 'Triple::Nested::Constant' => { 'Alternative' => 'Value', 'DeprecatedVersion' => '2.4' }, 'Have::No::Alternative' => { 'DeprecatedVersion' => '2.4' }, 'Have::No::DeprecatedVersion' => { 'Alternative' => 'Value' } } } end it 'registers and corrects an offense when using `NIL`' do expect_offense(<<~RUBY) NIL ^^^ Use `nil` instead of `NIL`, deprecated since Ruby 2.4. RUBY expect_correction(<<~RUBY) nil RUBY end it 'registers and corrects an offense when using `TRUE`' do expect_offense(<<~RUBY) TRUE ^^^^ Use `true` instead of `TRUE`, deprecated since Ruby 2.4. RUBY expect_correction(<<~RUBY) true RUBY end it 'registers and corrects an offense when using `FALSE`' do expect_offense(<<~RUBY) FALSE ^^^^^ Use `false` instead of `FALSE`, deprecated since Ruby 2.4. RUBY expect_correction(<<~RUBY) false RUBY end context 'Ruby <= 2.5', :ruby25, unsupported_on: :prism do it 'does not register an offense when using `Net::HTTPServerException`' do expect_no_offenses(<<~RUBY) Net::HTTPServerException RUBY end end context 'Ruby >= 2.6', :ruby26 do it 'registers and corrects an offense when using `Net::HTTPServerException`' do expect_offense(<<~RUBY) Net::HTTPServerException ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Net::HTTPClientException` instead of `Net::HTTPServerException`, deprecated since Ruby 2.6. RUBY expect_correction(<<~RUBY) Net::HTTPClientException RUBY end end context 'Ruby <= 2.7', :ruby27, unsupported_on: :prism do it 'does not register an offense when using `Random::DEFAULT`' do expect_no_offenses(<<~RUBY) Random::DEFAULT RUBY end it 'does not register an offense when using `Struct::Group`' do expect_no_offenses(<<~RUBY) Struct::Group RUBY end it 'does not register an offense when using `Struct::Passwd`' do expect_no_offenses(<<~RUBY) Struct::Passwd RUBY end end context 'Ruby >= 3.0', :ruby30 do it 'registers and corrects an offense when using `Random::DEFAULT`' do expect_offense(<<~RUBY) Random::DEFAULT ^^^^^^^^^^^^^^^ Use `Random.new` instead of `Random::DEFAULT`, deprecated since Ruby 3.0. RUBY expect_correction(<<~RUBY) Random.new RUBY end it 'registers and corrects an offense when using `::Random::DEFAULT`' do expect_offense(<<~RUBY) ::Random::DEFAULT ^^^^^^^^^^^^^^^^^ Use `Random.new` instead of `::Random::DEFAULT`, deprecated since Ruby 3.0. RUBY expect_correction(<<~RUBY) Random.new RUBY end it 'registers and corrects an offense when using `Struct::Group`' do expect_offense(<<~RUBY) Struct::Group ^^^^^^^^^^^^^ Use `Etc::Group` instead of `Struct::Group`, deprecated since Ruby 3.0. RUBY expect_correction(<<~RUBY) Etc::Group RUBY end it 'registers and corrects an offense when using `Struct::Passwd`' do expect_offense(<<~RUBY) Struct::Passwd ^^^^^^^^^^^^^^ Use `Etc::Passwd` instead of `Struct::Passwd`, deprecated since Ruby 3.0. RUBY expect_correction(<<~RUBY) Etc::Passwd RUBY end end it 'registers and corrects an offense when using `::NIL`' do expect_offense(<<~RUBY) ::NIL ^^^^^ Use `nil` instead of `::NIL`, deprecated since Ruby 2.4. RUBY expect_correction(<<~RUBY) nil RUBY end it 'registers and corrects an offense when using `::TRUE`' do expect_offense(<<~RUBY) ::TRUE ^^^^^^ Use `true` instead of `::TRUE`, deprecated since Ruby 2.4. RUBY expect_correction(<<~RUBY) true RUBY end it 'registers and corrects an offense when using `::FALSE`' do expect_offense(<<~RUBY) ::FALSE ^^^^^^^ Use `false` instead of `::FALSE`, deprecated since Ruby 2.4. RUBY expect_correction(<<~RUBY) false RUBY end it 'registers and corrects an offense when using `::Triple::Nested::Constant`' do expect_offense(<<~RUBY) ::Triple::Nested::Constant ^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Value` instead of `::Triple::Nested::Constant`, deprecated since Ruby 2.4. RUBY expect_correction(<<~RUBY) Value RUBY end it 'registers an offense when using deprecated methods that have no alternative' do expect_offense(<<~RUBY) Have::No::Alternative ^^^^^^^^^^^^^^^^^^^^^ Do not use `Have::No::Alternative`, deprecated since Ruby 2.4. RUBY expect_no_corrections end it 'registers and corrects an offense when using deprecated methods that have no deprecated version' do expect_offense(<<~RUBY) Have::No::DeprecatedVersion ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Value` instead of `Have::No::DeprecatedVersion`. RUBY expect_correction(<<~RUBY) Value RUBY end it 'does not register an offense when not using deprecated constant' do expect_no_offenses(<<~RUBY) Foo::TRUE RUBY end it 'does not register an offense when using `__ENCODING__' do expect_no_offenses(<<~RUBY) __ENCODING__ 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/lint/literal_assignment_in_condition_spec.rb
spec/rubocop/cop/lint/literal_assignment_in_condition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::LiteralAssignmentInCondition, :config do it 'registers an offense when assigning integer literal to local variable in `if` condition' do expect_offense(<<~RUBY) if test = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning string literal to local variable in `if` condition' do expect_offense(<<~RUBY) if test = 'foo' ^^^^^^^ Don't use literal assignment `= 'foo'` in conditional, should be `==` or non-literal operand. end RUBY end it 'does not register an offense when assigning interpolated string literal to local variable in `if` condition' do expect_no_offenses(<<~'RUBY') if test = "#{foo}" end RUBY end it 'does not register an offense when assigning xstring literal to local variable in `if` condition' do expect_no_offenses(<<~RUBY) if test = `echo 'hi'` end RUBY end it 'registers an offense when assigning empty array literal to local variable in `if` condition' do expect_offense(<<~RUBY) if test = [] ^^^^ Don't use literal assignment `= []` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning array literal with only literal elements to local variable in `if` condition' do expect_offense(<<~RUBY) if test = [1, 2, 3] ^^^^^^^^^^^ Don't use literal assignment `= [1, 2, 3]` in conditional, should be `==` or non-literal operand. end RUBY end it 'does not register an offense when assigning array literal with non-literal elements to local variable in `if` condition' do expect_no_offenses(<<~RUBY) if test = [42, x, y] end RUBY end it 'registers an offense when assigning empty hash literal to local variable in `if` condition' do expect_offense(<<~RUBY) if test = {} ^^^^ Don't use literal assignment `= {}` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning hash literal with only literal elements to local variable in `if` condition' do expect_offense(<<~RUBY) if test = {x: :y} ^^^^^^^^^ Don't use literal assignment `= {x: :y}` in conditional, should be `==` or non-literal operand. end RUBY end it 'does not register an offense when assigning hash literal with non-literal key to local variable in `if` condition' do expect_no_offenses(<<~RUBY) if test = {x => :y} end RUBY end it 'does not register an offense when assigning hash literal with non-literal value to local variable in `if` condition' do expect_no_offenses(<<~RUBY) if test = {x: y} end RUBY end it 'does not register an offense when assigning non-literal to local variable in `if` condition' do expect_no_offenses(<<~RUBY) if test = do_something end RUBY end it 'registers an offense when assigning literal to local variable in `while` condition' do expect_offense(<<~RUBY) while test = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning literal to local variable in `until` condition' do expect_offense(<<~RUBY) until test = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning literal to instance variable in condition' do expect_offense(<<~RUBY) if @test = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning literal to class variable in condition' do expect_offense(<<~RUBY) if @@test = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning literal to global variable in condition' do expect_offense(<<~RUBY) if $test = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. end RUBY end it 'registers an offense when assigning literal to constant in condition' do expect_offense(<<~RUBY) if TEST = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. end RUBY end it 'does not register an offense when assigning literal to collection element in condition' do expect_no_offenses(<<~RUBY) if collection[index] = 42 end RUBY end it 'does not register an offense when `==` in condition' do expect_no_offenses(<<~RUBY) if test == 10 end RUBY end it 'registers an offense when assigning after `== `in condition' do expect_offense(<<~RUBY) if test == 10 || foo = 1 ^^^ Don't use literal assignment `= 1` in conditional, should be `==` or non-literal operand. end RUBY end it 'does not register an offense when `=` in a block that is called in a condition' do expect_no_offenses('return 1 if any_errors? { o = inspect(file) }') end it 'does not register an offense when `=` in a block followed by method call' do expect_no_offenses('return 1 if any_errors? { o = file }.present?') end it 'does not register an offense when assignment in a block after `||`' do expect_no_offenses(<<~RUBY) if x?(bar) || y? { z = baz } foo end RUBY end it 'registers an offense when `=` in condition inside a block' do expect_offense(<<~RUBY) foo { x if y = 42 } ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. RUBY end it 'does not register an offense when `=` in condition inside a block' do expect_no_offenses(<<~RUBY) foo { x if y = z } RUBY end it 'does not register an offense when `||=` in condition' do expect_no_offenses('raise StandardError unless foo ||= bar') end it 'registers an offense when literal assignment after `||=` in condition' do expect_offense(<<~RUBY) raise StandardError unless (foo ||= bar) || a = 42 ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. RUBY end it 'does not register an offense when assigning non-literal after `||=` in condition' do expect_no_offenses(<<~RUBY) raise StandardError unless (foo ||= bar) || a = b RUBY end it 'does not register an offense when assignment method in condition' do expect_no_offenses(<<~RUBY) if test.method = 42 end RUBY end it 'does not blow up when empty `if` condition' do expect_no_offenses(<<~RUBY) if () end RUBY end it 'does not blow up when empty `unless` condition' do expect_no_offenses(<<~RUBY) unless () end RUBY end it 'does not register an offense when using parallel assignment with splat operator in the block of guard condition' do expect_no_offenses(<<~RUBY) return if do_something do |z| x, y = *z end RUBY end it 'registers when `=` in condition surrounded with braces' do expect_offense(<<~RUBY) if (test = 42) ^^^^ Don't use literal assignment `= 42` in conditional, should be `==` or non-literal operand. 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/lint/empty_when_spec.rb
spec/rubocop/cop/lint/empty_when_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyWhen, :config do let(:cop_config) { { 'AllowComments' => false } } context 'when a `when` body is missing' do it 'registers an offense for a missing when body' do expect_offense(<<~RUBY) case foo when :bar then 1 when :baz # nothing ^^^^^^^^^ Avoid `when` branches without a body. end RUBY expect_no_corrections end it 'registers an offense for missing when body followed by else' do expect_offense(<<~RUBY) case foo when :bar then 1 when :baz # nothing ^^^^^^^^^ Avoid `when` branches without a body. else 3 end RUBY expect_no_corrections end it 'registers an offense for missing when ... then body' do expect_offense(<<~RUBY) case foo when :bar then 1 when :baz then # nothing ^^^^^^^^^ Avoid `when` branches without a body. end RUBY expect_no_corrections end it 'registers an offense for missing when ... then body followed by else' do expect_offense(<<~RUBY) case foo when :bar then 1 when :baz then # nothing ^^^^^^^^^ Avoid `when` branches without a body. else 3 end RUBY expect_no_corrections end it 'registers an offense for missing when body with a comment' do expect_offense(<<~RUBY) case foo when :bar 1 when :baz ^^^^^^^^^ Avoid `when` branches without a body. # nothing end RUBY expect_no_corrections end it 'registers an offense for missing when body with a comment followed by else' do expect_offense(<<~RUBY) case foo when :bar 1 when :baz ^^^^^^^^^ Avoid `when` branches without a body. # nothing else 3 end RUBY expect_no_corrections end it 'registers an offense when case line has no expression' do expect_offense(<<~RUBY) case when :bar 1 when :baz ^^^^^^^^^ Avoid `when` branches without a body. # nothing else 3 end RUBY expect_no_corrections end end context 'when a `when` body is present' do it 'accepts case with when ... then statements' do expect_no_offenses(<<~RUBY) case foo when :bar then 1 when :baz then 2 end RUBY end it 'accepts case with when ... then statements and else clause' do expect_no_offenses(<<~RUBY) case foo when :bar then 1 when :baz then 2 else 3 end RUBY end it 'accepts case with when bodies' do expect_no_offenses(<<~RUBY) case foo when :bar 1 when :baz 2 end RUBY end it 'accepts case with when bodies and else clause' do expect_no_offenses(<<~RUBY) case foo when :bar 1 when :baz 2 else 3 end RUBY end it 'accepts with no case line expression' do expect_no_offenses(<<~RUBY) case when :bar 1 when :baz 2 else 3 end RUBY end end context 'when `AllowComments: true`' do let(:cop_config) { { 'AllowComments' => true } } it 'accepts an empty when body with a comment' do expect_no_offenses(<<~RUBY) case condition when foo do_something when bar # do nothing end RUBY end it 'registers an offense for missing when body without a comment' do expect_offense(<<~RUBY) case condition when foo 42 # magic number when bar ^^^^^^^^ Avoid `when` branches without a body. when baz # more comments mixed 21 # another magic number end RUBY end it 'accepts an empty when ... then body with a comment' do expect_no_offenses(<<~RUBY) case condition when foo do_something when bar then # do nothing end RUBY end end context 'when `AllowComments: false`' do let(:cop_config) { { 'AllowComments' => false } } it 'registers an offense for empty when body with a comment' do expect_offense(<<~RUBY) case condition when foo do_something when bar ^^^^^^^^ Avoid `when` branches without a body. # do nothing end RUBY expect_no_corrections end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/cop_directive_syntax_spec.rb
spec/rubocop/cop/lint/cop_directive_syntax_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::CopDirectiveSyntax, :config do it 'does not register an offense for a single cop name' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout/LineLength RUBY end it 'does not register an offense for a single cop department' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout RUBY end it 'does not register an offense for multiple cops' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout/LineLength, Style/Encoding RUBY end it 'does not register an offense for `all` cops' do expect_no_offenses(<<~RUBY) # rubocop:disable all RUBY end it 'does not register an offense for enable directives' do expect_no_offenses(<<~RUBY) # rubocop:enable Layout/LineLength RUBY end it 'does not register an offense for todo directives' do expect_no_offenses(<<~RUBY) # rubocop:todo Layout/LineLength RUBY end it 'registers an offense for multiple cops a without comma' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength Style/Encoding ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Malformed directive comment detected. Cop names must be separated by commas. Comment in the directive must start with `--`. RUBY end it 'registers an offense for duplicate directives' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength # rubocop:disable Style/Encoding ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Malformed directive comment detected. Cop names must be separated by commas. Comment in the directive must start with `--`. RUBY end it 'registers an offense for missing cop name' do expect_offense(<<~RUBY) # rubocop:disable ^^^^^^^^^^^^^^^^^ Malformed directive comment detected. The cop name is missing. RUBY end it 'registers an offense for incorrect mode' do expect_offense(<<~RUBY) # rubocop:disabled Layout/LineLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Malformed directive comment detected. The mode name must be one of `enable`, `disable`, `todo`, `push`, or `pop`. RUBY end it 'registers an offense if the mode name is missing' do expect_offense(<<~RUBY) # rubocop: ^^^^^^^^^^ Malformed directive comment detected. The mode name is missing. RUBY end it 'does not register an offense when a comment does not start with `# rubocop:`, which is not a directive comment' do expect_no_offenses(<<~RUBY) # "rubocop:disable Layout/LineLength" RUBY end it 'does not register an offense for duplicate comment out' do expect_no_offenses(<<~RUBY) # # rubocop:disable Layout/LineLength RUBY end it 'does not register an offense for an extra trailing comment' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout/LineLength -- This is a good comment. RUBY end it 'does not register an offense for a single line directive with trailing comment' do expect_no_offenses(<<~RUBY) a = 1 # rubocop:disable Layout/LineLength -- This is a good comment. RUBY end it 'registers an offense when trailing comment does not start with `--`' do expect_offense(<<~RUBY) # rubocop:disable Layout/LineLength == This is a bad comment. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Malformed directive comment detected. Cop names must be separated by commas. Comment in the directive must start with `--`. 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/lint/assignment_in_condition_spec.rb
spec/rubocop/cop/lint/assignment_in_condition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::AssignmentInCondition, :config do let(:cop_config) { { 'AllowSafeAssignment' => true } } it 'registers an offense for lvar assignment in condition' do expect_offense(<<~RUBY) if test = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if (test = 10) end RUBY end it 'registers an offense for lvar assignment in while condition' do expect_offense(<<~RUBY) while test = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) while (test = 10) end RUBY end it 'registers an offense for lvar assignment in until condition' do expect_offense(<<~RUBY) until test = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) until (test = 10) end RUBY end it 'registers an offense for ivar assignment in condition' do expect_offense(<<~RUBY) if @test = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if (@test = 10) end RUBY end it 'registers an offense for clvar assignment in condition' do expect_offense(<<~RUBY) if @@test = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if (@@test = 10) end RUBY end it 'registers an offense for gvar assignment in condition' do expect_offense(<<~RUBY) if $test = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if ($test = 10) end RUBY end it 'registers an offense for constant assignment in condition' do expect_offense(<<~RUBY) if TEST = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if (TEST = 10) end RUBY end it 'registers an offense for collection element assignment in condition' do expect_offense(<<~RUBY) if a[3] = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if (a[3] = 10) end RUBY end it 'accepts == in condition' do expect_no_offenses(<<~RUBY) if test == 10 end RUBY end it 'registers an offense for assignment after == in condition' do expect_offense(<<~RUBY) if test == 10 || foobar = 1 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if test == 10 || (foobar = 1) end RUBY end it 'accepts = in a block that is called in a condition' do expect_no_offenses('return 1 if any_errors? { o = inspect(file) }') end it 'accepts = in a block followed by method call' do expect_no_offenses('return 1 if any_errors? { o = file }.present?') end it 'accepts = in a numblock that is called in a condition' do expect_no_offenses('return 1 if any_errors? { o = inspect(_1) }') end it 'accepts = in a numblock followed by method call' do expect_no_offenses('return 1 if any_errors? { o = _1 }.present?') end context 'Ruby 3.4', :ruby34 do it 'accepts = in an itblock that is called in a condition' do expect_no_offenses('return 1 if any_errors? { o = inspect(it) }') end it 'accepts = in an itblock followed by method call' do expect_no_offenses('return 1 if any_errors? { o = it }.present?') end end it 'accepts assignment in a block after ||' do expect_no_offenses(<<~RUBY) if x?(bar) || y? { z = baz } foo end RUBY end it 'registers an offense for = in condition inside a block' do expect_offense(<<~RUBY) foo { x if y = z } ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. RUBY expect_correction(<<~RUBY) foo { x if (y = z) } RUBY end it 'accepts ||= in condition' do expect_no_offenses('raise StandardError unless foo ||= bar') end it 'registers an offense for assignment after ||= in condition' do expect_offense(<<~RUBY) raise StandardError unless (foo ||= bar) || a = b ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. RUBY expect_correction(<<~RUBY) raise StandardError unless (foo ||= bar) || (a = b) RUBY end it 'registers an offense for assignment methods' do expect_offense(<<~RUBY) if test.method = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if (test.method = 10) end RUBY end it 'registers an offense for assignment methods with safe navigation operator' do expect_offense(<<~RUBY) if test&.method = 10 ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) if (test&.method = 10) end RUBY end it 'does not blow up for empty if condition' do expect_no_offenses(<<~RUBY) if () end RUBY end it 'does not blow up for empty unless condition' do expect_no_offenses(<<~RUBY) unless () end RUBY end it 'does not register an offense for assignment in method call' do expect_no_offenses(<<~RUBY) return unless %i[asc desc].include?(order = params[:order]) RUBY end context 'safe assignment is allowed' do it 'accepts = in condition surrounded with braces' do expect_no_offenses(<<~RUBY) if (test = 10) end RUBY end it 'accepts []= in condition surrounded with braces' do expect_no_offenses(<<~RUBY) if (test[0] = 10) end RUBY end %i[&& ||].each do |operator| context "with an unparenthesized assignment inside a parenthesized #{operator} statement" do %i[if while until].each do |keyword| context "inside an #{keyword} statement" do it 'registers an offense and corrects' do expect_offense(<<~RUBY, keyword: keyword, operator: operator) %{keyword} (foo == bar %{operator} test = 10) _{keyword} _{operator} ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) #{keyword} (foo == bar #{operator} (test = 10)) end RUBY end it 'registers an offense and corrects inside nested parentheses' do expect_offense(<<~RUBY, keyword: keyword, operator: operator) %{keyword} ((foo == bar %{operator} test = 10)) _{keyword} _{operator} ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. end RUBY expect_correction(<<~RUBY) #{keyword} ((foo == bar #{operator} (test = 10))) end RUBY end end context "inside an #{keyword} modifier" do it 'registers an offense and corrects' do expect_offense(<<~RUBY, keyword: keyword, operator: operator) do_something %{keyword} (foo == bar %{operator} test = 10) _{keyword} _{operator} ^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition. RUBY expect_correction(<<~RUBY) do_something #{keyword} (foo == bar #{operator} (test = 10)) RUBY end end end end context "with a compound assignment using #{operator} inside parentheses" do it 'does not register an offense' do expect_no_offenses(<<~RUBY) if (test = foo #{operator} bar == baz) end RUBY end end end end context 'safe assignment is not allowed' do let(:cop_config) { { 'AllowSafeAssignment' => false } } it 'does not accept = in condition surrounded with braces' do expect_offense(<<~RUBY) if (test = 10) ^ Use `==` if you meant to do a comparison or move the assignment up out of the condition. end RUBY expect_no_corrections end it 'does not accept []= in condition surrounded with braces' do expect_offense(<<~RUBY) if (test[0] = 10) ^ Use `==` if you meant to do a comparison or move the assignment up out of the condition. end RUBY expect_no_corrections end %i[&& ||].each do |operator| context "with an unparenthesized assignment inside a parenthesized #{operator} statement" do %i[if while until].each do |keyword| context "inside an #{keyword} statement" do it 'registers an offense but does not correct' do expect_offense(<<~RUBY, keyword: keyword, operator: operator) %{keyword} (foo == bar %{operator} test = 10) _{keyword} _{operator} ^ Use `==` if you meant to do a comparison or move the assignment up out of the condition. end RUBY expect_no_corrections end it 'registers an offense but does not correct inside nested parentheses' do expect_offense(<<~RUBY, keyword: keyword, operator: operator) %{keyword} ((foo == bar %{operator} test = 10)) _{keyword} _{operator} ^ Use `==` if you meant to do a comparison or move the assignment up out of the condition. end RUBY expect_no_corrections end end context "inside an #{keyword} modifier" do it 'registers an offense but does not correct' do expect_offense(<<~RUBY, keyword: keyword, operator: operator) do_something %{keyword} (foo == bar %{operator} test = 10) _{keyword} _{operator} ^ Use `==` if you meant to do a comparison or move the assignment up out of the condition. RUBY expect_no_corrections end end end end context "with a compound assignment using #{operator} inside parentheses" do it 'registers an offense but does not correct' do expect_offense(<<~RUBY) if (test = foo #{operator} bar == baz) ^ Use `==` if you meant to do a comparison or move the assignment up out of the condition. end RUBY expect_no_corrections 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/lint/rand_one_spec.rb
spec/rubocop/cop/lint/rand_one_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RandOne, :config do shared_examples 'offenses' do |source| describe source do it 'registers an offense' do expect_offense(<<~RUBY, source: source) %{source} ^{source} `#{source}` always returns `0`. [...] RUBY end end end shared_examples 'no offense' do |source| describe source do it 'does not register an offense' do expect_no_offenses(source) end end end it_behaves_like 'offenses', 'rand 1' it_behaves_like 'offenses', 'rand(-1)' it_behaves_like 'offenses', 'rand(1.0)' it_behaves_like 'offenses', 'rand(-1.0)' it_behaves_like 'no offense', 'rand' it_behaves_like 'no offense', 'rand(2)' it_behaves_like 'no offense', 'rand(-1..1)' it_behaves_like 'offenses', 'Kernel.rand(1)' it_behaves_like 'offenses', 'Kernel.rand(-1)' it_behaves_like 'offenses', 'Kernel.rand 1.0' it_behaves_like 'offenses', 'Kernel.rand(-1.0)' it_behaves_like 'no offense', 'Kernel.rand' it_behaves_like 'no offense', 'Kernel.rand 2' it_behaves_like 'no offense', 'Kernel.rand(-1..1)' it_behaves_like 'offenses', '::Kernel.rand(1)' it_behaves_like 'no offense', '::Kernel.rand' end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/shadowing_outer_local_variable_spec.rb
spec/rubocop/cop/lint/shadowing_outer_local_variable_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ShadowingOuterLocalVariable, :config do context 'when a block argument has same name as an outer scope variable' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = 1 puts foo 1.times do |foo| ^^^ Shadowing outer local variable - `foo`. end end RUBY end end context 'when a splat block argument has same name as an outer scope variable' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = 1 puts foo 1.times do |*foo| ^^^^ Shadowing outer local variable - `foo`. end end RUBY end end context 'when a block block argument has same name as an outer scope variable' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = 1 puts foo proc_taking_block = proc do |&foo| ^^^^ Shadowing outer local variable - `foo`. end proc_taking_block.call do end end RUBY end end context 'when a block local variable has same name as an outer scope variable' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = 1 puts foo 1.times do |i; foo| ^^^ Shadowing outer local variable - `foo`. puts foo end end RUBY end end context 'when a block local variable has same name as an outer `until` scope variable' do it 'registers an offense' do expect_offense(<<~RUBY) until foo var = do_something end if bar array.each do |var| ^^^ Shadowing outer local variable - `var`. end end RUBY end end context 'when a block local variable has same name as an outer `while` scope variable' do it 'registers an offense' do expect_offense(<<~RUBY) while foo var = do_something end if bar array.each do |var| ^^^ Shadowing outer local variable - `var`. end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with same branches of same `if` condition node not in the method definition' do it 'registers an offense' do expect_offense(<<~RUBY) if condition? foo = 1 puts foo bar.each do |foo| ^^^ Shadowing outer local variable - `foo`. end else bar.each do |foo| end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with same branches of same `if` condition node' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method if condition? foo = 1 puts foo bar.each do |foo| ^^^ Shadowing outer local variable - `foo`. end else bar.each do |foo| end end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with same branches of same nested `if` condition node' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method if condition? foo = 1 puts foo if other_condition? bar.each do |foo| ^^^ Shadowing outer local variable - `foo`. end end elsif other_condition? bar.each do |foo| end else bar.each do |foo| end end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with same branches of same `unless` condition node' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method unless condition? foo = 1 puts foo bar.each do |foo| ^^^ Shadowing outer local variable - `foo`. end else bar.each do |foo| end end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with same branches of same `case` condition node' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method case condition when foo then foo = 1 puts foo bar.each do |foo| ^^^ Shadowing outer local variable - `foo`. end when bar then bar.each do |foo| end else bar.each do |foo| end end end RUBY end end context 'when a block local variable inside an `if` has same name as an outer scope variable' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = 1 if cond bar.each do |foo| ^^^ Shadowing outer local variable - `foo`. end end end RUBY end end context 'when a block local variable has same name as method argument' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(foo) 1.times do |foo| ^^^ Shadowing outer local variable - `foo`. end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with different branches of same `if` condition node' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method if condition? foo = 1 elsif other_condition? bar.each do |foo| end else bar.each do |foo| end end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with different branches of same `unless` condition node' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method unless condition? foo = 1 else bar.each do |foo| end end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with different branches of same `if` condition node' \ 'in a nested node' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method if condition? foo = 1 else bar = [1, 2, 3] bar.each do |foo| end end end RUBY end end context 'when a block local variable has same name as an outer scope variable' \ 'with different branches of same `case` condition node' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method case condition when foo then foo = 1 else bar.each do |foo| end end end RUBY end end context 'when a block argument has different name with outer scope variables' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method foo = 1 puts foo 1.times do |bar| end end RUBY end end context 'when an outer scope variable is reassigned in a block' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method foo = 1 puts foo 1.times do foo = 2 end end RUBY end end context 'when an outer scope variable is referenced in a block' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method foo = 1 puts foo 1.times do puts foo end end RUBY end end context 'when the same variable name as a block variable is used in return value assignment of `if`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method foo = if condition bar { |foo| baz(foo) } end end RUBY end end context 'when the same variable name as a block variable is used in return value assignment of method' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method foo = bar { |foo| baz(foo) } end RUBY end end context 'when multiple block arguments have same name "_"' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method 1.times do |_, foo, _| end end RUBY end end context 'when multiple block arguments have a same name starts with "_"' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method 1.times do |_foo, bar, _foo| end end RUBY end end context 'when a block argument has same name "_" as outer scope variable "_"' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method _ = 1 puts _ 1.times do |_| end end RUBY end end context 'when a block argument has a same name starts with "_" as an outer scope variable' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method _foo = 1 puts _foo 1.times do |_foo| end end RUBY end end context 'when a method argument has same name as an outer scope variable' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class SomeClass foo = 1 puts foo def some_method(foo) end end RUBY end end context 'when a block parameter has same name as a prior block body variable' do context 'when assigning a block parameter' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def x(array) array.each { |foo| bar = foo }.each { |bar| } end RUBY end end context 'when assigning a numbered block parameter', :ruby27 do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def x(array) array.each { bar = _1 }.each { |bar| } end RUBY end end context 'when assigning an `it` block parameter', :ruby34 do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def x(array) array.each { bar = it }.each { |bar| } end RUBY end end end context 'with Ractor.new' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def foo(*args) Ractor.new(*args) do |*args| 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/lint/ambiguous_operator_precedence_spec.rb
spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::AmbiguousOperatorPrecedence, :config do it 'does not register an offense when there is only one operator in the expression' do expect_no_offenses(<<~RUBY) a + b RUBY end it 'does not register an offense when all operators in the expression have the same precedence' do expect_no_offenses(<<~RUBY) a + b + c a * b / c % d a && b && c RUBY end it 'does not register an offense when expressions are wrapped in parentheses by precedence' do expect_no_offenses(<<~RUBY) a + (b * c) (a ** b) + c RUBY end it 'does not register an offense when expressions are wrapped in parentheses by reverse precedence' do expect_no_offenses(<<~RUBY) (a + b) * c a ** (b + c) RUBY end it 'does not register an offense when boolean expressions are wrapped in parens' do expect_no_offenses(<<~RUBY) (a && b) || c a || (b & c) RUBY end it 'registers an offense when an expression with mixed precedence has no parens' do expect_offense(<<~RUBY) a + b * c ^^^^^ Wrap expressions with varying precedence with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) a + (b * c) RUBY end it 'registers an offense when an expression with mixed boolean operators has no parens' do expect_offense(<<~RUBY) a && b || c ^^^^^^ Wrap expressions with varying precedence with parentheses to avoid ambiguity. a || b && c ^^^^^^ Wrap expressions with varying precedence with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (a && b) || c a || (b && c) RUBY end it 'registers an offense for expressions containing booleans and operators' do expect_offense(<<~RUBY) a && b * c ^^^^^ Wrap expressions with varying precedence with parentheses to avoid ambiguity. a * b && c ^^^^^ Wrap expressions with varying precedence with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) a && (b * c) (a * b) && c RUBY end it 'registers an offense when the entire expression is wrapped in parentheses' do expect_offense(<<~RUBY) (a + b * c ** d) ^^^^^^ Wrap expressions with varying precedence with parentheses to avoid ambiguity. ^^^^^^^^^^ Wrap expressions with varying precedence with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (a + (b * (c ** d))) RUBY end it 'corrects a super long expression in precedence order' do expect_offense(<<~RUBY) a ** b * c / d % e + f - g << h >> i & j | k ^ l && m || n ^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] RUBY expect_correction(<<~RUBY) (((((((a ** b) * c / d % e) + f - g) << h >> i) & j) | k ^ l) && m) || n RUBY end it 'corrects a super long expression in reverse precedence order' do expect_offense(<<~RUBY) a || b && c | d ^ e & f << g >> h + i - j * k / l % n ** m ^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Wrap expressions [...] RUBY expect_correction(<<~RUBY) a || (b && (c | d ^ (e & (f << g >> (h + i - (j * k / l % (n ** m))))))) RUBY end it 'allows an operator with `and`' do expect_no_offenses(<<~RUBY) array << i and return RUBY end it 'allows an operator with `or`' do expect_no_offenses(<<~RUBY) array << i or return 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/lint/underscore_prefixed_variable_name_spec.rb
spec/rubocop/cop/lint/underscore_prefixed_variable_name_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnderscorePrefixedVariableName, :config do let(:cop_config) { { 'AllowKeywordBlockArguments' => false } } context 'when an underscore-prefixed variable is used' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method _foo = 1 ^^^^ Do not use prefix `_` for a variable that is used. puts _foo end RUBY end end context 'when non-underscore-prefixed variable is used' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method foo = 1 puts foo end RUBY end end context 'when an underscore-prefixed variable is reassigned' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method _foo = 1 _foo = 2 end RUBY end end context 'when an underscore-prefixed method argument is used' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(_foo) ^^^^ Do not use prefix `_` for a variable that is used. puts _foo end RUBY end end context 'when an underscore-prefixed block argument is used' do [true, false].each do |config| let(:cop_config) { { 'AllowKeywordBlockArguments' => config } } it 'registers an offense' do expect_offense(<<~RUBY) 1.times do |_foo| ^^^^ Do not use prefix `_` for a variable that is used. puts _foo end RUBY end end end context 'when an underscore-prefixed keyword block argument is used' do it 'registers an offense' do expect_offense(<<~RUBY) define_method(:foo) do |_foo: 'default'| ^^^^ Do not use prefix `_` for a variable that is used. puts _foo end RUBY end context 'when AllowKeywordBlockArguments is set' do let(:cop_config) { { 'AllowKeywordBlockArguments' => true } } it 'does not register an offense' do expect_no_offenses(<<~RUBY) define_method(:foo) do |_foo: 'default'| puts _foo end RUBY end end end context 'when an underscore-prefixed variable in top-level scope is used' do it 'registers an offense' do expect_offense(<<~RUBY) _foo = 1 ^^^^ Do not use prefix `_` for a variable that is used. puts _foo RUBY end end context 'when an underscore-prefixed variable is captured by a block' do it 'accepts' do expect_no_offenses(<<~RUBY) _foo = 1 1.times do _foo = 2 end RUBY end end context 'when an underscore-prefixed named capture variable is used' do it 'registers an offense' do expect_offense(<<~RUBY) /(?<_foo>\\w+)/ =~ 'FOO' ^^^^^^^^^^^^^^ Do not use prefix `_` for a variable that is used. puts _foo RUBY end end %w[super binding].each do |keyword| context "in a method calling `#{keyword}` without arguments" do context 'when an underscore-prefixed argument is not used explicitly' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method(*_) #{keyword} end RUBY end end context 'when an underscore-prefixed argument is used explicitly' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(*_) ^ Do not use prefix `_` for a variable that is used. #{keyword} puts _ end RUBY end end end context "in a method calling `#{keyword}` with arguments" do context 'when an underscore-prefixed argument is not used' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method(*_) #{keyword}(:something) end RUBY end end context 'when an underscore-prefixed argument is used explicitly' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(*_) ^ Do not use prefix `_` for a variable that is used. #{keyword}(*_) 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/lint/unified_integer_spec.rb
spec/rubocop/cop/lint/unified_integer_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnifiedInteger, :config do shared_examples 'registers an offense' do |klass| context 'target ruby version < 2.4', :ruby23, unsupported_on: :prism do context "when #{klass}" do context 'without any decorations' do it 'registers an offense but does not correct' do expect_offense(<<~RUBY, klass: klass) 1.is_a?(%{klass}) ^{klass} Use `Integer` instead of `#{klass}`. RUBY expect_no_corrections end end context 'when explicitly specified as toplevel constant' do it 'registers an offense' do expect_offense(<<~RUBY, klass: klass) 1.is_a?(::%{klass}) ^^^{klass} Use `Integer` instead of `#{klass}`. RUBY expect_no_corrections end end context 'with MyNamespace' do it 'does not register an offense' do expect_no_offenses("1.is_a?(MyNamespace::#{klass})") end end end end context 'target ruby version >= 2.4', :ruby24 do context "when #{klass}" do context 'without any decorations' do it 'registers an offense' do expect_offense(<<~RUBY, klass: klass) 1.is_a?(#{klass}) ^{klass} Use `Integer` instead of `#{klass}`. RUBY expect_correction(<<~RUBY) 1.is_a?(Integer) RUBY end end context 'when explicitly specified as toplevel constant' do it 'registers an offense' do expect_offense(<<~RUBY, klass: klass) 1.is_a?(::#{klass}) ^^^{klass} Use `Integer` instead of `#{klass}`. RUBY expect_correction(<<~RUBY) 1.is_a?(::Integer) RUBY end end context 'with MyNamespace' do it 'does not register an offense' do expect_no_offenses("1.is_a?(MyNamespace::#{klass})") end end end end end it_behaves_like 'registers an offense', 'Fixnum' it_behaves_like 'registers an offense', 'Bignum' context 'when Integer' do context 'without any decorations' do it 'does not register an offense' do expect_no_offenses('1.is_a?(Integer)') end end context 'when explicitly specified as toplevel constant' do it 'does not register an offense' do expect_no_offenses('1.is_a?(::Integer)') end end context 'with MyNamespace' do it 'does not register an offense' do expect_no_offenses('1.is_a?(MyNamespace::Integer)') 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/lint/require_relative_self_path_spec.rb
spec/rubocop/cop/lint/require_relative_self_path_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RequireRelativeSelfPath, :config do it 'registers an offense when using `require_relative` with self file path argument' do expect_offense(<<~RUBY, 'foo.rb') require_relative 'foo' ^^^^^^^^^^^^^^^^^^^^^^ Remove the `require_relative` that requires itself. require_relative 'bar' RUBY expect_correction(<<~RUBY) require_relative 'bar' RUBY end it 'registers an offense when using `require_relative` with self file path argument (with ext)' do expect_offense(<<~RUBY, 'foo.rb') require_relative 'foo.rb' ^^^^^^^^^^^^^^^^^^^^^^^^^ Remove the `require_relative` that requires itself. require_relative 'bar' RUBY expect_correction(<<~RUBY) require_relative 'bar' RUBY end it 'does not register an offense when using `require_relative` without self file path argument' do expect_no_offenses(<<~RUBY, 'foo.rb') require_relative 'bar' RUBY end it 'does not register an offense when using `require_relative` without argument' do expect_no_offenses(<<~RUBY, 'foo.rb') require_relative RUBY end it 'does not register an offense when the filename is the same but the extension does not match' do expect_no_offenses(<<~RUBY, 'foo.rb') require_relative 'foo.racc' RUBY end it 'does not register an offense when using a variable as an argument of `require_relative`' do expect_no_offenses(<<~RUBY, 'foo.rb') Dir['test/**/test_*.rb'].each { |f| require_relative f } 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/lint/ordered_magic_comments_spec.rb
spec/rubocop/cop/lint/ordered_magic_comments_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::OrderedMagicComments, :config do it 'registers an offense and corrects when an `encoding` magic comment ' \ 'does not precede all other magic comments' do expect_offense(<<~RUBY) # frozen_string_literal: true # encoding: ascii ^^^^^^^^^^^^^^^^^ The encoding magic comment should precede all other magic comments. RUBY expect_correction(<<~RUBY) # encoding: ascii # frozen_string_literal: true RUBY end it 'registers an offense and corrects when `coding` magic comment ' \ 'does not precede all other magic comments' do expect_offense(<<~RUBY) # frozen_string_literal: true # coding: ascii ^^^^^^^^^^^^^^^ The encoding magic comment should precede all other magic comments. RUBY expect_correction(<<~RUBY) # coding: ascii # frozen_string_literal: true RUBY end it 'registers an offense and corrects when `-*- encoding : ascii-8bit -*-` ' \ 'magic comment does not precede all other magic comments' do expect_offense(<<~RUBY) # frozen_string_literal: true # -*- encoding : ascii-8bit -*- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The encoding magic comment should precede all other magic comments. RUBY expect_correction(<<~RUBY) # -*- encoding : ascii-8bit -*- # frozen_string_literal: true RUBY end it 'registers an offense and corrects when using `frozen_string_literal` ' \ 'magic comment is next of shebang' do expect_offense(<<~RUBY) #!/usr/bin/env ruby # frozen_string_literal: true # encoding: ascii ^^^^^^^^^^^^^^^^^ The encoding magic comment should precede all other magic comments. RUBY expect_correction(<<~RUBY) #!/usr/bin/env ruby # encoding: ascii # frozen_string_literal: true RUBY end it 'does not register an offense when using `encoding` magic comment is first line' do expect_no_offenses(<<~RUBY) # encoding: ascii # frozen_string_literal: true RUBY end it 'does not register an offense when using `encoding` magic comment is next of shebang' do expect_no_offenses(<<~RUBY) #!/usr/bin/env ruby # encoding: ascii # frozen_string_literal: true RUBY end it 'does not register an offense when using `encoding` magic comment only' do expect_no_offenses(<<~RUBY) # encoding: ascii RUBY end it 'does not register an offense when using `frozen_string_literal` magic comment only' do expect_no_offenses(<<~RUBY) # frozen_string_literal: true RUBY end it 'does not register an offense when using ' \ '`encoding: Encoding::SJIS` Hash notation after' \ '`frozen_string_literal` magic comment' do expect_no_offenses(<<~RUBY) # frozen_string_literal: true x = { encoding: Encoding::SJIS } puts x RUBY end it 'does not register an offense when comment text `# encoding: ISO-8859-1` is embedded within ' \ 'example code as source code comment' do expect_no_offenses(<<~RUBY) # frozen_string_literal: true # eval('# encoding: ISO-8859-1') RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/disjunctive_assignment_in_constructor_spec.rb
spec/rubocop/cop/lint/disjunctive_assignment_in_constructor_spec.rb
# frozen_string_literal: true RSpec.describe( RuboCop::Cop::Lint::DisjunctiveAssignmentInConstructor, :config ) do context 'empty constructor' do it 'accepts' do expect_no_offenses(<<~RUBY) class Banana def initialize end end RUBY end end context 'constructor does not have disjunctive assignment' do it 'accepts' do expect_no_offenses(<<~RUBY) class Banana def initialize @delicious = true end end RUBY end end context 'constructor has disjunctive assignment' do context 'LHS is lvar' do it 'accepts' do expect_no_offenses(<<~RUBY) class Banana def initialize delicious ||= true end end RUBY end end context 'LHS is ivar' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class Banana def initialize @delicious ||= true ^^^ Unnecessary disjunctive assignment. Use plain assignment. end end RUBY expect_correction(<<~RUBY) class Banana def initialize @delicious = true end end RUBY end context 'constructor calls super after assignment' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class Banana def initialize @delicious ||= true ^^^ Unnecessary disjunctive assignment. Use plain assignment. super end end RUBY expect_correction(<<~RUBY) class Banana def initialize @delicious = true super end end RUBY end end context 'constructor calls super before disjunctive assignment' do it 'accepts' do expect_no_offenses(<<~RUBY) class Banana def initialize super @delicious ||= true end end RUBY end end context 'constructor calls any method before disjunctive assignment' do it 'accepts' do expect_no_offenses(<<~RUBY) class Banana def initialize # With the limitations of static analysis, it's very difficult # to determine, after this method call, whether the disjunctive # assignment is necessary or not. absolutely_any_method @delicious ||= true end end RUBY end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/mixed_case_range_spec.rb
spec/rubocop/cop/lint/mixed_case_range_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::MixedCaseRange, :config do let(:message) do 'Ranges from upper to lower case ASCII letters may include unintended ' \ 'characters. Instead of `A-z` (which also includes several symbols) ' \ 'specify each range individually: `A-Za-z` and individually specify any symbols.' end it 'registers an offense for an overly broad character range' do expect_offense(<<~RUBY) foo = 'A'..'z' ^^^^^^^^ #{message} RUBY end it 'registers an offense for an overly broad exclusive character range' do expect_offense(<<~RUBY) foo = 'A'...'z' ^^^^^^^^^ #{message} RUBY end it 'does not register an offense for an acceptable range' do expect_no_offenses(<<~RUBY) foo = 'A'..'Z' RUBY end it 'does not register an offense when the number of characters at the start of range is other than 1' do expect_no_offenses(<<~RUBY) foo = 'aa'..'z' RUBY end it 'does not register an offense when the number of characters at the end of range is other than 1' do expect_no_offenses(<<~RUBY) foo = 'a'..'zz' RUBY end context 'ruby > 2.6', :ruby27 do it 'does not register an offense for a beginless range' do expect_no_offenses(<<~RUBY) (..'z') RUBY end end it 'does not register an offense for an endless range' do expect_no_offenses(<<~RUBY) ('a'..) RUBY end it 'registers an offense for an overly broad range' do expect_offense(<<~RUBY) foo = /[A-z]/ ^^^ #{message} RUBY expect_correction(<<~RUBY) foo = /[A-Za-z]/ RUBY end it 'registers an offense for an overly broad range between interpolations' do expect_offense(<<~'RUBY'.sub(/\#{message}/, message)) foo = /[#{A-z}A-z#{y}]/ ^^^ #{message} RUBY expect_correction(<<~'RUBY') foo = /[#{A-z}A-Za-z#{y}]/ RUBY end it 'registers an offense for each of multiple unsafe ranges' do expect_offense(<<~RUBY) foo = /[_A-b;Z-a!]/ ^^^ #{message} ^^^ #{message} RUBY expect_correction(<<~RUBY) foo = /[_A-Za-b;Za!]/ RUBY end it 'registers an offense for each of multiple unsafe ranges at the correct place' do expect_offense(<<~RUBY) foo = %r{[A-z]+/[A-z]+|all}.freeze || /_[A-z]/ ^^^ #{message} ^^^ #{message} ^^^ #{message} RUBY expect_correction(<<~RUBY) foo = %r{[A-Za-z]+/[A-Za-z]+|all}.freeze || /_[A-Za-z]/ RUBY end it 'registers an offense in an extended regexp' do expect_offense(<<~RUBY) foo = / A-z # not a character class [A-z]_..._ ^^^ #{message} /x RUBY expect_correction(<<~RUBY) foo = / A-z # not a character class [A-Za-z]_..._ /x RUBY end it 'registers an offense for negated ranges' do expect_offense(<<~RUBY) foo = /[^G-f]/ ^^^ #{message} RUBY expect_correction(<<~RUBY) foo = /[^G-Za-f]/ RUBY end it 'registers an offense for unsafe range with possible octal digits following' do expect_offense(<<~RUBY) foo = /[_A-z123]/ ^^^ #{message} RUBY expect_correction(<<~RUBY) foo = /[_A-Za-z123]/ RUBY end it 'registers an offense for unsafe range with full octal escape preceding' do expect_offense(<<~'RUBY'.sub(/\#{message}/, message)) foo = /[\001A-z123]/ ^^^ #{message} RUBY expect_correction(<<~'RUBY') foo = /[\001A-Za-z123]/ RUBY end it 'registers an offense for unsafe range with short octal escape preceding' do expect_offense(<<~'RUBY'.sub(/\#{message}/, message)) foo = /[\1A-z123]/ ^^^ #{message} RUBY expect_correction(<<~'RUBY') foo = /[\1A-Za-z123]/ RUBY end it 'does not register an offense for accepted ranges' do expect_no_offenses(<<~RUBY) foo = /[_a-zA-Z0-9;]/ RUBY end it 'does not register an offense with escaped octal opening bound' do expect_no_offenses(<<~'RUBY') foo = /[\101-z]/ RUBY end it 'does not register an offense with escaped octal closing bound' do expect_no_offenses(<<~'RUBY') foo = /[A-\172]/ RUBY end it 'does not register an offense with opening hex bound' do expect_no_offenses(<<~'RUBY') foo = /[\x01-z]/ RUBY end it 'does not register an offense with closing hex bound' do expect_no_offenses(<<~'RUBY') foo = /[A-\x7a]/ RUBY end it 'does not register an offense with escaped hex bounds' do expect_no_offenses(<<~'RUBY') foo = /[\x41-\x7a]/ RUBY end it 'does not register an offense with tricky escaped hex bounds' do expect_no_offenses(<<~'RUBY') foo = /[\xA-\xf]/ RUBY end it 'does not register an offense with escaped unicode bounds' do expect_no_offenses(<<~'RUBY') foo = /[\u0041-\u007a]/ RUBY end it 'does not register an offense with control characters' do expect_no_offenses(<<~'RUBY') foo = /[\C-A-\cz]/ RUBY end it 'does not register an offense with escaped dash (not a range)' do expect_no_offenses(<<~'RUBY') foo = /[A\-z]/ RUBY end it 'does not register an offense with nested character class' do expect_no_offenses(<<~RUBY) foo = /[a-[bc]]/ RUBY end it 'does not register an offense with `/[[ ]]/' do expect_no_offenses(<<~RUBY) /[[ ]]/ RUBY end it 'does not register an offense when a character between `Z` and `a` is at the start of range.' do expect_no_offenses(<<~RUBY) foo = /[_-a]/ RUBY end it 'does not register an offense when a character between `Z` and `a` is at the end of range.' do expect_no_offenses(<<~RUBY) foo = /[A-_]/ RUBY end it 'does not register an offense with invalid byte sequence in UTF-8' do expect_no_offenses(<<~'RUBY') foo = /[\–]/ RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/boolean_symbol_spec.rb
spec/rubocop/cop/lint/boolean_symbol_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::BooleanSymbol, :config do it 'registers an offense when using `:true`' do expect_offense(<<~RUBY) :true ^^^^^ Symbol with a boolean name - you probably meant to use `true`. RUBY expect_correction(<<~RUBY) true RUBY end it 'registers an offense when using `:false`' do expect_offense(<<~RUBY) :false ^^^^^^ Symbol with a boolean name - you probably meant to use `false`. RUBY expect_correction(<<~RUBY) false RUBY end context 'when using the rocket hash syntax' do it 'registers an offense when using a boolean symbol key' do expect_offense(<<~RUBY) { :false => 42 } ^^^^^^ Symbol with a boolean name - you probably meant to use `false`. RUBY expect_correction(<<~RUBY) { false => 42 } RUBY end end context 'when using the new hash syntax' do it 'registers an offense when using `true:`' do expect_offense(<<~RUBY) { true: 'Foo' } ^^^^ Symbol with a boolean name - you probably meant to use `true`. RUBY expect_correction(<<~RUBY) { true => 'Foo' } RUBY end it 'registers an offense when using `false:`' do expect_offense(<<~RUBY) { false: :bar } ^^^^^ Symbol with a boolean name - you probably meant to use `false`. RUBY expect_correction(<<~RUBY) { false => :bar } RUBY end it 'registers an offense when using `key: :false`' do expect_offense(<<~RUBY) { false: :false } ^^^^^^ Symbol with a boolean name - you probably meant to use `false`. ^^^^^ Symbol with a boolean name - you probably meant to use `false`. RUBY expect_correction(<<~RUBY) { false => false } RUBY end end it 'does not register an offense when using regular symbol' do expect_no_offenses(<<~RUBY) :something RUBY end it 'does not register an offense when using `true`' do expect_no_offenses(<<~RUBY) true RUBY end it 'does not register an offense when using `false`' do expect_no_offenses(<<~RUBY) false RUBY end it 'does not register an offense when used inside percent-literal symbol array' do expect_no_offenses(<<~RUBY) %i[foo false] 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/lint/safe_navigation_chain_spec.rb
spec/rubocop/cop/lint/safe_navigation_chain_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SafeNavigationChain, :config do shared_examples 'accepts' do |name, code| it "accepts usages of #{name}" do expect_no_offenses(code) end end context 'TargetRubyVersion >= 2.3', :ruby23 do [ ['ordinary method chain', 'x.foo.bar.baz'], ['ordinary method chain with argument', 'x.foo(x).bar(y).baz(z)'], ['method chain with safe navigation only', 'x&.foo&.bar&.baz'], ['method chain with safe navigation only with argument', 'x&.foo(x)&.bar(y)&.baz(z)'], ['safe navigation at last only', 'x.foo.bar&.baz'], ['safe navigation at last only with argument', 'x.foo(x).bar(y)&.baz(z)'], ['safe navigation with == operator', 'x&.foo == bar'], ['safe navigation with === operator', 'x&.foo === bar'], ['safe navigation with || operator', 'x&.foo || bar'], ['safe navigation with && operator', 'x&.foo && bar'], ['safe navigation with | operator', 'x&.foo | bar'], ['safe navigation with & operator', 'x&.foo & bar'], ['safe navigation with `nil?` method', 'x&.foo.nil?'], ['safe navigation with `present?` method', 'x&.foo.present?'], ['safe navigation with `blank?` method', 'x&.foo.blank?'], ['safe navigation with `try` method', 'a&.b.try(:c)'], ['safe navigation with assignment method', 'x&.foo = bar'], ['safe navigation with self assignment method', 'x&.foo += bar'], ['safe navigation with `to_d` method', 'x&.foo.to_d'], ['safe navigation with `in?` method', 'x&.foo.in?([:baz, :qux])'], ['safe navigation with `+@` method', '+str&.to_i'], ['safe navigation with `-@` method', '-str&.to_i'] ].each do |name, code| it_behaves_like 'accepts', name, code end it 'registers an offense for ordinary method call exists after safe navigation method call' do expect_offense(<<~RUBY) x&.foo.bar ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.bar RUBY end it 'registers an offense for ordinary method call exists after ' \ 'safe navigation method call with an argument' do expect_offense(<<~RUBY) x&.foo(x).bar(y) ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo(x)&.bar(y) RUBY end it 'registers an offense for ordinary method chain exists after safe navigation method call' do expect_offense(<<~RUBY) something x&.foo.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) something x&.foo&.bar&.baz RUBY end it 'registers an offense for ordinary method chain exists after safe navigation leading dot method call' do expect_offense(<<~RUBY) x&.foo &.bar .baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo &.bar &.baz RUBY end it 'registers an offense for ordinary method chain exists after ' \ 'safe navigation method call with an argument' do expect_offense(<<~RUBY) x&.foo(x).bar(y).baz(z) ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo(x)&.bar(y)&.baz(z) RUBY end it 'registers an offense for ordinary method chain exists after ' \ 'safe navigation method call with a block-pass' do expect_offense(<<~RUBY) something x&.select(&:foo).bar ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) something x&.select(&:foo)&.bar RUBY end it 'registers an offense for ordinary method chain exists after ' \ 'safe navigation method call with a block' do expect_offense(<<~RUBY) something x&.select { |x| foo(x) }.bar ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) something x&.select { |x| foo(x) }&.bar RUBY end it 'registers an offense for safe navigation with < operator' do expect_offense(<<~RUBY) x&.foo < bar ^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&. < bar RUBY end it 'registers an offense for safe navigation with > operator' do expect_offense(<<~RUBY) x&.foo > bar ^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&. > bar RUBY end it 'registers an offense for safe navigation with <= operator' do expect_offense(<<~RUBY) x&.foo <= bar ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&. <= bar RUBY end it 'registers an offense for safe navigation with >= operator' do expect_offense(<<~RUBY) x&.foo >= bar ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&. >= bar RUBY end it 'registers an offense when a safe navigation operator is used with a method call as both the LHS and RHS operands of `&&` for the same receiver' do expect_offense(<<~RUBY) x&.foo.bar && x&.foo.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.bar && x&.foo.baz RUBY end it 'does not register an offense when a safe navigation operator is used with a method call as the RHS operand of `&&` for the same receiver' do expect_no_offenses(<<~RUBY) x&.foo&.bar && x&.foo.baz RUBY end it 'registers an offense when a safe navigation operator is used with a method call as the RHS operand of `&&` for a different receiver' do expect_offense(<<~RUBY) x&.foo&.bar && y&.foo.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.bar && y&.foo&.baz RUBY end it 'registers an offense when a safe navigation operator is used with a method call as both the LHS and RHS operands of `||` for the same receiver' do expect_offense(<<~RUBY) x&.foo.bar || x&.foo.baz ^^^^ Do not chain ordinary method call after safe navigation operator. ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.bar || x&.foo&.baz RUBY end it 'registers an offense when a safe navigation operator is used with a method call as the RHS operand of `||` for the same receiver' do expect_offense(<<~RUBY) x&.foo&.bar || x&.foo.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.bar || x&.foo&.baz RUBY end it 'registers an offense when a safe navigation operator is used with a method call as the RHS operand of `||` for a different receiver' do expect_offense(<<~RUBY) x&.foo&.bar || y&.foo.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.bar || y&.foo&.baz RUBY end it 'registers an offense for safe navigation with a method call as an expression of `&&` operand' do expect_offense(<<~RUBY) do_something && x&.foo.bar ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) do_something && x&.foo&.bar RUBY end it 'registers an offense for safe navigation with `>=` operator as an expression of `&&` operand' do expect_offense(<<~RUBY) do_something && x&.foo >= bar ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) do_something && (x&.foo&. >= bar) RUBY end it 'registers an offense for safe navigation with `>=` operator as an expression of `||` operand' do expect_offense(<<~RUBY) do_something || x&.foo >= bar ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) do_something || (x&.foo&. >= bar) RUBY end it 'registers an offense for safe navigation with `>=` operator as an expression of `and` operand' do expect_offense(<<~RUBY) do_something and x&.foo >= bar ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) do_something and x&.foo&. >= bar RUBY end it 'registers an offense for safe navigation with `>=` operator as an expression of `or` operand' do expect_offense(<<~RUBY) do_something or x&.foo >= bar ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) do_something or x&.foo&. >= bar RUBY end it 'registers an offense for safe navigation with `>=` operator as an expression of comparison method operand' do expect_offense(<<~RUBY) do_something == x&.foo >= bar ^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) do_something == (x&.foo&. >= bar) RUBY end it 'registers an offense for safe navigation with + operator' do expect_offense(<<~RUBY) x&.foo + bar ^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&. + bar RUBY end it 'registers an offense for safe navigation with [] operator' do expect_offense(<<~RUBY) x&.foo[bar] ^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.[](bar) RUBY end it 'registers an offense for safe navigation with [] operator followed by method chain' do expect_offense(<<~RUBY) x&.foo[bar].to_s ^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.[](bar).to_s RUBY end it 'registers an offense for safe navigation with []= operator' do expect_offense(<<~RUBY) x&.foo[bar] = baz ^^^^^^^^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.[]=(bar, baz) RUBY end it 'registers an offense for [] operator followed by a safe navigation and method chain' do expect_offense(<<~RUBY) foo[bar]&.x.y ^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) foo[bar]&.x&.y RUBY end it 'registers an offense for safe navigation on the right-hand side of the `+`' do expect_offense(<<~RUBY) x + foo&.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x + foo&.bar&.baz RUBY end it 'registers an offense for safe navigation on the right-hand side of the `-`' do expect_offense(<<~RUBY) x - foo&.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x - foo&.bar&.baz RUBY end it 'registers an offense for safe navigation on the right-hand side of the `*`' do expect_offense(<<~RUBY) x * foo&.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x * foo&.bar&.baz RUBY end it 'registers an offense for safe navigation on the right-hand side of the `/`' do expect_offense(<<~RUBY) x / foo&.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x / foo&.bar&.baz RUBY end it 'registers an offense for safe navigation on the left-hand side of a `-` operator when inside an array' do expect_offense(<<~RUBY) [foo, a&.baz - 1] ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) [foo, (a&.baz&. - 1)] RUBY end it 'registers an offense for safe navigation on the left-hand side of a `-` operator when inside a hash' do expect_offense(<<~RUBY) { foo: a&.baz - 1 } ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) { foo: (a&.baz&. - 1) } RUBY end context 'proper highlighting' do it 'when there are methods before' do expect_offense(<<~RUBY) something x&.foo.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) something x&.foo&.bar&.baz RUBY end it 'when there are methods after' do expect_offense(<<~RUBY) x&.foo.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. something RUBY expect_correction(<<~RUBY) x&.foo&.bar&.baz something RUBY end it 'when in a method' do expect_offense(<<~RUBY) def something x&.foo.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. end RUBY expect_correction(<<~RUBY) def something x&.foo&.bar&.baz end RUBY end it 'when in a begin' do expect_offense(<<~RUBY) begin x&.foo.bar.baz ^^^^ Do not chain ordinary method call after safe navigation operator. end RUBY expect_correction(<<~RUBY) begin x&.foo&.bar&.baz end RUBY end it 'when used with a modifier if' do expect_offense(<<~RUBY) x&.foo.bar.baz if something ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) x&.foo&.bar&.baz if something RUBY end end end context '>= Ruby 2.7', :ruby27 do it 'registers an offense for ordinary method chain exists after ' \ 'safe navigation method call with a block using numbered parameter' do expect_offense(<<~RUBY) something x&.select { foo(_1) }.bar ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) something x&.select { foo(_1) }&.bar RUBY end end context '>= Ruby 3.4', :ruby34 do it 'registers an offense for ordinary method chain exists after ' \ 'safe navigation method call with a block using `it` parameter' do expect_offense(<<~RUBY) something x&.select { foo(it) }.bar ^^^^ Do not chain ordinary method call after safe navigation operator. RUBY expect_correction(<<~RUBY) something x&.select { foo(it) }&.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/lint/float_out_of_range_spec.rb
spec/rubocop/cop/lint/float_out_of_range_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::FloatOutOfRange, :config do it 'does not register an offense for 0.0' do expect_no_offenses('0.0') end it 'does not register an offense for tiny little itty bitty floats' do expect_no_offenses('1.1e-100') end it 'does not register an offense for respectably sized floats' do expect_no_offenses('55.7e89') end context 'on whopping big floats which tip the scales' do it 'registers an offense' do expect_offense(<<~RUBY) 9.9999e999 ^^^^^^^^^^ Float out of range. RUBY end end context 'on floats so close to zero that nobody can tell the difference' do it 'registers an offense' do expect_offense(<<~RUBY) 1.0e-400 ^^^^^^^^ Float out of range. 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/lint/empty_expression_spec.rb
spec/rubocop/cop/lint/empty_expression_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyExpression, :config do context 'when used as a standalone expression' do it 'registers an offense' do expect_offense(<<~RUBY) () ^^ Avoid empty expressions. RUBY end context 'with nested empty expressions' do it 'registers an offense' do expect_offense(<<~RUBY) (()) ^^ Avoid empty expressions. RUBY end end end context 'when used in a condition' do it 'registers an offense inside `if`' do expect_offense(<<~RUBY) if (); end ^^ Avoid empty expressions. RUBY end it 'registers an offense inside `elsif`' do expect_offense(<<~RUBY) if foo 1 elsif () ^^ Avoid empty expressions. 2 end RUBY end it 'registers an offense inside `case`' do expect_offense(<<~RUBY) case () ^^ Avoid empty expressions. when :foo then 1 end RUBY end it 'registers an offense inside `when`' do expect_offense(<<~RUBY) case foo when () then 1 ^^ Avoid empty expressions. end RUBY end it 'registers an offense in the condition of a ternary operator' do expect_offense(<<~RUBY) () ? true : false ^^ Avoid empty expressions. RUBY end it 'registers an offense in the return value of a ternary operator' do expect_offense(<<~RUBY) foo ? () : bar ^^ Avoid empty expressions. RUBY end end context 'when used as a return value' do it 'registers an offense in the return value of a method' do expect_offense(<<~RUBY) def foo () ^^ Avoid empty expressions. end RUBY end it 'registers an offense in the return value of a condition' do expect_offense(<<~RUBY) if foo () ^^ Avoid empty expressions. end RUBY end it 'registers an offense in the return value of a case statement' do expect_offense(<<~RUBY) case foo when :bar then () ^^ Avoid empty expressions. end RUBY end end context 'when used as an assignment' do it 'registers an offense for the assigned value' do expect_offense(<<~RUBY) foo = () ^^ Avoid empty expressions. 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/lint/float_comparison_spec.rb
spec/rubocop/cop/lint/float_comparison_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::FloatComparison, :config do it 'registers an offense when comparing with float' do expect_offense(<<~RUBY) x == 0.1 ^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. 0.1 == x ^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. x != 0.1 ^^^^^^^^ Avoid inequality comparisons of floats as they are unreliable. 0.1 != x ^^^^^^^^ Avoid inequality comparisons of floats as they are unreliable. x.eql?(0.1) ^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. 0.1.eql?(x) ^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. RUBY end it 'registers an offense when comparing with float returning method' do expect_offense(<<~RUBY) x == Float(1) ^^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. x == '0.1'.to_f ^^^^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. x == 1.fdiv(2) ^^^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. RUBY end it 'registers an offense when comparing with arithmetic operator on floats' do expect_offense(<<~RUBY) x == 0.1 + y ^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. x == y + Float('0.1') ^^^^^^^^^^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. x == y + z * (foo(arg) + '0.1'.to_f) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. RUBY end it 'registers an offense when comparing with method on float receiver' do expect_offense(<<~RUBY) x == 0.1.abs ^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. RUBY end it 'does not register an offense when comparing with float method ' \ 'that can return numeric and returns integer' do expect_no_offenses(<<~RUBY) x == 1.1.ceil RUBY end it 'registers an offense when comparing with float method ' \ 'that can return numeric and returns float' do expect_offense(<<~RUBY) x == 1.1.ceil(1) ^^^^^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. RUBY end it 'does not register an offense when comparing with float using epsilon' do expect_no_offenses(<<~RUBY) (x - 0.1) < epsilon RUBY end it 'does not register an offense when comparing with rational literal' do expect_no_offenses(<<~RUBY) value == 0.2r RUBY end it 'does not register an offense when comparing against zero' do expect_no_offenses(<<~RUBY) x == 0.0 x.to_f == 0 x.to_f.abs == 0.0 x != 0.0 x.to_f != 0 x.to_f.zero? x.to_f.nonzero? RUBY end it 'does not register an offense when comparing against nil' do expect_no_offenses(<<~RUBY) Float('not_a_float', exception: false) == nil nil != Float('not_a_float', exception: false) RUBY end it 'does not register an offense when comparing with multiple arguments' do expect_no_offenses(<<~RUBY) x.==(0.1, 0.2) x.!=(0.1, 0.2) x.eql?(0.1, 0.2) x.equal?(0.1, 0.2) RUBY end it 'registers an offense for `eql?` called with safe navigation' do expect_offense(<<~RUBY) x&.eql?(0.1) ^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. RUBY end it 'registers an offense for `equal?` called with safe navigation' do expect_offense(<<~RUBY) x&.equal?(0.1) ^^^^^^^^^^^^^^ Avoid equality comparisons of floats as they are unreliable. RUBY end it 'registers an offense when using float in case statement' do expect_offense(<<~RUBY) case value when 1.0 ^^^ Avoid float literal comparisons in case statements as they are unreliable. foo when 2.0 ^^^ Avoid float literal comparisons in case statements as they are unreliable. bar end RUBY end it 'registers an offense when using float in case statement with multiple conditions' do expect_offense(<<~RUBY) case value when 1.0, 2.0 ^^^ Avoid float literal comparisons in case statements as they are unreliable. ^^^ Avoid float literal comparisons in case statements as they are unreliable. foo end RUBY end it 'does not register an offense when using zero float in case statement' do expect_no_offenses(<<~RUBY) case value when 0.0 foo end RUBY end it 'does not register an offense when using non-float in case statement' do expect_no_offenses(<<~RUBY) case value when 1 foo when 'string' bar end RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/no_return_in_begin_end_blocks_spec.rb
spec/rubocop/cop/lint/no_return_in_begin_end_blocks_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NoReturnInBeginEndBlocks, :config do shared_examples 'rejects return inside a block' do |operator| it "rejects a return statement inside a block when using #{operator} for local variable" do expect_offense(<<~RUBY) some_value = 10 some_value #{operator} begin return 1 if rand(1..2).odd? ^^^^^^^^ Do not `return` in `begin..end` blocks in assignment contexts. 2 end RUBY end it "rejects a return statement inside a block when using #{operator} for instance variable" do expect_offense(<<~RUBY) @some_value #{operator} begin return 1 if rand(1..2).odd? ^^^^^^^^ Do not `return` in `begin..end` blocks in assignment contexts. 2 end RUBY end it "rejects a return statement inside a block when using #{operator} for class variable" do expect_offense(<<~RUBY) @@some_value #{operator} begin return 1 if rand(1..2).odd? ^^^^^^^^ Do not `return` in `begin..end` blocks in assignment contexts. 2 end RUBY end it "rejects a return statement inside a block when using #{operator} for global variable" do expect_offense(<<~RUBY) $some_value #{operator} begin return 1 if rand(1..2).odd? ^^^^^^^^ Do not `return` in `begin..end` blocks in assignment contexts. 2 end RUBY end it "rejects a return statement inside a block when using #{operator} for constant" do expect_offense(<<~RUBY) CONST #{operator} begin return 1 if rand(1..2).odd? ^^^^^^^^ Do not `return` in `begin..end` blocks in assignment contexts. 2 end RUBY end end shared_examples 'accepts a block with no return' do |operator| it "accepts a block with no return when using #{operator} for local variable" do expect_no_offenses(<<~RUBY) some_value #{operator} begin if rand(1..2).odd? "odd number" else "even number" end end RUBY end it "accepts a block with no return when using #{operator} for instance variable" do expect_no_offenses(<<~RUBY) @some_value #{operator} begin if rand(1..2).odd? "odd number" else "even number" end end RUBY end it "accepts a block with no return when using #{operator} for class variable" do expect_no_offenses(<<~RUBY) @@some_value #{operator} begin if rand(1..2).odd? "odd number" else "even number" end end RUBY end it "accepts a block with no return when using #{operator} for global variable" do expect_no_offenses(<<~RUBY) $some_value #{operator} begin if rand(1..2).odd? "odd number" else "even number" end end RUBY end it "accepts a block with no return when using #{operator} for constant" do expect_no_offenses(<<~RUBY) CONST #{operator} begin if rand(1..2).odd? "odd number" else "even number" end end RUBY end end %w[= += -= *= /= **= ||=].each do |operator| it_behaves_like 'rejects return inside a block', operator it_behaves_like 'accepts a block with no return', operator end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/literal_as_condition_spec.rb
spec/rubocop/cop/lint/literal_as_condition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::LiteralAsCondition, :config do %w(1 2.0 [1] {} :sym :"#{a}").each do |lit| it "registers an offense for truthy literal #{lit} in if" do expect_offense(<<~RUBY, lit: lit) if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for truthy literal #{lit} in if-else" do expect_offense(<<~RUBY, lit: lit) if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top else foo end RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for truthy literal #{lit} in if-elsif" do expect_offense(<<~RUBY, lit: lit) if condition top elsif %{lit} ^{lit} Literal `#{lit}` appeared as a condition. foo end RUBY expect_correction(<<~RUBY) if condition top else foo end RUBY end it 'registers offenses for truthy literals in both the branches in `if`' do expect_offense(<<~RUBY, lit: lit) if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. x = 1 elsif %{lit} ^{lit} Literal `#{lit}` appeared as a condition. x = 2 end RUBY expect_correction(<<~RUBY) x = 1 RUBY end it "registers an offense for truthy literal #{lit} in if-elsif-else" do expect_offense(<<~RUBY, lit: lit) if condition top elsif %{lit} ^{lit} Literal `#{lit}` appeared as a condition. foo else bar end RUBY expect_correction(<<~RUBY) if condition top else foo end RUBY end it "registers an offense for truthy literal #{lit} in if-elsif-else and preserves comments" do expect_offense(<<~RUBY, lit: lit) if condition top # comment 1 elsif %{lit} ^{lit} Literal `#{lit}` appeared as a condition. foo # comment 2 else bar end RUBY expect_correction(<<~RUBY) if condition top # comment 1 else foo # comment 2 end RUBY end it "registers an offense for truthy literal #{lit} in modifier if" do expect_offense(<<~RUBY, lit: lit) top if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for truthy literal #{lit} in ternary" do expect_offense(<<~RUBY, lit: lit) %{lit} ? top : bar ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for truthy literal #{lit} in unless" do expect_offense(<<~RUBY, lit: lit) unless %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) RUBY end it "registers an offense for truthy literal #{lit} in modifier unless" do expect_offense(<<~RUBY, lit: lit) top unless %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) RUBY end it "registers an offense for truthy literal #{lit} in while" do expect_offense(<<~RUBY, lit: lit) while %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) while true top end RUBY end it "registers an offense for truthy literal #{lit} in post-loop while" do expect_offense(<<~RUBY, lit: lit) begin top end while %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) begin top end while true RUBY end it "registers an offense for truthy literal #{lit} in until" do expect_offense(<<~RUBY, lit: lit) until %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) RUBY end it "registers an offense for truthy literal #{lit} in post-loop until" do expect_offense(<<~RUBY, lit: lit) begin top end until %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for literal #{lit} in case" do expect_offense(<<~RUBY, lit: lit) case %{lit} ^{lit} Literal `#{lit}` appeared as a condition. when x then top end RUBY expect_no_corrections end it "registers an offense for literal #{lit} in a when " \ 'of a case without anything after case keyword' do expect_offense(<<~RUBY, lit: lit) case when %{lit} then top ^{lit} Literal `#{lit}` appeared as a condition. end RUBY expect_no_corrections end it "accepts literal #{lit} in a when of a case with something after case keyword" do expect_no_offenses(<<~RUBY) case x when #{lit} then top end RUBY end context '>= Ruby 2.7', :ruby27 do it "accepts an offense for literal #{lit} in case match with a match var" do expect_no_offenses(<<~RUBY) case %{lit} in x then top end RUBY end it "registers an offense for literal #{lit} in case match without a match var" do expect_offense(<<~RUBY, lit: lit) case %{lit} ^{lit} Literal `#{lit}` appeared as a condition. in CONST then top end RUBY expect_no_corrections end it "accepts literal #{lit} in a when of a case match" do expect_no_offenses(<<~RUBY) case x in #{lit} then top end RUBY end end it "registers an offense for truthy literal #{lit} on the lhs of &&" do expect_offense(<<~RUBY, lit: lit) if %{lit} && x ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) if x top end RUBY end it "registers an offense for truthy literal #{lit} on the lhs of && with a truthy literal rhs" do expect_offense(<<~RUBY, lit: lit) if %{lit} && true ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) top RUBY end it "does not register an offense for truthy literal #{lit} on the rhs of &&" do expect_no_offenses(<<~RUBY) if x && %{lit} top end RUBY end it "registers an offense for truthy literal #{lit} in complex cond" do expect_offense(<<~RUBY, lit: lit) if x && !(%{lit} && a) && y && z ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) if x && !(a) && y && z top end RUBY end it "registers an offense for literal #{lit} in !" do expect_offense(<<~RUBY, lit: lit) if !%{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_no_corrections end it "accepts literal #{lit} if it's not an and/or operand" do expect_no_offenses(<<~RUBY) if test(#{lit}) top end RUBY end it "accepts literal #{lit} in non-toplevel and/or as an `if` condition" do expect_no_offenses(<<~RUBY) if (a || #{lit}).something top end RUBY end it "accepts literal #{lit} in non-toplevel and/or as a `case` condition" do expect_no_offenses(<<~RUBY) case a || #{lit} when b top end RUBY end it "registers an offense for `!#{lit}`" do expect_offense(<<~RUBY, lit: lit) !%{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_no_corrections end it "registers an offense for `not #{lit}`" do expect_offense(<<~RUBY, lit: lit) not(%{lit}) ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_no_corrections end end it 'accepts array literal in case, if it has non-literal elements' do expect_no_offenses(<<~RUBY) case [1, 2, x] when [1, 2, 5] then top end RUBY end it 'accepts array literal in case, if it has nested non-literal element' do expect_no_offenses(<<~RUBY) case [1, 2, [x, 1]] when [1, 2, 5] then top end RUBY end it 'registers an offense for case with a primitive array condition' do expect_offense(<<~RUBY) case [1, 2, [3, 4]] ^^^^^^^^^^^^^^ Literal `[1, 2, [3, 4]]` appeared as a condition. when [1, 2, 5] then top end RUBY expect_no_corrections end it 'accepts dstr literal in case' do expect_no_offenses(<<~'RUBY') case "#{x}" when [1, 2, 5] then top end RUBY end context '>= Ruby 2.7', :ruby27 do it 'accepts array literal in case match, if it has non-literal elements' do expect_no_offenses(<<~RUBY) case [1, 2, x] in [1, 2, 5] then top end RUBY end it 'accepts array literal in case match, if it has nested non-literal element' do expect_no_offenses(<<~RUBY) case [1, 2, [x, 1]] in [1, 2, 5] then top end RUBY end it 'registers an offense for case match with a primitive array condition' do expect_offense(<<~RUBY) case [1, 2, [3, 4]] ^^^^^^^^^^^^^^ Literal `[1, 2, [3, 4]]` appeared as a condition. in [1, 2, 5] then top end RUBY expect_no_corrections end it 'accepts an offense for case match with a match var' do expect_no_offenses(<<~RUBY) case { a: 1, b: 2, c: 3 } in a: Integer => m end RUBY end it 'accepts dstr literal in case match' do expect_no_offenses(<<~'RUBY') case "#{x}" in [1, 2, 5] then top end RUBY end end it 'accepts `true` literal in `while`' do expect_no_offenses(<<~RUBY) while true break if condition end RUBY end it 'accepts `true` literal in post-loop `while`' do expect_no_offenses(<<~RUBY) begin break if condition end while true RUBY end it 'accepts `false` literal in `until`' do expect_no_offenses(<<~RUBY) until false break if condition end RUBY end it 'accepts `false` literal in post-loop `until`' do expect_no_offenses(<<~RUBY) begin break if condition end until false RUBY end %w[nil false].each do |lit| it "registers an offense for falsey literal #{lit} in `if`" do expect_offense(<<~RUBY, lit: lit) if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) RUBY end it "registers an offense for falsey literal #{lit} in if-else" do expect_offense(<<~RUBY, lit: lit) if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top else foo end RUBY expect_correction(<<~RUBY) foo RUBY end it "registers an offense for falsey literal #{lit} in if-elsif" do expect_offense(<<~RUBY, lit: lit) if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top elsif condition foo end RUBY expect_correction(<<~RUBY) if condition foo end RUBY end it "registers an offense for falsey literal #{lit} in if-elsif-else" do expect_offense(<<~RUBY, lit: lit) if condition top elsif %{lit} ^{lit} Literal `#{lit}` appeared as a condition. foo else bar end RUBY expect_correction(<<~RUBY) if condition top else bar end RUBY end it "registers an offense for falsey literal #{lit} in if-elsif-else and preserves comments" do expect_offense(<<~RUBY, lit: lit) if condition top # comment 1 elsif %{lit} ^{lit} Literal `#{lit}` appeared as a condition. foo # comment 2 else bar # comment 3 end RUBY expect_correction(<<~RUBY) if condition top # comment 1 else bar # comment 3 end RUBY end it "registers an offense for falsey literal #{lit} in modifier `if`" do expect_offense(<<~RUBY, lit: lit) top if %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) RUBY end it "registers an offense for falsey literal #{lit} in ternary" do expect_offense(<<~RUBY, lit: lit) %{lit} ? top : bar ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) bar RUBY end it "registers an offense for falsey literal #{lit} in `unless`" do expect_offense(<<~RUBY, lit: lit) unless %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for falsey literal #{lit} in modifier `unless`" do expect_offense(<<~RUBY, lit: lit) top unless %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for falsey literal #{lit} in `while`" do expect_offense(<<~RUBY, lit: lit) while %{lit} ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) RUBY end it "registers an offense for falsey literal #{lit} in post-loop `while`" do expect_offense(<<~RUBY, lit: lit) begin top end while %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for falsey literal #{lit} in complex post-loop `while`" do expect_offense(<<~RUBY, lit: lit) begin top foo end while %{lit} ^{lit} Literal `#{lit}` appeared as a condition. RUBY expect_correction(<<~RUBY) top foo RUBY end it "registers an offense for falsey literal #{lit} in `case`" do expect_offense(<<~RUBY, lit: lit) case %{lit} ^{lit} Literal `#{lit}` appeared as a condition. when x top end RUBY end it "registers an offense for falsey literal #{lit} on the lhs of ||" do expect_offense(<<~RUBY, lit: lit) if %{lit} || x ^{lit} Literal `#{lit}` appeared as a condition. top end RUBY expect_correction(<<~RUBY) if x top end RUBY end end it 'registers an offense for `nil` literal in `until`' do expect_offense(<<~RUBY) until nil ^^^ Literal `nil` appeared as a condition. top end RUBY expect_correction(<<~RUBY) until false top end RUBY end it 'registers an offense for `nil` literal in post-loop `until`' do expect_offense(<<~RUBY) begin top end until nil ^^^ Literal `nil` appeared as a condition. RUBY expect_correction(<<~RUBY) begin top end until false RUBY end context 'void value expressions after autocorrect' do it 'registers an offense but does not autocorrect when `return` is used after `&&`' do expect_offense(<<~RUBY) def foo puts 123 && return if bar? ^^^ Literal `123` appeared as a condition. end RUBY expect_no_corrections end it 'registers an offense but does not autocorrect when `return` is used after `||`' do expect_offense(<<~RUBY) def foo puts nil || return if bar? ^^^ Literal `nil` appeared as a condition. end RUBY expect_no_corrections end it 'registers an offense but does not autocorrect when inside `if` and `return` is used after `&&`' do expect_offense(<<~RUBY) def foo baz? if 123 && return ^^^ Literal `123` appeared as a condition. end RUBY expect_no_corrections end it 'registers an offense but does not autocorrect when `break` is used after `&&`' do expect_offense(<<~RUBY) def foo bar do puts 123 && break if baz? ^^^ Literal `123` appeared as a condition. end end RUBY expect_no_corrections end it 'registers an offense but does not autocorrect when `next` is used after `&&`' do expect_offense(<<~RUBY) def foo bar do puts 123 && next if baz? ^^^ Literal `123` appeared as a condition. end end RUBY expect_no_corrections end it 'registers an offense when there is no body for `if` node' do expect_offense(<<~RUBY) if 42 ^^ Literal `42` appeared as a condition. end RUBY expect_correction(<<~RUBY) RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/ambiguous_block_association_spec.rb
spec/rubocop/cop/lint/ambiguous_block_association_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::AmbiguousBlockAssociation, :config do shared_examples 'accepts' do |code| it 'does not register an offense' do expect_no_offenses(code) end end it_behaves_like 'accepts', 'foo == bar { baz a }' it_behaves_like 'accepts', 'foo ->(a) { bar a }' it_behaves_like 'accepts', 'some_method(a) { |el| puts el }' it_behaves_like 'accepts', 'some_method(a) { puts _1 }' it_behaves_like 'accepts', 'some_method(a) do;puts a;end' it_behaves_like 'accepts', 'some_method a do;puts "dev";end' it_behaves_like 'accepts', 'some_method a do |e|;puts e;end' it_behaves_like 'accepts', 'Foo.bar(a) { |el| puts el }' it_behaves_like 'accepts', 'env ENV.fetch("ENV") { "dev" }' it_behaves_like 'accepts', 'env(ENV.fetch("ENV") { "dev" })' it_behaves_like 'accepts', '{ f: "b"}.fetch(:a) do |e|;puts e;end' it_behaves_like 'accepts', 'Hash[some_method(a) { |el| el }]' it_behaves_like 'accepts', 'foo = lambda do |diagnostic|;end' it_behaves_like 'accepts', 'Proc.new { puts "proc" }' it_behaves_like 'accepts', 'expect { order.save }.to(change { orders.size })' it_behaves_like 'accepts', 'scope :active, -> { where(status: "active") }' it_behaves_like 'accepts', 'scope :active, proc { where(status: "active") }' it_behaves_like 'accepts', 'scope :active, Proc.new { where(status: "active") }' it_behaves_like('accepts', 'assert_equal posts.find { |p| p.title == "Foo" }, results.first') it_behaves_like('accepts', 'assert_equal(posts.find { |p| p.title == "Foo" }, results.first)') it_behaves_like('accepts', 'assert_equal(results.first, posts.find { |p| p.title == "Foo" })') it_behaves_like('accepts', 'allow(cop).to receive(:on_int) { raise RuntimeError }') it_behaves_like('accepts', 'allow(cop).to(receive(:on_int) { raise RuntimeError })') context 'without parentheses' do context 'without receiver' do it 'registers an offense' do expect_offense(<<~RUBY) some_method a { |el| puts el } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `a { |el| puts el }` to make sure that the block will be associated with the `a` method call. RUBY expect_correction(<<~RUBY) some_method(a { |el| puts el }) RUBY end end context 'without receiver and numblock' do it 'registers an offense' do expect_offense(<<~RUBY) some_method a { puts _1 } ^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `a { puts _1 }` to make sure that the block will be associated with the `a` method call. RUBY expect_correction(<<~RUBY) some_method(a { puts _1 }) RUBY end end context 'without receiver and itblock', :ruby34 do it 'registers an offense' do expect_offense(<<~RUBY) some_method a { puts it } ^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `a { puts it }` to make sure that the block will be associated with the `a` method call. RUBY expect_correction(<<~RUBY) some_method(a { puts it }) RUBY end end context 'with receiver' do it 'registers an offense' do expect_offense(<<~RUBY) Foo.some_method a { |el| puts el } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `a { |el| puts el }` to make sure that the block will be associated with the `a` method call. RUBY expect_correction(<<~RUBY) Foo.some_method(a { |el| puts el }) RUBY end context 'when using safe navigation operator' do it 'registers an offense' do expect_offense(<<~RUBY) Foo&.some_method a { |el| puts el } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `a { |el| puts el }` to make sure that the block will be associated with the `a` method call. RUBY expect_correction(<<~RUBY) Foo&.some_method(a { |el| puts el }) RUBY end end end context 'rspec expect {}.to change {}' do it 'registers an offense' do expect_offense(<<~RUBY) expect { order.expire }.to change { order.events } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `change { order.events }` to make sure that the block will be associated with the `change` method call. RUBY expect_correction(<<~RUBY) expect { order.expire }.to(change { order.events }) RUBY end end context 'as a hash key' do it 'registers an offense' do expect_offense(<<~RUBY) Hash[some_method a { |el| el }] ^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `a { |el| el }` to make sure that the block will be associated with the `a` method call. RUBY expect_correction(<<~RUBY) Hash[some_method(a { |el| el })] RUBY end end context 'with assignment' do it 'registers an offense' do expect_offense(<<~RUBY) foo = some_method a { |el| puts el } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `a { |el| puts el }` to make sure that the block will be associated with the `a` method call. RUBY expect_correction(<<~RUBY) foo = some_method(a { |el| puts el }) RUBY end end end context 'when AllowedMethods is enabled' do let(:cop_config) { { 'AllowedMethods' => %w[change] } } it 'does not register an offense for an allowed method' do expect_no_offenses(<<~RUBY) expect { order.expire }.to change { order.events } RUBY end it 'registers an offense for other methods' do expect_offense(<<~RUBY) expect { order.expire }.to update { order.events } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `update { order.events }` to make sure that the block will be associated with the `update` method call. RUBY expect_correction(<<~RUBY) expect { order.expire }.to(update { order.events }) RUBY end end context 'when AllowedPatterns is enabled' do let(:cop_config) { { 'AllowedPatterns' => [/change/, /receive\(.*?\)\.twice/] } } it 'does not register an offense for an allowed method' do expect_no_offenses(<<~RUBY) expect { order.expire }.to not_change { order.events } RUBY expect_no_offenses(<<~RUBY) expect(order).to receive(:complete).twice { OrderCount.update! } RUBY end it 'registers an offense for other methods' do expect_offense(<<~RUBY) expect { order.expire }.to update { order.events } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Parenthesize the param `update { order.events }` to make sure that the block will be associated with the `update` method call. RUBY expect_correction(<<~RUBY) expect { order.expire }.to(update { order.events }) 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/lint/ensure_return_spec.rb
spec/rubocop/cop/lint/ensure_return_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EnsureReturn, :config do it 'registers an offense but does not correct for return in ensure' do expect_offense(<<~RUBY) begin something ensure file.close return ^^^^^^ Do not return from an `ensure` block. end RUBY expect_no_corrections end it 'registers an offense but does not correct for return with argument in ensure' do expect_offense(<<~RUBY) begin foo ensure return baz ^^^^^^^^^^ Do not return from an `ensure` block. end RUBY expect_no_corrections end it 'registers an offense when returning multiple values in `ensure`' do expect_offense(<<~RUBY) begin something ensure do_something return foo, bar ^^^^^^^^^^^^^^^ Do not return from an `ensure` block. end RUBY expect_no_corrections end it 'does not register an offense for return outside ensure' do expect_no_offenses(<<~RUBY) begin something return ensure file.close end RUBY end it 'does not check when ensure block has no body' do expect_no_offenses(<<~RUBY) begin something ensure 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/lint/useless_else_without_rescue_spec.rb
spec/rubocop/cop/lint/useless_else_without_rescue_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessElseWithoutRescue, :config do context 'with `else` without `rescue`', :ruby25, unsupported_on: :prism do it 'registers an offense' do expect_offense(<<~RUBY) begin do_something else ^^^^ `else` without `rescue` is useless. handle_unknown_errors end RUBY end end context 'with `else` with `rescue`' do it 'accepts' do expect_no_offenses(<<~RUBY) begin do_something rescue ArgumentError handle_argument_error else handle_unknown_errors 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/lint/duplicate_methods_spec.rb
spec/rubocop/cop/lint/duplicate_methods_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateMethods, :config do shared_examples 'in scope' do |type, opening_line| it "registers an offense for duplicate method in #{type}" do expect_offense(<<~RUBY) #{opening_line} def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both (string):2 and (string):5. implement 2 end end RUBY end it "doesn't register an offense for non-duplicate method in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} def some_method implement 1 end def any_method implement 2 end end RUBY end it "registers an offense for duplicate class methods in #{type}" do expect_offense(<<~RUBY, 'dups.rb') #{opening_line} def self.some_method implement 1 end def self.some_method ^^^^^^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both dups.rb:2 and dups.rb:5. implement 2 end end RUBY end it "doesn't register offense for non-duplicate class methods in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} def self.some_method implement 1 end def self.any_method implement 2 end end RUBY end it "recognizes difference between instance and class methods in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} def some_method implement 1 end def self.some_method implement 2 end end RUBY end it "registers an offense for duplicate private methods in #{type}" do expect_offense(<<~RUBY) #{opening_line} private def some_method implement 1 end private def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both (string):2 and (string):5. implement 2 end end RUBY end it "registers an offense for duplicate private self methods in #{type}" do expect_offense(<<~RUBY) #{opening_line} private def self.some_method implement 1 end private def self.some_method ^^^^^^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both (string):2 and (string):5. implement 2 end end RUBY end it "doesn't register an offense for different private methods in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} private def some_method implement 1 end private def any_method implement 2 end end RUBY end it "registers an offense for duplicate protected methods in #{type}" do expect_offense(<<~RUBY) #{opening_line} protected def some_method implement 1 end protected def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both (string):2 and (string):5. implement 2 end end RUBY end it "registers 2 offenses for pair of duplicate methods in #{type}" do expect_offense(<<~RUBY, 'dups.rb') #{opening_line} def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both dups.rb:2 and dups.rb:5. implement 2 end def any_method implement 1 end def any_method ^^^^^^^^^^^^^^ Method `A#any_method` is defined at both dups.rb:8 and dups.rb:11. implement 2 end end RUBY end it "registers an offense for a duplicate instance method in separate #{type} blocks" do expect_offense(<<~RUBY, 'dups.rb') #{opening_line} def some_method implement 1 end end #{opening_line} def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both dups.rb:2 and dups.rb:7. implement 2 end end RUBY end it "registers an offense for a duplicate class method in separate #{type} blocks" do expect_offense(<<~RUBY, 'test.rb') #{opening_line} def self.some_method implement 1 end end #{opening_line} def self.some_method ^^^^^^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both test.rb:2 and test.rb:7. implement 2 end end RUBY end it 'only registers an offense for the second instance of a duplicate instance method in separate files' do expect_no_offenses(<<~RUBY, 'first.rb') #{opening_line} def some_method implement 1 end end RUBY expect_offense(<<~RUBY, 'second.rb') #{opening_line} def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both first.rb:2 and second.rb:2. implement 2 end end RUBY end it 'understands class << self' do expect_offense(<<~RUBY, 'test.rb') #{opening_line} class << self def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both test.rb:3 and test.rb:6. implement 2 end end end RUBY end it 'understands nested modules' do expect_offense(<<~RUBY, 'test.rb') module B #{opening_line} def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `B::A#some_method` is defined at both test.rb:3 and test.rb:6. implement 2 end def self.another end def self.another ^^^^^^^^^^^^^^^^ Method `B::A.another` is defined at both test.rb:9 and test.rb:11. end end end RUBY end it 'registers an offense when class << exp is used' do expect_offense(<<~RUBY, 'test.rb') #{opening_line} class << blah def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `blah.some_method` is defined at both test.rb:3 and test.rb:6. implement 2 end end end RUBY end it "registers an offense for duplicate alias in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end alias some_method any_method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "does not register an offense for duplicate self-alias in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} alias some_method some_method def some_method implement 1 end end RUBY end it "doesn't register an offense for non-duplicate alias in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} def some_method implement 1 end alias any_method some_method end RUBY end it "registers an offense for duplicate alias_method in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end alias_method :some_method, :any_method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "does not register an offense for duplicate self-alias_method in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} alias_method :some_method, :some_method def some_method implement 1 end end RUBY end it "does not register an offense for duplicate self-alias_method with dynamic original name in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} alias_method :some_method, unknown() def some_method implement 1 end end RUBY end it "accepts for non-duplicate alias_method in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} def some_method implement 1 end alias_method :any_method, :some_method end RUBY end it "doesn't register an offense for alias for gvar in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} alias $foo $bar end RUBY end it "registers an offense for duplicate attr_reader in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def something end attr_reader :something ^^^^^^^^^^^^^^^^^^^^^^ Method `A#something` is defined at both example.rb:2 and example.rb:4. end RUBY end it "registers an offense for duplicate attr_writer in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def something=(right) end attr_writer :something ^^^^^^^^^^^^^^^^^^^^^^ Method `A#something=` is defined at both example.rb:2 and example.rb:4. end RUBY end it "registers offenses for duplicate attr_accessor in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} attr_accessor :something def something ^^^^^^^^^^^^^ Method `A#something` is defined at both example.rb:2 and example.rb:4. end def something=(right) ^^^^^^^^^^^^^^ Method `A#something=` is defined at both example.rb:2 and example.rb:6. end end RUBY end it "registers an offense for duplicate attr in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def something end attr :something ^^^^^^^^^^^^^^^ Method `A#something` is defined at both example.rb:2 and example.rb:4. end RUBY end it "registers offenses for duplicate assignable attr in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} attr :something, true def something ^^^^^^^^^^^^^ Method `A#something` is defined at both example.rb:2 and example.rb:4. end def something=(right) ^^^^^^^^^^^^^^ Method `A#something=` is defined at both example.rb:2 and example.rb:6. end end RUBY end it "accepts for attr_reader and setter in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} def something=(right) end attr_reader :something end RUBY end it "accepts for attr_writer and getter in #{type}" do expect_no_offenses(<<~RUBY) #{opening_line} def something end attr_writer :something end RUBY end it "registers an offense for duplicate nested method in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def foo def some_method implement 1 end end def foo ^^^^^^^ Method `A#foo` is defined at both example.rb:2 and example.rb:8. def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:3 and example.rb:9. implement 2 end end end RUBY end it "registers an offense for duplicate nested method in self method of #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def self.foo def some_method implement 1 end end def self.foo ^^^^^^^^^^^^ Method `A.foo` is defined at both example.rb:2 and example.rb:8. def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:3 and example.rb:9. implement 2 end end end RUBY end it 'does not register an offense for same method name defined in different methods' do expect_no_offenses(<<~RUBY) #{opening_line} def foo def some_method implement 1 end end def bar def some_method implement 2 end end end RUBY end it 'does not register an offense for same method name defined in different self methods' do expect_no_offenses(<<~RUBY) #{opening_line} def self.foo def some_method implement 1 end end def self.bar def some_method implement 2 end end end RUBY end it 'does not register an offense for same method name defined in different blocks' do expect_no_offenses(<<~RUBY) #{opening_line} dsl_like('foo') do def some_method implement 1 end end dsl_like('bar') do def some_method implement 2 end end end RUBY end context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do let(:config) do RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => true }) end it "registers an offense for duplicate delegate with symbol method in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :some_method, to: :foo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "registers an offense for duplicate delegate with string method in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate 'some_method', to: :foo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "registers an offense for duplicate delegate with string `to` argument in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :some_method, to: 'foo' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "registers an offense for duplicate delegate with symbol prefix in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :method, to: :foo, prefix: :some ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "registers an offense for duplicate delegate with string prefix in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :method, to: :foo, prefix: 'some' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "registers an offense for duplicate delegate with prefix true in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :method, to: :some, prefix: true ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "registers an offense with multiple delegates in #{type}" do expect_offense(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :other_method, :some_method, to: :foo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both example.rb:2 and example.rb:5. end RUBY end it "does not register an offense for non-duplicate delegate with prefix false in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :method, prefix: false, to: :some end RUBY end it "does not register an offense for dynamically specified `to` option with enabled prefix in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end %w[any none some].each do |type| delegate :method, prefix: true, to: type end end RUBY end it "does not register an offense for dynamically specified `prefix` in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :method, prefix: some_condition, to: :some end RUBY end it "does not register an offense for non-duplicate delegate in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :other_method, to: :foo end RUBY end it "does not register an offense for duplicate delegate inside a condition in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end if cond delegate :some_method, to: :foo end end RUBY end it "does not register an offense for duplicate delegate with splat keyword arguments in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :some_method, **options end RUBY end it "does not register an offense for duplicate delegate without keyword arguments in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :some_method end RUBY end it 'does not register an offense for duplicate delegate without `to` argument' do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :some_method, prefix: true end RUBY end end context 'when `AllCops/ActiveSupportExtensionsEnabled: false`' do let(:config) do RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => false }) end it "does not register an offense for duplicate delegate in #{type}" do expect_no_offenses(<<~RUBY, 'example.rb') #{opening_line} def some_method implement 1 end delegate :some_method, to: :foo end RUBY end end end it_behaves_like('in scope', 'class', 'class A') it_behaves_like('in scope', 'module', 'module A') it_behaves_like('in scope', 'dynamic class', 'A = Class.new do') it_behaves_like('in scope', 'dynamic module', 'A = Module.new do') it_behaves_like('in scope', 'class_eval block', 'A.class_eval do') %w[class module].each do |type| it "registers an offense for duplicate class methods with named receiver in #{type}" do expect_offense(<<~RUBY, 'src.rb') #{type} A def A.some_method implement 1 end def A.some_method ^^^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both src.rb:2 and src.rb:5. implement 2 end end RUBY end it 'registers an offense for duplicate class methods with `self` and ' \ "named receiver in #{type}" do expect_offense(<<~RUBY, 'src.rb') #{type} A def self.some_method implement 1 end def A.some_method ^^^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both src.rb:2 and src.rb:5. implement 2 end end RUBY end it 'registers an offense for duplicate class methods with `<<` and named ' \ "receiver in #{type}" do expect_offense(<<~RUBY, 'test.rb') #{type} A class << self def some_method implement 1 end end def A.some_method ^^^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both test.rb:3 and test.rb:7. implement 2 end end RUBY end end it 'registers an offense for duplicate methods at top level' do expect_offense(<<~RUBY, 'toplevel.rb') def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `Object#some_method` is defined at both toplevel.rb:1 and toplevel.rb:4. implement 2 end RUBY end it 'understands class << A' do expect_offense(<<~RUBY, 'test.rb') class << A def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `A.some_method` is defined at both test.rb:2 and test.rb:5. implement 2 end end RUBY end it 'handles class_eval with implicit receiver' do expect_offense(<<~RUBY, 'test.rb') module A class_eval do def some_method implement 1 end def some_method ^^^^^^^^^^^^^^^ Method `A#some_method` is defined at both test.rb:3 and test.rb:6. implement 2 end end end RUBY end it 'ignores method definitions in RSpec `describe` blocks' do expect_no_offenses(<<~RUBY) describe "something" do def some_method implement 1 end def some_method implement 2 end end RUBY end it 'ignores Class.new blocks which are assigned to local variables' do expect_no_offenses(<<~RUBY) a = Class.new do def foo end end b = Class.new do def foo end end RUBY end it 'does not register an offense when there are same `alias_method` name outside `ensure` scope' do expect_no_offenses(<<~RUBY) module FooTest def make_save_always_fail Foo.class_eval do def failed_save raise end alias_method :original_save, :save alias_method :save, :failed_save end yield ensure Foo.class_eval do alias_method :save, :original_save end end end RUBY end it 'registers an offense when there are duplicate `alias_method` name inside `ensure` scope' do expect_offense(<<~RUBY, 'test.rb') module FooTest def make_save_always_fail Foo.class_eval do def failed_save raise end alias_method :original_save, :save alias_method :save, :failed_save end yield ensure Foo.class_eval do alias_method :save, :original_save alias_method :save, :original_save ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `FooTest::Foo#save` is defined at both test.rb:14 and test.rb:15. end end end RUBY end it 'does not register an offense when there are same `alias_method` name outside `rescue` scope' do expect_no_offenses(<<~RUBY) module FooTest def make_save_always_fail Foo.class_eval do def failed_save raise end alias_method :original_save, :save alias_method :save, :failed_save end yield rescue Foo.class_eval do alias_method :save, :original_save end end end RUBY end it 'registers an offense when there are duplicate `alias_method` name inside `rescue` scope' do expect_offense(<<~RUBY, 'test.rb') module FooTest def make_save_always_fail Foo.class_eval do def failed_save raise end alias_method :original_save, :save alias_method :save, :failed_save end yield rescue Foo.class_eval do alias_method :save, :original_save alias_method :save, :original_save ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method `FooTest::Foo#save` is defined at both test.rb:14 and test.rb:15. end end end RUBY end it 'does not register for the same method in different scopes within `class << self`' do expect_no_offenses(<<~RUBY, 'test.rb') class A class << self def foo end class B def foo end end end end RUBY end it 'properly registers an offense when deeply nested' do expect_offense(<<~RUBY, 'test.rb') module A module B class C class << self def foo end def foo ^^^^^^^ Method `A::B::C.foo` is defined at both test.rb:5 and test.rb:8. end end end end end RUBY end context 'when path is in the project root' do before do allow(Dir).to receive(:pwd).and_return('/path/to/project/root') allow_any_instance_of(Parser::Source::Buffer).to receive(:name) .and_return('/path/to/project/root/lib/foo.rb') end it 'adds a message with relative path' do expect_offense(<<~RUBY) def something end def something ^^^^^^^^^^^^^ Method `Object#something` is defined at both lib/foo.rb:1 and lib/foo.rb:3. end RUBY end end context 'when path is not in the project root' do before do allow(Dir).to receive(:pwd).and_return('/path/to/project/root') allow_any_instance_of(Parser::Source::Buffer).to receive(:name) .and_return('/no/project/root/foo.rb') end it 'adds a message with absolute path' do expect_offense(<<~RUBY) def something end def something ^^^^^^^^^^^^^ Method `Object#something` is defined at both /no/project/root/foo.rb:1 and /no/project/root/foo.rb: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/lint/to_json_spec.rb
spec/rubocop/cop/lint/to_json_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ToJSON, :config do it 'registers an offense and corrects using `#to_json` without arguments' do expect_offense(<<~RUBY) def to_json ^^^^^^^^^^^ `#to_json` requires an optional argument to be parsable via JSON.generate(obj). end RUBY expect_correction(<<~RUBY) def to_json(*_args) end RUBY end it 'does not register an offense when using `#to_json` with arguments' do expect_no_offenses(<<~RUBY) def to_json(*_args) 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/lint/redundant_safe_navigation_spec.rb
spec/rubocop/cop/lint/redundant_safe_navigation_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantSafeNavigation, :config do let(:cop_config) do { 'AllowedMethods' => %w[respond_to?], 'AdditionalNilMethods' => %w[present?] } end it 'registers an offense and corrects when `&.` is used for camel case const receiver' do expect_offense(<<~RUBY) Const&.do_something ^^ Redundant safe navigation detected, use `.` instead. ConstName&.do_something ^^ Redundant safe navigation detected, use `.` instead. Const_name&.do_something # It is treated as camel case, similar to the `Naming/ConstantName` cop. ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) Const.do_something ConstName.do_something Const_name.do_something # It is treated as camel case, similar to the `Naming/ConstantName` cop. RUBY end it 'does not register an offense when `&.` is used for snake case const receiver' do expect_no_offenses(<<~RUBY) CONST&.do_something CONST_NAME&.do_something RUBY end it 'registers an offense and corrects when `&.` is used for namespaced camel case const receiver' do expect_offense(<<~RUBY) FOO::Const&.do_something ^^ Redundant safe navigation detected, use `.` instead. bar::ConstName&.do_something ^^ Redundant safe navigation detected, use `.` instead. BAZ::Const_name&.do_something # It is treated as camel case, similar to the `Naming/ConstantName` cop. ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) FOO::Const.do_something bar::ConstName.do_something BAZ::Const_name.do_something # It is treated as camel case, similar to the `Naming/ConstantName` cop. RUBY end it 'does not register an offense when `&.` is used for namespaced snake case const receiver' do expect_no_offenses(<<~RUBY) FOO::CONST&.do_something bar::CONST_NAME&.do_something RUBY end it 'registers an offense and corrects when `&.` is used inside `if` condition' do expect_offense(<<~RUBY) if foo&.respond_to?(:bar) ^^ Redundant safe navigation detected, use `.` instead. do_something elsif foo&.respond_to?(:baz) ^^ Redundant safe navigation detected, use `.` instead. do_something_else end RUBY expect_correction(<<~RUBY) if foo.respond_to?(:bar) do_something elsif foo.respond_to?(:baz) do_something_else end RUBY end it 'registers an offense and corrects when `&.` is used inside `unless` condition' do expect_offense(<<~RUBY) do_something unless foo&.respond_to?(:bar) ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) do_something unless foo.respond_to?(:bar) RUBY end it 'registers an offense and corrects when `&.` is used for string literals' do expect_offense(<<~RUBY) '2012-03-02 16:05:37'&.to_time ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) '2012-03-02 16:05:37'.to_time RUBY end it 'registers an offense and corrects when `&.` is used for integer literals' do expect_offense(<<~RUBY) 42&.minutes ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) 42.minutes RUBY end it 'registers an offense and corrects when `&.` is used for array literals' do expect_offense(<<~RUBY) [1, 2, 3]&.join(', ') ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) [1, 2, 3].join(', ') RUBY end it 'registers an offense and corrects when `&.` is used for hash literals' do expect_offense(<<~RUBY) {k: :v}&.count ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) {k: :v}.count RUBY end it 'does not register an offense when `&.` is used for `nil` literal' do expect_no_offenses(<<~RUBY) nil&.to_i RUBY end it 'registers an offense and correct when `&.` is used with `self`' do expect_offense(<<~RUBY) self&.foo ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) self.foo RUBY end %i[while until].each do |loop_type| it 'registers an offense and corrects when `&.` is used inside `#{loop_type}` condition' do expect_offense(<<~RUBY, loop_type: loop_type) %{loop_type} foo&.respond_to?(:bar) _{loop_type} ^^ Redundant safe navigation detected, use `.` instead. do_something end begin do_something end %{loop_type} foo&.respond_to?(:bar) _{loop_type} ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) #{loop_type} foo.respond_to?(:bar) do_something end begin do_something end #{loop_type} foo.respond_to?(:bar) RUBY end end it 'registers an offense and corrects when `&.` is used inside complex condition' do expect_offense(<<~RUBY) do_something if foo&.respond_to?(:bar) && !foo&.respond_to?(:baz) ^^ Redundant safe navigation detected, use `.` instead. ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) do_something if foo.respond_to?(:bar) && !foo.respond_to?(:baz) RUBY end it 'does not register an offense when using `&.` outside of conditions' do expect_no_offenses(<<~RUBY) foo&.respond_to?(:bar) if condition foo&.respond_to?(:bar) end RUBY end it 'does not register an offense when using `&.` with non-allowed method in condition' do expect_no_offenses(<<~RUBY) do_something if foo&.bar? RUBY end it 'does not register an offense when using `&.respond_to?` with `nil` specific method as argument in condition' do expect_no_offenses(<<~RUBY) do_something if foo&.respond_to?(:to_a) RUBY end it 'does not register an offense when `&.` is used with coercion methods' do expect_no_offenses(<<~RUBY) foo&.to_s || 'Default string' foo&.to_i || 1 do_something if foo&.to_d RUBY end it 'registers an offense and corrects when `.&` is used in `.to_h` conversion with default' do expect_offense(<<~RUBY) foo&.to_h || {} ^^^^^^^^^^^^ Redundant safe navigation with default literal detected. RUBY expect_correction(<<~RUBY) foo.to_h RUBY end it 'registers an offense and corrects when `.&` is used in `.to_h` conversion having block with default' do expect_offense(<<~RUBY) foo&.to_h { |k, v| [k, v] } || {} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Redundant safe navigation with default literal detected. RUBY expect_correction(<<~RUBY) foo.to_h { |k, v| [k, v] } RUBY end it 'does not register an offense when `.&` is used in `.to_h` conversion with incorrect default' do expect_no_offenses(<<~RUBY) foo&.to_h || { a: 1 } RUBY end it 'registers an offense and corrects when `.&` is used in `.to_a` conversion with default' do expect_offense(<<~RUBY) foo&.to_a || [] ^^^^^^^^^^^^ Redundant safe navigation with default literal detected. RUBY expect_correction(<<~RUBY) foo.to_a RUBY end it 'does not register an offense when `.&` is used in `.to_a` conversion with incorrect default' do expect_no_offenses(<<~RUBY) foo&.to_a || [1] RUBY end it 'registers an offense and corrects when `.&` is used in `.to_i` conversion with default' do expect_offense(<<~RUBY) foo&.to_i || 0 ^^^^^^^^^^^ Redundant safe navigation with default literal detected. RUBY expect_correction(<<~RUBY) foo.to_i RUBY end it 'does not register an offense when `.&` is used in `.to_i` conversion with incorrect default' do expect_no_offenses(<<~RUBY) foo&.to_i || 1 RUBY end it 'registers an offense and corrects when `.&` is used in `.to_f` conversion with default' do expect_offense(<<~RUBY) foo&.to_f || 0.0 ^^^^^^^^^^^^^ Redundant safe navigation with default literal detected. RUBY expect_correction(<<~RUBY) foo.to_f RUBY end it 'does not register an offense when `.&` is used in `.to_f` conversion with incorrect default' do expect_no_offenses(<<~RUBY) foo&.to_f || 1.0 RUBY end it 'registers an offense and corrects when `.&` is used in `.to_s` conversion with default' do expect_offense(<<~RUBY) foo&.to_s || '' ^^^^^^^^^^^^ Redundant safe navigation with default literal detected. RUBY expect_correction(<<~RUBY) foo.to_s RUBY end it 'does not register an offense when `.&` is used in `.to_s` conversion with incorrect default' do expect_no_offenses(<<~RUBY) foo&.to_s || 'default' RUBY end context 'when InferNonNilReceiver is disabled' do let(:cop_config) { { 'InferNonNilReceiver' => false } } it 'does not register an offense when method is called on receiver on preceding line' do expect_no_offenses(<<~RUBY) foo.bar foo&.baz RUBY end end context 'when InferNonNilReceiver is enabled' do let(:cop_config) { { 'InferNonNilReceiver' => true } } it 'registers an offense and corrects when method is called on receiver on preceding line' do expect_offense(<<~RUBY) foo.bar foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). RUBY expect_correction(<<~RUBY) foo.bar foo.baz RUBY end it 'registers an offense and corrects when method is called on receiver on preceding line and is a method argument' do expect_offense(<<~RUBY) zoo(1, foo.bar, 2) foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). RUBY expect_correction(<<~RUBY) zoo(1, foo.bar, 2) foo.baz RUBY end it 'registers an offense and corrects when method is called on a receiver in a condition' do expect_offense(<<~RUBY) if foo.condition? foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). end RUBY expect_correction(<<~RUBY) if foo.condition? foo.bar end RUBY end it 'registers an offense and corrects when method receiver is a sole condition of parent `if`' do expect_offense(<<~RUBY) if foo foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). else foo&.baz end RUBY expect_correction(<<~RUBY) if foo foo.bar else foo&.baz end RUBY end it 'registers an offense and corrects when method receiver is a sole condition of parent `elsif`' do expect_offense(<<~RUBY) if condition? 1 elsif foo foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). else foo&.baz end RUBY expect_correction(<<~RUBY) if condition? 1 elsif foo foo.bar else foo&.baz end RUBY end it 'registers an offense and corrects when method receiver is a sole condition of parent ternary' do expect_offense(<<~RUBY) foo ? foo&.bar : foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). RUBY expect_correction(<<~RUBY) foo ? foo.bar : foo&.baz RUBY end it 'registers an offense and corrects when method is called on receiver in lhs of condition' do expect_offense(<<~RUBY) if foo.condition? && other_condition foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). end RUBY expect_correction(<<~RUBY) if foo.condition? && other_condition foo.bar end RUBY end it 'does not register an offense when method is called on receiver in rhs of condition' do expect_no_offenses(<<~RUBY) if other_condition && foo.condition? foo&.bar end RUBY end it 'registers an offense and corrects when method is called on receiver in `if` condition of if/else' do expect_offense(<<~RUBY) if foo.condition? 1 else foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). end RUBY expect_correction(<<~RUBY) if foo.condition? 1 else foo.bar end RUBY end it 'registers an offense and corrects when method is called on receiver in `elsif`' do expect_offense(<<~RUBY) if condition? 1 elsif foo.condition? foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). end RUBY expect_correction(<<~RUBY) if condition? 1 elsif foo.condition? foo.bar end RUBY end it 'registers an offense and corrects when method is called on receiver in condition of ternary' do expect_offense(<<~RUBY) foo.condition? ? foo&.bar : foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). RUBY expect_correction(<<~RUBY) foo.condition? ? foo.bar : foo.baz RUBY end it 'does not register an offense when method is called on receiver further in the condition' do expect_no_offenses(<<~RUBY) if condition1? && (foo.condition? || condition2?) foo&.bar end RUBY end it 'does not register an offense when method is called on receiver in a previous branch body' do expect_no_offenses(<<~RUBY) if condition? foo.bar elsif foo&.bar? 2 end RUBY end it 'does not register an offense when receiver is a sole condition in a previous `if`' do expect_no_offenses(<<~RUBY) if foo do_something end foo&.bar RUBY end it 'registers an offense and corrects when method is called on receiver on preceding line in array literal' do expect_offense(<<~RUBY) [ foo.bar, foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). ] RUBY expect_correction(<<~RUBY) [ foo.bar, foo.baz ] RUBY end it 'registers an offense and corrects when method is called on receiver on preceding line in hash literal' do expect_offense(<<~RUBY) { bar: foo.bar, baz: foo&.baz, ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). foo&.zoo => 3 ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). } RUBY expect_correction(<<~RUBY) { bar: foo.bar, baz: foo.baz, foo.zoo => 3 } RUBY end it 'does not register an offense when `nil`s method is called on receiver' do expect_no_offenses(<<~RUBY) if foo.nil? foo&.bar end RUBY end it 'does not register an offense when calling custom nil method' do expect_no_offenses(<<~RUBY) foo.present? foo&.bar RUBY end it 'registers an offense and corrects when receiver is a `case` condition' do expect_offense(<<~RUBY) case foo.condition when 1 foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). when foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). 2 else foo&.zoo ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). end RUBY expect_correction(<<~RUBY) case foo.condition when 1 foo.bar when foo.baz 2 else foo.zoo end RUBY end it 'does not register an offense when method is called on receiver in another branch' do expect_no_offenses(<<~RUBY) case when 1 foo.bar when 2 foo&.baz else foo&.zoo end RUBY end it 'registers an offense and corrects when method is called on receiver in a branch condition' do expect_offense(<<~RUBY) case when 1 2 when foo.bar foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). else foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). end RUBY expect_correction(<<~RUBY) case when 1 2 when foo.bar foo.bar else foo.baz end RUBY end it 'registers an offense and corrects when method is called in preceding line in assignment with `||`' do expect_offense(<<~RUBY) x = foo.bar || true foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). RUBY expect_correction(<<~RUBY) x = foo.bar || true foo.baz RUBY end it 'registers an offense and corrects when method is called in preceding line in assignment' do expect_offense(<<~RUBY) CONST = foo.bar foo&.baz ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). RUBY expect_correction(<<~RUBY) CONST = foo.bar foo.baz RUBY end it 'ignores offenses outside of the method definition scope' do expect_no_offenses(<<~RUBY) foo.bar def x foo&.bar end RUBY end it 'ignores offenses outside of the singleton method definition scope' do expect_no_offenses(<<~RUBY) foo.bar def self.x foo&.bar end RUBY end it 'correctly detects and corrects complex cases' do expect_offense(<<~RUBY) x = 1 && foo.bar if true foo&.bar elsif (foo.bar) call(1, 2, 3 + foo&.baz) ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). else case when 1, foo&.bar ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). [ 1, { 2 => 3, foo&.baz => 4, ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). 4 => -foo&.zoo ^^ Redundant safe navigation on non-nil receiver (detected by analyzing previous code/method invocations). } ] end end RUBY expect_correction(<<~RUBY) x = 1 && foo.bar if true foo&.bar elsif (foo.bar) call(1, 2, 3 + foo.baz) else case when 1, foo.bar [ 1, { 2 => 3, foo.baz => 4, 4 => -foo.zoo } ] end end RUBY end end it 'registers an offense when `&.` is used for `to_s`' do expect_offense(<<~RUBY) foo.to_s&.strip ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) foo.to_s.strip RUBY end it 'does not register an offense when `&.` is used for `to_s` with safe navigation' do expect_no_offenses(<<~RUBY) foo&.to_s&.zero? RUBY end it 'registers an offense when `&.` is used for `to_i`' do expect_offense(<<~RUBY) foo.to_i&.zero? ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) foo.to_i.zero? RUBY end it 'does not register an offense when `&.` is used for `to_i` with safe navigation' do expect_no_offenses(<<~RUBY) foo&.to_i&.zero? RUBY end it 'registers an offense when `&.` is used for `to_f`' do expect_offense(<<~RUBY) foo.to_f&.zero? ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) foo.to_f.zero? RUBY end it 'does not register an offense when `&.` is used for `to_f` with safe navigation' do expect_no_offenses(<<~RUBY) foo&.to_f&.zero? RUBY end it 'registers an offense when `&.` is used for `to_a`' do expect_offense(<<~RUBY) foo.to_a&.size ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) foo.to_a.size RUBY end it 'does not register an offense when `&.` is used for `to_a` with safe navigation' do expect_no_offenses(<<~RUBY) foo&.to_a&.zero? RUBY end it 'registers an offense when `&.` is used for `to_h`' do expect_offense(<<~RUBY) foo.to_h&.size ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) foo.to_h.size RUBY end it 'does not register an offense when `&.` is used for `to_h` with safe navigation' do expect_no_offenses(<<~RUBY) foo&.to_h&.zero? RUBY end it 'registers an offense when `&.` is used for `to_h` with block' do expect_offense(<<~RUBY) foo.to_h { |entry| do_something(entry) }&.keys ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) foo.to_h { |entry| do_something(entry) }.keys RUBY end it 'does not register an offense when `&.` is used for `to_h { ... }` with block with safe navigation' do expect_no_offenses(<<~RUBY) foo&.to_h { |entry| do_something(entry) }&.keys RUBY end it 'registers an offense when `&.` is used for `to_h` with numbered block' do expect_offense(<<~RUBY) foo.to_h { do_something(_1) }&.keys ^^ Redundant safe navigation detected, use `.` instead. RUBY expect_correction(<<~RUBY) foo.to_h { do_something(_1) }.keys RUBY end it 'does not register an offense when `&.` is used for `to_h { ... }` with numbered block with safe navigation' do expect_no_offenses(<<~RUBY) foo&.to_h { do_something(_1) }&.keys 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/lint/empty_in_pattern_spec.rb
spec/rubocop/cop/lint/empty_in_pattern_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyInPattern, :config do let(:cop_config) { { 'AllowComments' => false } } context 'when a `in` body is missing', :ruby27 do it 'registers an offense for a missing `in` body' do expect_offense(<<~RUBY) case foo in [a] then 1 in [a, b] # nothing ^^^^^^^^^ Avoid `in` branches without a body. end RUBY expect_no_corrections end it 'registers an offense for missing `in` body followed by `else`' do expect_offense(<<~RUBY) case foo in [a] then 1 in [a, b] # nothing ^^^^^^^^^ Avoid `in` branches without a body. else 3 end RUBY expect_no_corrections end it 'registers an offense for missing `in` ... `then` body' do expect_offense(<<~RUBY) case foo in [a] then 1 in [a, b] then # nothing ^^^^^^^^^ Avoid `in` branches without a body. end RUBY expect_no_corrections end it 'registers an offense for missing `in` ... then `body` followed by `else`' do expect_offense(<<~RUBY) case foo in [a] then 1 in [a, b] then # nothing ^^^^^^^^^ Avoid `in` branches without a body. else 3 end RUBY expect_no_corrections end it 'registers an offense for missing `in` body with a comment' do expect_offense(<<~RUBY) case foo in [a] 1 in [a, b] ^^^^^^^^^ Avoid `in` branches without a body. # nothing end RUBY expect_no_corrections end it 'registers an offense for missing `in` body with a comment followed by `else`' do expect_offense(<<~RUBY) case foo in [a] 1 in [a, b] ^^^^^^^^^ Avoid `in` branches without a body. # nothing else 3 end RUBY expect_no_corrections end end context 'when a `in` body is present', :ruby27 do it 'accepts `case` with `in` ... `then` statements' do expect_no_offenses(<<~RUBY) case foo in [a] then 1 in [a, b] then 2 end RUBY end it 'accepts `case` with `in` ... `then` statements and else clause' do expect_no_offenses(<<~RUBY) case foo in [a] then 1 in [a, b] then 2 else 3 end RUBY end it 'accepts `case` with `in` bodies' do expect_no_offenses(<<~RUBY) case foo in [a] 1 in [a, b] 2 end RUBY end it 'accepts `case` with `in` bodies and `else` clause' do expect_no_offenses(<<~RUBY) case foo in [a] 1 in [a, b] 2 else 3 end RUBY end end context 'when `AllowComments: true`', :ruby27 do let(:cop_config) { { 'AllowComments' => true } } it 'registers an offense for empty `in` when comment is in another branch' do expect_offense(<<~RUBY) case condition in [a] ^^^^^^ Avoid `in` branches without a body. in [a, b] # do nothing end RUBY end it 'accepts an empty `in` body with a comment' do expect_no_offenses(<<~RUBY) case condition in [a] do_something in [a, b] # do nothing end RUBY end end context 'when `AllowComments: false`', :ruby27 do let(:cop_config) { { 'AllowComments' => false } } it 'registers an offense for empty `in` body with a comment' do expect_offense(<<~RUBY) case condition in [a] do_something in [a, b] ^^^^^^^^^ Avoid `in` branches without a body. # do nothing end RUBY expect_no_corrections end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/duplicate_regexp_character_class_element_spec.rb
spec/rubocop/cop/lint/duplicate_regexp_character_class_element_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateRegexpCharacterClassElement, :config do context 'with a repeated character class element' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[xyx]/ ^ Duplicate element inside regexp character class RUBY expect_correction(<<~RUBY) foo = /[xy]/ RUBY end end context 'with a repeated character class element with quantifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[xyx]+/ ^ Duplicate element inside regexp character class RUBY expect_correction(<<~RUBY) foo = /[xy]+/ RUBY end end context 'with no repeated character class elements' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) foo = /[xyz]/ RUBY end end context 'with repeated elements in different character classes' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) foo = /[xyz][xyz]/ RUBY end end context 'with no repeated character class elements when `"\0\07"` (means `"\u0000\a"`)' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') /[\0\07]/ RUBY end end context 'with repeated character class elements when `"\0\08"` (means `"\u0000\u00008"`)' do it 'registers an offense' do expect_offense(<<~'RUBY') /[\0\08]/ ^^ Duplicate element inside regexp character class RUBY expect_correction(<<~'RUBY') /[\08]/ RUBY end end context 'with repeated character class elements when `"\07\01\078"` (means `"\u0007\u0001\u00078"`)' do it 'registers an offense' do expect_offense(<<~'RUBY') /[\07\01\078]/ ^^^ Duplicate element inside regexp character class RUBY expect_correction(<<~'RUBY') /[\07\018]/ RUBY end end context 'with repeated character class elements when `"\177\01\1778"` (means `"\u007f\u0001\u007f8"`)' do it 'registers an offense' do expect_offense(<<~'RUBY') /[\177\01\1778]/ ^^^^ Duplicate element inside regexp character class RUBY expect_correction(<<~'RUBY') /[\177\018]/ RUBY end end context 'with a repeated character class element and %r{} literal' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = %r{[xyx]} ^ Duplicate element inside regexp character class RUBY expect_correction(<<~RUBY) foo = %r{[xy]} RUBY end end context 'with a repeated character class element inside a group' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /([xyx])/ ^ Duplicate element inside regexp character class RUBY expect_correction(<<~RUBY) foo = /([xy])/ RUBY end end context 'with a repeated character posix character class inside a group' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /([[:alnum:]y[:alnum:]])/ ^^^^^^^^^ Duplicate element inside regexp character class RUBY expect_correction(<<~RUBY) foo = /([[:alnum:]y])/ RUBY end end context 'with a repeated character class element with interpolation' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /([a#{foo}a#{bar}a])/ ^ Duplicate element inside regexp character class ^ Duplicate element inside regexp character class RUBY expect_correction(<<~'RUBY') foo = /([a#{foo}#{bar}])/ RUBY end end context 'with a repeated range element' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[0-9x0-9]/ ^^^ Duplicate element inside regexp character class RUBY expect_correction(<<~RUBY) foo = /[0-9x]/ RUBY end end context 'with a repeated intersection character class' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) foo = /[ab&&ab]/ RUBY end end context 'with a range that covers a repeated element character class' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) foo = /[a-cb]/ RUBY end end context 'with multiple regexps with the same interpolation' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') a_field.gsub!(/[#{bad_chars}]/, '') some_other_field.gsub!(/[#{bad_chars}]/, '') 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/lint/useless_access_modifier_spec.rb
spec/rubocop/cop/lint/useless_access_modifier_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessAccessModifier, :config do context 'when an access modifier has no effect' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass def some_method puts 10 end private ^^^^^^^ Useless `private` access modifier. def self.some_method puts 10 end end RUBY expect_correction(<<~RUBY) class SomeClass def some_method puts 10 end def self.some_method puts 10 end end RUBY end end context 'when an access modifier is used on top-level' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) def some_method puts 10 end private ^^^^^^^ Useless `private` access modifier. def other_method puts 10 end RUBY expect_correction(<<~RUBY) def some_method puts 10 end def other_method puts 10 end RUBY end end context 'when an access modifier has no methods' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass def some_method puts 10 end protected ^^^^^^^^^ Useless `protected` access modifier. end RUBY expect_correction(<<~RUBY) class SomeClass def some_method puts 10 end end RUBY end end context 'when an access modifier is followed by attr_*' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class SomeClass protected attr_accessor :some_property public attr_reader :another_one private attr :yet_again, true protected attr_writer :just_for_good_measure end RUBY end end context 'when an access modifier is followed by a class method defined on constant' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass protected ^^^^^^^^^ Useless `protected` access modifier. def SomeClass.some_method end end RUBY expect_correction(<<~RUBY) class SomeClass def SomeClass.some_method end end RUBY end end context 'when there are consecutive access modifiers' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass private private ^^^^^^^ Useless `private` access modifier. def some_method puts 10 end def some_other_method puts 10 end end RUBY expect_correction(<<~RUBY) class SomeClass private def some_method puts 10 end def some_other_method puts 10 end end RUBY end end context 'when passing method as symbol' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class SomeClass def some_method puts 10 end private :some_method end RUBY end end context 'when class is empty save modifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass private ^^^^^^^ Useless `private` access modifier. end RUBY expect_correction(<<~RUBY) class SomeClass end RUBY end end context 'when multiple class definitions in file but only one has offense' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass private ^^^^^^^ Useless `private` access modifier. end class SomeOtherClass end RUBY expect_correction(<<~RUBY) class SomeClass end class SomeOtherClass end RUBY end end context 'when using inline modifiers' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class SomeClass private def some_method puts 10 end end RUBY end end context 'when only a constant or local variable is defined after the modifier' do %w[CONSTANT some_var].each do |binding_name| it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass private ^^^^^^^ Useless `private` access modifier. #{binding_name} = 1 end RUBY expect_correction(<<~RUBY) class SomeClass #{binding_name} = 1 end RUBY end end end context 'when a def is an argument to a method call' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class SomeClass private helper_method def some_method puts 10 end end RUBY end end context 'when private_class_method is used without arguments' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) class SomeClass private_class_method ^^^^^^^^^^^^^^^^^^^^ Useless `private_class_method` access modifier. def self.some_method puts 10 end end RUBY expect_correction(<<~RUBY) class SomeClass def self.some_method puts 10 end end RUBY end end context 'when private_class_method is used with arguments' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class SomeClass private_class_method def self.some_method puts 10 end end RUBY end end context "when using ActiveSupport's `concerning` method" do let(:config) do RuboCop::Config.new( 'Lint/UselessAccessModifier' => { 'ContextCreatingMethods' => ['concerning'] } ) end it 'is aware that this creates a new scope' do expect_no_offenses(<<~RUBY) class SomeClass concerning :FirstThing do def foo end private def method end end concerning :SecondThing do def omg end private def method end end end RUBY end it 'still points out redundant uses within the block' do expect_offense(<<~RUBY) class SomeClass concerning :FirstThing do def foo end private def method end end concerning :SecondThing do def omg end private def method end private ^^^^^^^ Useless `private` access modifier. def another_method end end end RUBY expect_correction(<<~RUBY) class SomeClass concerning :FirstThing do def foo end private def method end end concerning :SecondThing do def omg end private def method end def another_method end end end RUBY end context 'Ruby 2.7', :ruby27 do it 'still points out redundant uses within the block' do expect_offense(<<~RUBY) class SomeClass concerning :SecondThing do p _1 def omg end private def method end private ^^^^^^^ Useless `private` access modifier. def another_method end end end RUBY expect_correction(<<~RUBY) class SomeClass concerning :SecondThing do p _1 def omg end private def method end def another_method end end end RUBY end end end context 'when using ActiveSupport behavior when Rails is not enabled' do it 'reports offenses and corrects' do expect_offense(<<~RUBY) module SomeModule extend ActiveSupport::Concern class_methods do def some_public_class_method end private def some_private_class_method end end def some_public_instance_method end private ^^^^^^^ Useless `private` access modifier. def some_private_instance_method end end RUBY expect_correction(<<~RUBY) module SomeModule extend ActiveSupport::Concern class_methods do def some_public_class_method end private def some_private_class_method end end def some_public_instance_method end def some_private_instance_method end end RUBY end end context 'when using the class_methods method from ActiveSupport::Concern' do let(:config) do RuboCop::Config.new( 'Lint/UselessAccessModifier' => { 'ContextCreatingMethods' => ['class_methods'] } ) end it 'is aware that this creates a new scope' do expect_no_offenses(<<~RUBY) module SomeModule extend ActiveSupport::Concern class_methods do def some_public_class_method end private def some_private_class_method end end def some_public_instance_method end private def some_private_instance_method end end RUBY end end context 'when using a known method-creating method' do let(:config) do RuboCop::Config.new( 'Lint/UselessAccessModifier' => { 'MethodCreatingMethods' => ['delegate'] } ) end it 'is aware that this creates a new method' do expect_no_offenses(<<~RUBY) class SomeClass private delegate :foo, to: :bar end RUBY end it 'still points out redundant uses within the module' do expect_offense(<<~RUBY) class SomeClass delegate :foo, to: :bar private ^^^^^^^ Useless `private` access modifier. end RUBY expect_correction(<<~RUBY) class SomeClass delegate :foo, to: :bar end RUBY end end shared_examples 'at the top of the body' do |keyword| it 'registers an offense and corrects for `public`' do expect_offense(<<~RUBY) #{keyword} A public ^^^^^^ Useless `public` access modifier. def method end end RUBY expect_correction(<<~RUBY) #{keyword} A def method end end RUBY end it "doesn't register an offense for `protected`" do expect_no_offenses(<<~RUBY) #{keyword} A protected def method end end RUBY end it "doesn't register an offense for `private`" do expect_no_offenses(<<~RUBY) #{keyword} A private def method end end RUBY end end shared_examples 'repeated visibility modifiers' do |keyword, modifier| it "registers an offense when `#{modifier}` is repeated" do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A #{modifier == 'private' ? 'protected' : 'private'} def method1 end %{modifier} %{modifier} ^{modifier} Useless `#{modifier}` access modifier. def method2 end end RUBY end end shared_examples 'non-repeated visibility modifiers' do |keyword| it 'registers an offense and corrects even when `public` is not repeated' do expect_offense(<<~RUBY) #{keyword} A def method1 end public ^^^^^^ Useless `public` access modifier. def method2 end end RUBY expect_correction(<<~RUBY) #{keyword} A def method1 end def method2 end end RUBY end it "doesn't register an offense when `protected` is not repeated" do expect_no_offenses(<<~RUBY) #{keyword} A def method1 end protected def method2 end end RUBY end it "doesn't register an offense when `private` is not repeated" do expect_no_offenses(<<~RUBY) #{keyword} A def method1 end private def method2 end end RUBY end end shared_examples 'at the end of the body' do |keyword, modifier| it "registers an offense for trailing `#{modifier}`" do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A def method1 end def method2 end %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end end shared_examples 'nested in a begin..end block' do |keyword, modifier| it "still flags repeated `#{modifier}`" do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A #{modifier == 'private' ? 'protected' : 'private'} def blah end begin def method1 end %{modifier} %{modifier} ^{modifier} Useless `#{modifier}` access modifier. def method2 end end end RUBY end unless modifier == 'public' it "doesn't flag an access modifier from surrounding scope" do expect_no_offenses(<<~RUBY) #{keyword} A #{modifier} begin def method1 end end end RUBY end end end shared_examples 'method named by access modifier name' do |keyword, modifier| it "does not register an offense for `#{modifier}`" do expect_no_offenses(<<~RUBY) #{keyword} A def foo end do_something do { #{modifier}: #{modifier} } end end RUBY end end shared_examples 'unused visibility modifiers' do |keyword| it 'registers an offense and corrects when visibility is ' \ 'immediately changed without any intervening defs' do expect_offense(<<~RUBY) #{keyword} A private def method1 end public ^^^^^^ Useless `public` access modifier. private def method2 end end RUBY expect_correction(<<~RUBY, loop: false) #{keyword} A private def method1 end private def method2 end end RUBY end end shared_examples 'conditionally defined method' do |keyword, modifier| %w[if unless].each do |conditional_type| it "doesn't register an offense for #{conditional_type}" do expect_no_offenses(<<~RUBY) #{keyword} A #{modifier} #{conditional_type} x def method1 end end end RUBY end end end shared_examples 'methods defined in an iteration' do |keyword, modifier| %w[each map].each do |iteration_method| it "doesn't register an offense for #{iteration_method}" do expect_no_offenses(<<~RUBY) #{keyword} A #{modifier} [1, 2].#{iteration_method} do |i| define_method("method\#{i}") do i end end end RUBY end end end shared_examples 'method defined with define_method' do |keyword, modifier| it "doesn't register an offense if a block is passed" do expect_no_offenses(<<~RUBY) #{keyword} A #{modifier} define_method(:method1) do end end RUBY end %w[lambda proc ->].each do |proc_type| it "doesn't register an offense if a #{proc_type} is passed" do expect_no_offenses(<<~RUBY) #{keyword} A #{modifier} define_method(:method1, #{proc_type} { }) end RUBY end end end shared_examples 'method defined on a singleton class' do |keyword, modifier| context 'inside a class' do it "doesn't register an offense if a method is defined" do expect_no_offenses(<<~RUBY) #{keyword} A class << self #{modifier} define_method(:method1) do end end end RUBY end it "doesn't register an offense if the modifier is the same as outside the meta-class" do expect_no_offenses(<<~RUBY) #{keyword} A #{modifier} def method1 end class << self #{modifier} def method2 end end end RUBY end it 'registers an offense if no method is defined' do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A class << self %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end end RUBY end it 'registers an offense if no method is defined after the modifier' do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A class << self def method1 end %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end end RUBY end it 'registers an offense even if a non-singleton-class method is defined' do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A def method1 end class << self %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end end RUBY end end context 'outside a class' do it "doesn't register an offense if a method is defined" do expect_no_offenses(<<~RUBY) class << A #{modifier} define_method(:method1) do end end RUBY end it 'registers an offense if no method is defined' do expect_offense(<<~RUBY, modifier: modifier) class << A %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end it 'registers an offense if no method is defined after the modifier' do expect_offense(<<~RUBY, modifier: modifier) class << A def method1 end %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end end end shared_examples 'method defined using class_eval' do |modifier| it "doesn't register an offense if a method is defined" do expect_no_offenses(<<~RUBY) A.class_eval do #{modifier} define_method(:method1) do end end RUBY end it 'registers an offense if no method is defined' do expect_offense(<<~RUBY, modifier: modifier) A.class_eval do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end context 'inside a class' do it 'registers an offense when a modifier is outside the block and a method is defined only inside the block' do expect_offense(<<~RUBY, modifier: modifier) class A %{modifier} ^{modifier} Useless `#{modifier}` access modifier. A.class_eval do def method1 end end end RUBY end it 'registers two offenses when a modifier is inside and outside the block and no method is defined' do expect_offense(<<~RUBY, modifier: modifier) class A %{modifier} ^{modifier} Useless `#{modifier}` access modifier. A.class_eval do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end end RUBY end end end shared_examples 'def in new block' do |klass, modifier| it "doesn't register an offense if a method is defined in #{klass}.new" do expect_no_offenses(<<~RUBY) #{klass}.new do #{modifier} def foo end end RUBY end it "registers an offense if no method is defined in #{klass}.new" do expect_offense(<<~RUBY, modifier: modifier) #{klass}.new do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end end shared_examples 'method defined using instance_eval' do |modifier| it "doesn't register an offense if a method is defined" do expect_no_offenses(<<~RUBY) A.instance_eval do #{modifier} define_method(:method1) do end end RUBY end it 'registers an offense if no method is defined' do expect_offense(<<~RUBY, modifier: modifier) A.instance_eval do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end context 'inside a class' do it 'registers an offense when a modifier is outside the block and a ' \ 'method is defined only inside the block' do expect_offense(<<~RUBY, modifier: modifier) class A %{modifier} ^{modifier} Useless `#{modifier}` access modifier. self.instance_eval do def method1 end end end RUBY end it 'registers two offenses when a modifier is inside and outside the and no method is defined' do expect_offense(<<~RUBY, modifier: modifier) class A %{modifier} ^{modifier} Useless `#{modifier}` access modifier. self.instance_eval do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end end RUBY end end end shared_examples 'nested modules' do |keyword, modifier| it "doesn't register an offense for nested #{keyword}s" do expect_no_offenses(<<~RUBY) #{keyword} A #{modifier} def method1 end #{keyword} B def method2 end #{modifier} def method3 end end end RUBY end context 'unused modifiers' do it "registers an offense with a nested #{keyword}" do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A %{modifier} ^{modifier} Useless `#{modifier}` access modifier. #{keyword} B %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end end RUBY end it "registers an offense when outside a nested #{keyword}" do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A %{modifier} ^{modifier} Useless `#{modifier}` access modifier. #{keyword} B def method1 end end end RUBY end it "registers an offense when inside a nested #{keyword}" do expect_offense(<<~RUBY, modifier: modifier) #{keyword} A #{keyword} B %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end end RUBY end end end %w[protected private].each do |modifier| it_behaves_like('method defined using class_eval', modifier) it_behaves_like('method defined using instance_eval', modifier) end %w[Class ::Class Module ::Module Struct ::Struct].each do |klass| %w[protected private].each do |modifier| it_behaves_like('def in new block', klass, modifier) end end context '`def` in `Data.define` block', :ruby32 do %w[protected private].each do |modifier| it "doesn't register an offense if a method is defined in `Data.define` with block" do expect_no_offenses(<<~RUBY) Data.define do #{modifier} def foo end end RUBY end it 'registers an offense if no method is defined in `Data.define` with block' do expect_offense(<<~RUBY, modifier: modifier) Data.define do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end it 'registers an offense if no method is defined in `::Data.define` with block' do expect_offense(<<~RUBY, modifier: modifier) ::Data.define do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. end RUBY end it 'registers an offense if no method is defined in `Data.define` with numblock' do expect_offense(<<~RUBY, modifier: modifier) Data.define do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. do_something(_1) end RUBY end it 'registers an offense if no method is defined in `Data.define` with itblock', :ruby34 do expect_offense(<<~RUBY, modifier: modifier) Data.define do %{modifier} ^{modifier} Useless `#{modifier}` access modifier. do_something(it) end RUBY end end end %w[module class].each do |keyword| it_behaves_like('at the top of the body', keyword) it_behaves_like('non-repeated visibility modifiers', keyword) it_behaves_like('unused visibility modifiers', keyword) %w[public protected private].each do |modifier| it_behaves_like('repeated visibility modifiers', keyword, modifier) it_behaves_like('at the end of the body', keyword, modifier) it_behaves_like('nested in a begin..end block', keyword, modifier) it_behaves_like('method named by access modifier name', keyword, modifier) next if modifier == 'public' it_behaves_like('conditionally defined method', keyword, modifier) it_behaves_like('methods defined in an iteration', keyword, modifier) it_behaves_like('method defined with define_method', keyword, modifier) it_behaves_like('method defined on a singleton class', keyword, modifier) it_behaves_like('nested modules', keyword, modifier) end end context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do let(:config) do RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => true }) end context 'when using same access modifier inside and outside the included block' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class SomeClass included do private def foo; end end private def bar; end end RUBY end it 'registers an offense when using repeated access modifier inside/outside the included block' do expect_offense(<<~RUBY) class SomeClass included do private private ^^^^^^^ Useless `private` access modifier. def foo; end end private private ^^^^^^^ Useless `private` access modifier. def bar; end end RUBY expect_correction(<<~RUBY) class SomeClass included do private def foo; end end private def bar; end end RUBY end end end context 'when `AllCops/ActiveSupportExtensionsEnabled: false`' do let(:config) do RuboCop::Config.new('AllCops' => { 'ActiveSupportExtensionsEnabled' => false }) end context 'when using same access modifier inside and outside the `included` block' do it 'registers an offense' do expect_offense(<<~RUBY) class SomeClass included do private def foo; end end private ^^^^^^^ Useless `private` access modifier. def bar; end end RUBY expect_correction(<<~RUBY) class SomeClass included do private def foo; end end def bar; end end RUBY end it 'registers an offense when using repeated access modifier inside/outside the `included` block' do expect_offense(<<~RUBY) class SomeClass included do private private ^^^^^^^ Useless `private` access modifier. def foo; end end private ^^^^^^^ Useless `private` access modifier. private ^^^^^^^ Useless `private` access modifier. def bar; end end RUBY expect_correction(<<~RUBY) class SomeClass included do private def foo; end end def bar; 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/lint/non_atomic_file_operation_spec.rb
spec/rubocop/cop/lint/non_atomic_file_operation_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NonAtomicFileOperation, :config do it 'registers an offense when use `FileTest.exist?` before creating file' do expect_offense(<<~RUBY) unless FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.mkdir(path) ^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.mkdir_p`. end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.mkdir_p(path) RUBY end %i[makedirs mkdir_p mkpath].each do |make_method| it 'registers an offense when use `FileTest.exist?` before force creating file' do expect_offense(<<~RUBY) unless FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.#{make_method}(path) end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.#{make_method}(path) RUBY end end %i[remove delete unlink remove_file rm rmdir safe_unlink].each do |remove_method| it 'registers an offense when use `FileTest.exist?` before remove file' do expect_offense(<<~RUBY, remove_method: remove_method) if FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.#{remove_method}(path) ^^^^^^^^^^^{remove_method}^^^^^^ Use atomic file operation method `FileUtils.rm_f`. end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.rm_f(path) RUBY end end %i[remove_dir remove_entry remove_entry_secure].each do |remove_method| it 'registers an offense when use `FileTest.exist?` before recursive remove file' do expect_offense(<<~RUBY, remove_method: remove_method) if FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.#{remove_method}(path) ^^^^^^^^^^^{remove_method}^^^^^^ Use atomic file operation method `FileUtils.rm_rf`. end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.rm_rf(path) RUBY end end %i[rm_f rm_rf].each do |remove_method| it 'registers an offense when use `FileTest.exist?` before force remove file' do expect_offense(<<~RUBY) if FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.#{remove_method}(path) end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.#{remove_method}(path) RUBY end end %i[rm_r rmtree].each do |remove_method| it 'does not register an offense when use `FileTest.exist?` before remove recursive file' do expect_no_offenses(<<~RUBY) if FileTest.exist?(path) FileUtils.#{remove_method}(path) end RUBY end end it 'registers an offense when use `FileTest.exist?` before creating file with an option `force: true`' do expect_offense(<<~RUBY) unless FileTest.exists?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exists?`. FileUtils.makedirs(path, force: true) end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.makedirs(path, force: true) RUBY end it 'registers an offense when using `FileTest.exist?` as a condition for `elsif`' do expect_offense(<<~RUBY) if condition do_something elsif FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.rm_f path end RUBY expect_no_corrections end it 'does not register an offense when use `FileTest.exist?` before creating file with an option `force: false`' do expect_no_offenses(<<~RUBY) unless FileTest.exists?(path) FileUtils.makedirs(path, force: false) end RUBY end it 'registers an offense when use `FileTest.exist?` before creating file with an option not `force`' do expect_offense(<<~RUBY) unless FileTest.exists?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exists?`. FileUtils.makedirs(path, verbose: true) end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.makedirs(path, verbose: true) RUBY end it 'registers an offense when use `FileTest.exists?` before creating file' do expect_offense(<<~RUBY) unless FileTest.exists?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exists?`. FileUtils.makedirs(path) end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.makedirs(path) RUBY end it 'registers an offense when use `FileTest.exist?` with negated `if` before creating file' do expect_offense(<<~RUBY) if !FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.makedirs(path) end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.makedirs(path) RUBY end it 'registers an offense when use file existence checks `unless` by postfix before creating file' do expect_offense(<<~RUBY) FileUtils.mkdir(path) unless FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. ^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.mkdir_p`. RUBY expect_correction(<<~RUBY) FileUtils.mkdir_p(path) RUBY end it 'registers an offense when use file existence checks `unless` by postfix before creating file while Dir.mkdir has 2 arguments' do expect_offense(<<~RUBY) Dir.mkdir(path, 0o0755) unless Dir.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `Dir.exist?`. ^^^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.mkdir_p`. RUBY expect_correction(<<~RUBY) FileUtils.mkdir_p(path, mode: 0o0755) RUBY end it 'registers an offense when use file existence checks `unless` by postfix before creating file while Dir.mkdir has an argument' do expect_offense(<<~RUBY) Dir.mkdir(path) unless Dir.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `Dir.exist?`. ^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.mkdir_p`. RUBY expect_correction(<<~RUBY) FileUtils.mkdir_p(path) RUBY end it 'registers an offense when use file existence checks `if` by postfix before removing file' do expect_offense(<<~RUBY) FileUtils.remove(path) if FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. ^^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.rm_f`. RUBY expect_correction(<<~RUBY) FileUtils.rm_f(path) RUBY end it 'registers an offense when use file existence checks line break `unless` by postfix before creating file' do expect_offense(<<~RUBY) FileUtils.mkdir(path) unless ^^^^^^ Remove unnecessary existence check `FileTest.exist?`. ^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.mkdir_p`. FileTest.exist?(path) RUBY expect_correction(<<~RUBY) FileUtils.mkdir_p(path) RUBY end it 'registers an offense when use file existence checks line break `unless` (wrapped the in parentheses) by postfix before creating file' do expect_offense(<<~RUBY) FileUtils.mkdir(path) unless ( ^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. ^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.mkdir_p`. FileTest.exist?(path)) RUBY expect_correction(<<~RUBY) FileUtils.mkdir_p(path) RUBY end context 'with fully-qualified constant names' do it 'registers an offense when existence check uses fully qualified constant name' do expect_offense(<<~RUBY) if ::FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. FileUtils.delete(path) ^^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.rm_f`. end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}FileUtils.rm_f(path) RUBY end it 'registers an offense when file method uses fully qualified constant name' do expect_offense(<<~RUBY) if FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. ::FileUtils.delete(path) ^^^^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.rm_f`. end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}::FileUtils.rm_f(path) RUBY end it 'registers an offense when both methods use fully qualified constant name' do expect_offense(<<~RUBY) if ::FileTest.exist?(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove unnecessary existence check `FileTest.exist?`. ::FileUtils.delete(path) ^^^^^^^^^^^^^^^^^^^^^^^^ Use atomic file operation method `FileUtils.rm_f`. end RUBY expect_correction(<<~RUBY) #{trailing_whitespace}#{trailing_whitespace}::FileUtils.rm_f(path) RUBY end end it 'does not register an offense when not checking for the existence' do expect_no_offenses(<<~RUBY) FileUtils.mkdir_p(path) RUBY end it 'does not register an offense when checking for the existence of different files' do expect_no_offenses(<<~RUBY) FileUtils.mkdir_p(y) unless FileTest.exist?(path) RUBY end it 'does not register an offense when not a method of file operation' do expect_no_offenses(<<~RUBY) unless FileUtils.exist?(path) FileUtils.options_of(:rm) end unless FileUtils.exist?(path) NotFile.remove(path) end RUBY end it 'does not register an offense when not an exist check' do expect_no_offenses(<<~RUBY) unless FileUtils.options_of(:rm) FileUtils.mkdir_p(path) end if FileTest.executable?(path) FileUtils.remove(path) end RUBY end it 'does not register an offense when processing other than file operations' do expect_no_offenses(<<~RUBY) unless FileTest.exist?(path) FileUtils.makedirs(path) do_something end unless FileTest.exist?(path) do_something FileUtils.makedirs(path) end RUBY end it 'does not register an offense when using `FileTest.exist?` with `if` condition that has `else` branch' do expect_no_offenses(<<~RUBY) if FileTest.exist?(path) FileUtils.mkdir(path) else do_something end RUBY end it 'does not register an offense when using complex conditional with `&&`' do expect_no_offenses(<<~RUBY) if FileTest.exist?(path) && File.stat(path).socket? FileUtils.mkdir(path) end RUBY end it 'does not register an offense when using complex conditional with `||`' do expect_no_offenses(<<~RUBY) if FileTest.exist?(path) || condition FileUtils.mkdir(path) end RUBY end it 'does not register an offense without explicit receiver' do expect_no_offenses(<<~RUBY) mkdir(path) unless FileTest.exist?(path) RUBY end it 'does not register an offense with non-constant receiver' do expect_no_offenses(<<~RUBY) storage[:files].delete(file) unless File.exists?(file) 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/lint/erb_new_arguments_spec.rb
spec/rubocop/cop/lint/erb_new_arguments_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ErbNewArguments, :config do context '<= Ruby 2.5', :ruby25, unsupported_on: :prism do it 'does not register an offense when using `ERB.new` with non-keyword arguments' do expect_no_offenses(<<~RUBY) ERB.new(str, nil, '-', '@output_buffer') RUBY end end context '>= Ruby 2.6', :ruby26 do it 'registers an offense when using `ERB.new` with non-keyword 2nd argument' do expect_offense(<<~RUBY) ERB.new(str, nil) ^^^ Passing safe_level with the 2nd argument of `ERB.new` is deprecated. Do not use it, and specify other arguments as keyword arguments. RUBY expect_correction(<<~RUBY) ERB.new(str) RUBY end it 'registers an offense when using `ERB.new` with non-keyword 2nd and 3rd arguments' do expect_offense(<<~RUBY) ERB.new(str, nil, '-') ^^^ Passing trim_mode with the 3rd argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, trim_mode: '-')` instead. ^^^ Passing safe_level with the 2nd argument of `ERB.new` is deprecated. Do not use it, and specify other arguments as keyword arguments. RUBY expect_correction(<<~RUBY) ERB.new(str, trim_mode: '-') RUBY end it 'registers an offense when using `ERB.new` with non-keyword 2nd, 3rd and 4th arguments' do expect_offense(<<~RUBY) ERB.new(str, nil, '-', '@output_buffer') ^^^^^^^^^^^^^^^^ Passing eoutvar with the 4th argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, eoutvar: '@output_buffer')` instead. ^^^ Passing trim_mode with the 3rd argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, trim_mode: '-')` instead. ^^^ Passing safe_level with the 2nd argument of `ERB.new` is deprecated. Do not use it, and specify other arguments as keyword arguments. RUBY expect_correction(<<~RUBY) ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') RUBY end it 'registers an offense when using `ERB.new` ' \ 'with non-keyword 2nd, 3rd and 4th arguments and' \ 'keyword 5th argument' do expect_offense(<<~RUBY) ERB.new(str, nil, '-', '@output_buffer', trim_mode: '-', eoutvar: '@output_buffer') ^^^^^^^^^^^^^^^^ Passing eoutvar with the 4th argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, eoutvar: '@output_buffer')` instead. ^^^ Passing trim_mode with the 3rd argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, trim_mode: '-')` instead. ^^^ Passing safe_level with the 2nd argument of `ERB.new` is deprecated. Do not use it, and specify other arguments as keyword arguments. RUBY expect_correction(<<~RUBY) ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') RUBY end it 'registers an offense when using `ERB.new` ' \ 'with non-keyword 2nd and 3rd arguments and' \ 'keyword 4th argument' do expect_offense(<<~RUBY) ERB.new(str, nil, '-', trim_mode: '-', eoutvar: '@output_buffer') ^^^ Passing trim_mode with the 3rd argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, trim_mode: '-')` instead. ^^^ Passing safe_level with the 2nd argument of `ERB.new` is deprecated. Do not use it, and specify other arguments as keyword arguments. RUBY expect_correction(<<~RUBY) ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') RUBY end it 'registers an offense when using `::ERB.new` with non-keyword 2nd, 3rd and 4th arguments' do expect_offense(<<~RUBY) ::ERB.new(str, nil, '-', '@output_buffer') ^^^^^^^^^^^^^^^^ Passing eoutvar with the 4th argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, eoutvar: '@output_buffer')` instead. ^^^ Passing trim_mode with the 3rd argument of `ERB.new` is deprecated. Use keyword argument like `ERB.new(str, trim_mode: '-')` instead. ^^^ Passing safe_level with the 2nd argument of `ERB.new` is deprecated. Do not use it, and specify other arguments as keyword arguments. RUBY expect_correction(<<~RUBY) ::ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') RUBY end it 'does not register an offense when using `ERB.new` with keyword arguments' do expect_no_offenses(<<~RUBY) ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') RUBY end it 'does not register an offense when using `ERB.new` without optional arguments' do expect_no_offenses(<<~RUBY) ERB.new(str) RUBY end context 'when using `ActionView::Template::Handlers::ERB.new`' do it 'does not register an offense when using `ERB.new` without arguments' do expect_no_offenses(<<~RUBY) ERB.new 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/lint/useless_assignment_spec.rb
spec/rubocop/cop/lint/useless_assignment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessAssignment, :config do context 'when a variable is assigned and assigned again in a modifier condition' do it 'accepts with parentheses' do expect_no_offenses(<<~RUBY) a = nil puts a if (a = 123) RUBY end it 'accepts without parentheses' do expect_no_offenses(<<~RUBY) a = nil puts a unless a = 123 RUBY end end context 'when a variable is assigned and assigned again in a modifier loop condition' do it 'accepts with parentheses' do expect_no_offenses(<<~RUBY) a = nil puts a while (a = false) RUBY end it 'accepts without parentheses' do expect_no_offenses(<<~RUBY) a = nil puts a until a = true RUBY end end context 'when a variable is assigned and unreferenced in a method' do it 'registers an offense' do expect_offense(<<~RUBY) class SomeClass foo = 1 puts foo def some_method foo = 2 ^^^ Useless assignment to variable - `foo`. bar = 3 puts bar end end RUBY expect_correction(<<~RUBY) class SomeClass foo = 1 puts foo def some_method 2 bar = 3 puts bar end end RUBY end end context 'when a variable is assigned and unreferenced ' \ 'in a singleton method defined with self keyword' do it 'registers an offense' do expect_offense(<<~RUBY) class SomeClass foo = 1 puts foo def self.some_method foo = 2 ^^^ Useless assignment to variable - `foo`. bar = 3 puts bar end end RUBY expect_correction(<<~RUBY) class SomeClass foo = 1 puts foo def self.some_method 2 bar = 3 puts bar end end RUBY end end context 'when a variable is assigned and unreferenced ' \ 'in a singleton method defined with variable name' do it 'registers an offense' do expect_offense(<<~RUBY) 1.times do foo = 1 puts foo instance = Object.new def instance.some_method foo = 2 ^^^ Useless assignment to variable - `foo`. bar = 3 puts bar end end RUBY expect_correction(<<~RUBY) 1.times do foo = 1 puts foo instance = Object.new def instance.some_method 2 bar = 3 puts bar end end RUBY end end context 'when a variable is assigned and unreferenced in a class' do it 'registers an offense' do expect_offense(<<~RUBY) 1.times do foo = 1 puts foo class SomeClass foo = 2 ^^^ Useless assignment to variable - `foo`. bar = 3 puts bar end end RUBY expect_correction(<<~RUBY) 1.times do foo = 1 puts foo class SomeClass 2 bar = 3 puts bar end end RUBY end end context 'when a variable is assigned and unreferenced in a class ' \ 'subclassing another class stored in local variable' do it 'registers an offense' do expect_offense(<<~RUBY) 1.times do foo = 1 puts foo array_class = Array class SomeClass < array_class foo = 2 ^^^ Useless assignment to variable - `foo`. bar = 3 puts bar end end RUBY expect_correction(<<~RUBY) 1.times do foo = 1 puts foo array_class = Array class SomeClass < array_class 2 bar = 3 puts bar end end RUBY end end context 'when a variable is assigned and unreferenced in a singleton class' do it 'registers an offense' do expect_offense(<<~RUBY) 1.times do foo = 1 puts foo instance = Object.new class << instance foo = 2 ^^^ Useless assignment to variable - `foo`. bar = 3 puts bar end end RUBY expect_correction(<<~RUBY) 1.times do foo = 1 puts foo instance = Object.new class << instance 2 bar = 3 puts bar end end RUBY end end context 'when a variable is assigned and unreferenced in a module' do it 'registers an offense' do expect_offense(<<~RUBY) 1.times do foo = 1 puts foo module SomeModule foo = 2 ^^^ Useless assignment to variable - `foo`. bar = 3 puts bar end end RUBY expect_correction(<<~RUBY) 1.times do foo = 1 puts foo module SomeModule 2 bar = 3 puts bar end end RUBY end end context 'when a variable is assigned and referenced when defining a module' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) x = Object.new module x::Foo end RUBY end end context 'when a variable is assigned and unreferenced in `for`' do it 'registers an offense' do expect_offense(<<~RUBY) for item in items ^^^^ Useless assignment to variable - `item`. Did you mean `items`? end RUBY expect_correction(<<~RUBY) for _ in items end RUBY end end context 'when a variable is assigned before `for`' do it 'registers an offense when it is not referenced' do expect_offense(<<~RUBY) node = foo ^^^^ Useless assignment to variable - `node`. for node in bar return node if baz? end RUBY expect_correction(<<~RUBY) foo for node in bar return node if baz? end RUBY end it 'registers no offense when the variable is referenced in the collection' do expect_no_offenses(<<~RUBY) node = foo for node in node.children return node if bar? end RUBY end end context 'when a variable is assigned and unreferenced in `for` with multiple variables' do it 'registers an offense' do expect_offense(<<~RUBY) for i, j in items ^ Useless assignment to variable - `j`. do_something(i) end RUBY expect_correction(<<~RUBY) for i, _ in items do_something(i) end RUBY end end context 'when a variable is assigned and referenced in `for`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) for item in items do_something(item) end RUBY end end context 'when a variable is assigned and unreferenced in top level' do it 'registers an offense' do expect_offense(<<~RUBY) foo = 1 ^^^ Useless assignment to variable - `foo`. bar = 2 puts bar RUBY expect_correction(<<~RUBY) 1 bar = 2 puts bar RUBY end end context 'when a variable is assigned with operator assignment in top level' do it 'registers an offense' do expect_offense(<<~RUBY) foo ||= 1 ^^^ Useless assignment to variable - `foo`. Use `||` instead of `||=`. RUBY expect_no_corrections end end context 'when a variable is assigned multiple times but unreferenced' do it 'registers offenses for each assignment' do expect_offense(<<~RUBY) def some_method foo = 1 ^^^ Useless assignment to variable - `foo`. bar = 2 foo = 3 ^^^ Useless assignment to variable - `foo`. puts bar end RUBY expect_correction(<<~RUBY) def some_method 1 bar = 2 3 puts bar end RUBY end end context 'when a referenced variable is reassigned but not re-referenced' do it 'registers an offense for the non-re-referenced assignment' do expect_offense(<<~RUBY) def some_method foo = 1 puts foo foo = 3 ^^^ Useless assignment to variable - `foo`. end RUBY expect_correction(<<~RUBY) def some_method foo = 1 puts foo 3 end RUBY end end context 'when an unreferenced variable is reassigned and re-referenced' do it 'registers an offense for the unreferenced assignment' do expect_offense(<<~RUBY) def some_method foo = 1 ^^^ Useless assignment to variable - `foo`. foo = 3 puts foo end RUBY expect_correction(<<~RUBY) def some_method 1 foo = 3 puts foo end RUBY end end context 'when an unreferenced variable is reassigned in a block' do it 'accepts' do expect_no_offenses(<<~RUBY) def const_name(node) const_names = [] const_node = node loop do namespace_node, name = *const_node const_names << name break unless namespace_node break if namespace_node.type == :cbase const_node = namespace_node end const_names.reverse.join('::') end RUBY end end context 'when a referenced variable is reassigned in a block' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method foo = 1 puts foo 1.times do foo = 2 end end RUBY end end context 'when a block local variable is declared but not assigned' do it 'accepts' do expect_no_offenses(<<~RUBY) 1.times do |i; foo| end RUBY end end context 'when a block local variable is assigned and unreferenced' do it 'registers offenses for the assignment' do expect_offense(<<~RUBY) 1.times do |i; foo| foo = 2 ^^^ Useless assignment to variable - `foo`. end RUBY expect_correction(<<~RUBY) 1.times do |i; foo| 2 end RUBY end it 'registers offenses for self assignment in numblock', :ruby27 do expect_offense(<<~RUBY) do_something { foo += _1 } ^^^ Useless assignment to variable - `foo`. Use `+` instead of `+=`. RUBY expect_correction(<<~RUBY) do_something { foo + _1 } RUBY end it 'registers offenses for self assignment in itblock', :ruby34 do expect_offense(<<~RUBY) do_something { foo += it } ^^^ Useless assignment to variable - `foo`. Use `+` instead of `+=`. RUBY expect_correction(<<~RUBY) do_something { foo + it } RUBY end end context 'when a variable is assigned in loop body and unreferenced' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method while true foo = 1 ^^^ Useless assignment to variable - `foo`. end end RUBY expect_correction(<<~RUBY) def some_method while true 1 end end RUBY end end context 'when a variable is reassigned at the end of loop body ' \ 'and would be referenced in next iteration' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method total = 0 foo = 0 while total < 100 total += foo foo += 1 end total end RUBY end end context 'when a variable is reassigned at the end of loop body ' \ 'and would be referenced in loop condition' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method total = 0 foo = 0 while foo < 100 total += 1 foo += 1 end total end RUBY end end context 'when a setter is invoked with operator assignment in loop body' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method obj = {} while obj[:count] < 100 obj[:count] += 1 end end RUBY end end context 'when a variable is reassigned before a block' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = 1 ^^^ Useless assignment to variable - `foo`. foo = 2 bar { foo = 3 } end RUBY end end context 'when a variable is reassigned in another branch before a block' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method if baz foo = 1 else foo = 2 bar { foo = 3 } end foo end RUBY end end context 'when a variable is reassigned in another case branch before a block' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method case baz when 1 foo = 1 else foo = 2 bar { foo = 3 } end foo end RUBY end end context 'when assigning in branch' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method changed = false if Random.rand > 1 changed = true end [].each do changed = true end puts changed end RUBY end end context 'when assigning in case' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method changed = false case Random.rand when 0.5 changed = true when 1..20 changed = false when 21..70 changed = true end [].each do changed = true end puts changed end RUBY end end context "when a variable is reassigned in loop body but won't " \ 'be referenced either next iteration or loop condition' do it 'registers an offense' do pending 'Requires advanced logic that checks whether the return ' \ 'value of an operator assignment is used or not.' expect_offense(<<~RUBY) def some_method total = 0 foo = 0 while total < 100 total += 1 foo += 1 ^^^ Useless assignment to variable - `foo`. end total end RUBY expect_correction(<<~RUBY) def some_method total = 0 foo = 0 while total < 100 total += 1 foo = 1 end total end RUBY end end context 'when a referenced variable is reassigned ' \ 'but not re-referenced in a method defined in loop' do it 'registers an offense' do expect_offense(<<~RUBY) while true def some_method foo = 1 puts foo foo = 3 ^^^ Useless assignment to variable - `foo`. end end RUBY expect_correction(<<~RUBY) while true def some_method foo = 1 puts foo 3 end end RUBY end end context 'when a variable that has same name as outer scope variable ' \ 'is not referenced in a method defined in loop' do it 'registers an offense' do expect_offense(<<~RUBY) foo = 1 while foo < 100 foo += 1 def some_method foo = 1 ^^^ Useless assignment to variable - `foo`. end end RUBY expect_correction(<<~RUBY) foo = 1 while foo < 100 foo += 1 def some_method 1 end end RUBY end end context 'when a variable is assigned in single branch if and unreferenced' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(flag) if flag foo = 1 ^^^ Useless assignment to variable - `foo`. end end RUBY expect_correction(<<~RUBY) def some_method(flag) if flag 1 end end RUBY end end context 'when an unreferenced variable is reassigned in same branch ' \ 'and referenced after the branching' do it 'registers an offense for the unreferenced assignment' do expect_offense(<<~RUBY) def some_method(flag) if flag foo = 1 ^^^ Useless assignment to variable - `foo`. foo = 2 end foo end RUBY expect_correction(<<~RUBY) def some_method(flag) if flag 1 foo = 2 end foo end RUBY end end context 'when a variable is reassigned in single branch if and referenced after the branching' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method(flag) foo = 1 if flag foo = 2 end foo end RUBY end end context 'when a variable is reassigned in a loop' do context 'while loop' do it 'accepts' do expect_no_offenses(<<~RUBY) def while(param) ret = 1 while param != 10 param += 2 ret = param + 1 end ret end RUBY end end context 'post while loop' do it 'accepts' do expect_no_offenses(<<~RUBY) def post_while(param) ret = 1 begin param += 2 ret = param + 1 end while param < 40 ret end RUBY end end context 'until loop' do it 'accepts' do expect_no_offenses(<<~RUBY) def until(param) ret = 1 until param == 10 param += 2 ret = param + 1 end ret end RUBY end end context 'post until loop' do it 'accepts' do expect_no_offenses(<<~RUBY) def post_until(param) ret = 1 begin param += 2 ret = param + 1 end until param == 10 ret end RUBY end end context 'for loop' do it 'accepts' do expect_no_offenses(<<~RUBY) def for(param) ret = 1 for x in param...10 param += x ret = param + 1 end ret end RUBY end end end context 'when a variable is assigned in each branch of if and referenced after the branching' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method(flag) if flag foo = 2 else foo = 3 end foo end RUBY end end context 'when a variable is reassigned in single branch if and referenced in the branch' do it 'registers an offense for the unreferenced assignment' do expect_offense(<<~RUBY) def some_method(flag) foo = 1 ^^^ Useless assignment to variable - `foo`. if flag foo = 2 puts foo end end RUBY expect_correction(<<~RUBY) def some_method(flag) 1 if flag foo = 2 puts foo end end RUBY end end context 'when a variable is assigned in each branch of if and referenced in the else branch' do it 'registers an offense for the assignment in the if branch' do expect_offense(<<~RUBY) def some_method(flag) if flag foo = 2 ^^^ Useless assignment to variable - `foo`. else foo = 3 puts foo end end RUBY expect_correction(<<~RUBY) def some_method(flag) if flag 2 else foo = 3 puts foo end end RUBY end end context 'when a variable is reassigned and unreferenced in an if branch ' \ 'while the variable is referenced in the paired else branch' do it 'registers an offense for the reassignment in the if branch' do expect_offense(<<~RUBY) def some_method(flag) foo = 1 if flag puts foo foo = 2 ^^^ Useless assignment to variable - `foo`. else puts foo end end RUBY expect_correction(<<~RUBY) def some_method(flag) foo = 1 if flag puts foo 2 else puts foo end end RUBY end end context "when there's an unreferenced assignment in top level if branch " \ 'while the variable is referenced in the paired else branch' do it 'registers an offense for the assignment in the if branch' do expect_offense(<<~RUBY) if flag foo = 1 ^^^ Useless assignment to variable - `foo`. else puts foo end RUBY expect_correction(<<~RUBY) if flag 1 else puts foo end RUBY end end context "when there's an unreferenced reassignment in an if branch " \ 'while the variable is referenced in the paired elsif branch' do it 'registers an offense for the reassignment in the if branch' do expect_offense(<<~RUBY) def some_method(flag_a, flag_b) foo = 1 if flag_a puts foo foo = 2 ^^^ Useless assignment to variable - `foo`. elsif flag_b puts foo end end RUBY expect_correction(<<~RUBY) def some_method(flag_a, flag_b) foo = 1 if flag_a puts foo 2 elsif flag_b puts foo end end RUBY end end context "when there's an unreferenced reassignment in an if branch " \ 'while the variable is referenced in a case branch ' \ 'in the paired else branch' do it 'registers an offense for the reassignment in the if branch' do expect_offense(<<~RUBY) def some_method(flag_a, flag_b) foo = 1 if flag_a puts foo foo = 2 ^^^ Useless assignment to variable - `foo`. else case when flag_b puts foo end end end RUBY expect_correction(<<~RUBY) def some_method(flag_a, flag_b) foo = 1 if flag_a puts foo 2 else case when flag_b puts foo end end end RUBY end end context 'when an assignment in an if branch is referenced in another if branch' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method(flag_a, flag_b) if flag_a foo = 1 end if flag_b puts foo end end RUBY end end context 'when a variable is assigned in branch of modifier if ' \ 'that references the variable in its conditional clause' \ 'and referenced after the branching' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method(flag) foo = 1 unless foo puts foo end RUBY end end context 'when a variable is assigned in branch of modifier if ' \ 'that references the variable in its conditional clause' \ 'and unreferenced' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method(flag) foo = 1 unless foo ^^^ Useless assignment to variable - `foo`. end RUBY expect_correction(<<~RUBY) def some_method(flag) 1 unless foo end RUBY end end context 'when a variable is assigned on each side of && and referenced after the &&' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method (foo = do_something_returns_object_or_nil) && (foo = 1) foo end RUBY end end context 'when an unreferenced variable is reassigned ' \ 'on the left side of && and referenced after the &&' do it 'registers an offense for the unreferenced assignment' do expect_offense(<<~RUBY) def some_method foo = 1 ^^^ Useless assignment to variable - `foo`. (foo = do_something_returns_object_or_nil) && do_something foo end RUBY expect_correction(<<~RUBY) def some_method 1 (foo = do_something_returns_object_or_nil) && do_something foo end RUBY end end context 'when an unreferenced variable is reassigned ' \ 'on the right side of && and referenced after the &&' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method foo = 1 do_something_returns_object_or_nil && foo = 2 foo end RUBY end end context 'when a variable is reassigned while referencing itself in rhs and referenced' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method foo = [1, 2] foo = foo.map { |i| i + 1 } puts foo end RUBY end it 'registers an offense when the reassignment is the last statement' do expect_offense(<<~RUBY) foo = [1, 2] foo = foo.map { |i| i + 1 } ^^^ Useless assignment to variable - `foo`. RUBY expect_correction(<<~RUBY) foo = [1, 2] foo.map { |i| i + 1 } RUBY end end context 'when a variable is reassigned with binary operator assignment and referenced' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method foo = 1 foo += 1 foo end RUBY end end context 'when a variable is reassigned with logical operator assignment and referenced' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method foo = do_something_returns_object_or_nil foo ||= 1 foo end RUBY end end context 'when a variable is reassigned with binary operator ' \ 'assignment while assigning to itself in rhs ' \ 'then referenced' do it 'registers an offense for the assignment in rhs' do expect_offense(<<~RUBY) def some_method foo = 1 foo += foo = 2 ^^^ Useless assignment to variable - `foo`. foo end RUBY expect_correction(<<~RUBY) def some_method foo = 1 foo += 2 foo end RUBY end end context 'when a variable is assigned first with ||= and referenced' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method foo ||= 1 foo end RUBY end end context 'when a variable is assigned with ||= at the last expression of the scope' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = do_something_returns_object_or_nil foo ||= 1 ^^^ Useless assignment to variable - `foo`. Use `||` instead of `||=`. end RUBY expect_no_corrections end end context 'when a variable is assigned with ||= before the last expression of the scope' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = do_something_returns_object_or_nil foo ||= 1 ^^^ Useless assignment to variable - `foo`. some_return_value end RUBY expect_no_corrections end end context 'when a variable is assigned with multiple assignment and unreferenced' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo, bar = do_something ^^^ Useless assignment to variable - `bar`. Use `_` or `_bar` as a variable name to indicate that it won't be used. puts foo end RUBY expect_correction(<<~RUBY) def some_method foo, _ = do_something puts foo end RUBY end end context 'when a variable is assigned as an argument to a method given to multiple assignment' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method a, b = func(c = 3) ^ Useless assignment to variable - `c`. [a, b] end RUBY expect_correction(<<~RUBY) def some_method a, b = func(3) [a, b] end RUBY end end context 'when a variable is assigned as an argument to a method given to multiple assignment and later used' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) def some_method a, b = func(c = 3) [a, b, c] end RUBY end end context 'when variables are assigned using chained assignment and remain unreferenced' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = bar = do_something ^^^ Useless assignment to variable - `foo`. end RUBY expect_correction(<<~RUBY) def some_method bar = do_something end RUBY end end context 'when same name variables are assigned using chained assignment' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = foo = do_something ^^^ Useless assignment to variable - `foo`. end RUBY expect_correction(<<~RUBY) def some_method foo = do_something end RUBY end end context 'when variables are assigned using unary operator in chained assignment and remain unreferenced' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = -bar = do_something ^^^ Useless assignment to variable - `foo`. end RUBY expect_correction(<<~RUBY) def some_method -bar = do_something end RUBY end end context 'when variables are assigned with sequential assignment using the comma operator and unreferenced' do it 'registers an offense' do expect_offense(<<~RUBY) def some_method foo = 1, bar = 2 ^^^ Useless assignment to variable - `foo`. ^^^ Useless assignment to variable - `bar`. end RUBY # NOTE: Removing the unused variables causes a syntax error, so it can't be autocorrected. expect_no_corrections end end context 'when a variable is reassigned with multiple assignment ' \ 'while referencing itself in rhs and referenced' do it 'accepts' do expect_no_offenses(<<~RUBY) def some_method foo = 1 foo, bar = do_something(foo) puts foo, bar end RUBY end end context 'when part of a multiple assignment is enclosed in parentheses' do
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
true
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/useless_times_spec.rb
spec/rubocop/cop/lint/useless_times_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessTimes, :config do it 'registers an offense and corrects with 0.times' do expect_offense(<<~RUBY) 0.times { something } ^^^^^^^^^^^^^^^^^^^^^ Useless call to `0.times` detected. RUBY expect_correction('') end it 'registers an offense and corrects with 0.times with block arg' do expect_offense(<<~RUBY) 0.times { |i| something(i) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless call to `0.times` detected. RUBY expect_correction('') end it 'registers an offense and corrects with negative times' do expect_offense(<<~RUBY) -1.times { something } ^^^^^^^^^^^^^^^^^^^^^^ Useless call to `-1.times` detected. RUBY expect_correction('') end it 'registers an offense and corrects with negative times with block arg' do expect_offense(<<~RUBY) -1.times { |i| something(i) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless call to `-1.times` detected. RUBY expect_correction('') end it 'registers an offense and corrects with 1.times' do expect_offense(<<~RUBY) 1.times { something } ^^^^^^^^^^^^^^^^^^^^^ Useless call to `1.times` detected. RUBY expect_correction(<<~RUBY) something RUBY end it 'registers an offense and corrects with 1.times with block arg' do expect_offense(<<~RUBY) 1.times { |i| something(i) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Useless call to `1.times` detected. RUBY expect_correction(<<~RUBY) something(0) RUBY end it 'registers an offense but does not correct with 1.times with method chain' do expect_offense(<<~RUBY) 1.times.reverse_each do ^^^^^^^ Useless call to `1.times` detected. foo end RUBY expect_no_corrections end it 'registers an offense and corrects when 1.times with empty block argument' do expect_offense(<<~RUBY) def foo 1.times do ^^^^^^^^^^ Useless call to `1.times` detected. end end RUBY expect_correction(<<~RUBY) def foo end RUBY end it 'registers an offense and corrects when there is a blank line in the method definition' do expect_offense(<<~RUBY) def foo 1.times do ^^^^^^^^^^ Useless call to `1.times` detected. bar baz end end RUBY expect_correction(<<~RUBY) def foo bar baz end RUBY end it 'does not register an offense for an integer > 1' do expect_no_offenses(<<~RUBY) 2.times { |i| puts i } RUBY end context 'short-form method' do it 'registers an offense and corrects with 0.times' do expect_offense(<<~RUBY) 0.times(&:something) ^^^^^^^^^^^^^^^^^^^^ Useless call to `0.times` detected. RUBY expect_correction('') end it 'registers an offense and corrects with negative times' do expect_offense(<<~RUBY) -1.times(&:something) ^^^^^^^^^^^^^^^^^^^^^ Useless call to `-1.times` detected. RUBY expect_correction('') end it 'registers an offense and corrects with 1.times' do expect_offense(<<~RUBY) 1.times(&:something) ^^^^^^^^^^^^^^^^^^^^ Useless call to `1.times` detected. RUBY expect_correction(<<~RUBY) something RUBY end it 'does not register an offense for an integer > 1' do expect_no_offenses(<<~RUBY) 2.times(&:something) RUBY end it 'does not adjust surrounding space' do expect_offense(<<~RUBY) precondition 0.times(&:something) ^^^^^^^^^^^^^^^^^^^^ Useless call to `0.times` detected. postcondition RUBY expect_correction(<<~RUBY) precondition postcondition RUBY end end context 'multiline block' do it 'correctly handles a multiline block with 1.times' do expect_offense(<<~RUBY) 1.times do |i| ^^^^^^^^^^^^^^ Useless call to `1.times` detected. do_something(i) do_something_else(i) end RUBY expect_correction(<<~RUBY) do_something(0) do_something_else(0) RUBY end it 'does not try to correct a block if the block arg is changed' do expect_offense(<<~RUBY) 1.times do |i| ^^^^^^^^^^^^^^ Useless call to `1.times` detected. do_something(i) i += 1 do_something_else(i) end RUBY expect_no_corrections end it 'does not try to correct a block if the block arg is changed in parallel assignment' do expect_offense(<<~RUBY) 1.times do |i| ^^^^^^^^^^^^^^ Useless call to `1.times` detected. do_something(i) i, j = i * 2, i * 3 do_something_else(i) end RUBY expect_no_corrections end it 'corrects a block that changes another lvar' do expect_offense(<<~RUBY) 1.times do |i| ^^^^^^^^^^^^^^ Useless call to `1.times` detected. do_something(i) j = 1 do_something_else(j) end RUBY expect_correction(<<~RUBY) do_something(0) j = 1 do_something_else(j) RUBY end end context 'within indentation' do it 'corrects properly when removing single line' do expect_offense(<<~RUBY) def my_method 0.times { do_something } ^^^^^^^^^^^^^^^^^^^^^^^^ Useless call to `0.times` detected. end RUBY expect_correction(<<~RUBY) def my_method end RUBY end it 'corrects properly when removing multiline' do expect_offense(<<~RUBY) def my_method 0.times do ^^^^^^^^^^ Useless call to `0.times` detected. do_something do_something_else end end RUBY expect_correction(<<~RUBY) def my_method end RUBY end it 'corrects properly when replacing' do expect_offense(<<~RUBY) def my_method 1.times do ^^^^^^^^^^ Useless call to `1.times` detected. do_something do_something_else end end RUBY expect_correction(<<~RUBY) def my_method do_something do_something_else end RUBY end context 'inline `Integer#times` calls' do it 'does not try to correct `0.times`' do expect_offense(<<~RUBY) foo(0.times { do_something }) ^^^^^^^^^^^^^^^^^^^^^^^^ Useless call to `0.times` detected. RUBY expect_no_corrections end it 'does not try to correct `1.times`' do expect_offense(<<~RUBY) foo(1.times { do_something }) ^^^^^^^^^^^^^^^^^^^^^^^^ Useless call to `1.times` detected. RUBY expect_no_corrections end it 'registers an offense for 1.times without block' do expect_offense(<<~RUBY) 1.times ^^^^^^^ Useless call to `1.times` detected. RUBY expect_no_corrections end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/useless_setter_call_spec.rb
spec/rubocop/cop/lint/useless_setter_call_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessSetterCall, :config do context 'with method ending with setter call on local object' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) def test top = Top.new top.attr = 5 ^^^ Useless setter call to local variable `top`. end RUBY expect_correction(<<~RUBY) def test top = Top.new top.attr = 5 top end RUBY end end context 'with singleton method ending with setter call on local object' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) def Top.test top = Top.new top.attr = 5 ^^^ Useless setter call to local variable `top`. end RUBY expect_correction(<<~RUBY) def Top.test top = Top.new top.attr = 5 top end RUBY end end context 'with method ending with square bracket setter on local object' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) def test top = Top.new top[:attr] = 5 ^^^ Useless setter call to local variable `top`. end RUBY expect_correction(<<~RUBY) def test top = Top.new top[:attr] = 5 top end RUBY end end context 'with method ending with ivar assignment' do it 'accepts' do expect_no_offenses(<<~RUBY) def test something @top = 5 end RUBY end end context 'with method ending with setter call on ivar' do it 'accepts' do expect_no_offenses(<<~RUBY) def test something @top.attr = 5 end RUBY end end context 'with method ending with setter call on argument' do it 'accepts' do expect_no_offenses(<<~RUBY) def test(some_arg) unrelated_local_variable = Top.new some_arg.attr = 5 end RUBY end end context 'when a lvar contains an object passed as argument at the end of the method' do it 'accepts the setter call on the lvar' do expect_no_offenses(<<~RUBY) def test(some_arg) @some_ivar = some_arg @some_ivar.do_something some_lvar = @some_ivar some_lvar.do_something some_lvar.attr = 5 end RUBY end end context 'when a lvar contains an object passed as argument ' \ 'by multiple-assignment at the end of the method' do it 'accepts the setter call on the lvar' do expect_no_offenses(<<~RUBY) def test(some_arg) _first, some_lvar, _third = 1, some_arg, 3 some_lvar.attr = 5 end RUBY end end context 'when a lvar does not contain any object passed as argument ' \ 'with multiple-assignment at the end of the method' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) def test(some_arg) _first, some_lvar, _third = do_something some_lvar.attr = 5 ^^^^^^^^^ Useless setter call to local variable `some_lvar`. end RUBY expect_correction(<<~RUBY) def test(some_arg) _first, some_lvar, _third = do_something some_lvar.attr = 5 some_lvar end RUBY end end context 'when a lvar possibly contains an object passed as argument ' \ 'by logical-operator-assignment at the end of the method' do it 'accepts the setter call on the lvar' do expect_no_offenses(<<~RUBY) def test(some_arg) some_lvar = nil some_lvar ||= some_arg some_lvar.attr = 5 end RUBY end end context 'when a lvar does not contain any object passed as argument ' \ 'by binary-operator-assignment at the end of the method' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) def test(some_arg) some_lvar = some_arg some_lvar += some_arg some_lvar.attr = 5 ^^^^^^^^^ Useless setter call to local variable `some_lvar`. end RUBY expect_correction(<<~RUBY) def test(some_arg) some_lvar = some_arg some_lvar += some_arg some_lvar.attr = 5 some_lvar end RUBY end end context 'when a lvar declared as an argument ' \ 'is no longer the passed object at the end of the method' do it 'registers an offense and corrects for the setter call on the lvar' do expect_offense(<<~RUBY) def test(some_arg) some_arg = Top.new some_arg.attr = 5 ^^^^^^^^ Useless setter call to local variable `some_arg`. end RUBY expect_correction(<<~RUBY) def test(some_arg) some_arg = Top.new some_arg.attr = 5 some_arg end RUBY end end context 'when a lvar contains a local object instantiated with literal' do it 'registers an offense and corrects for the setter call on the lvar' do expect_offense(<<~RUBY) def test some_arg = {} some_arg[:attr] = 1 ^^^^^^^^ Useless setter call to local variable `some_arg`. end RUBY expect_correction(<<~RUBY) def test some_arg = {} some_arg[:attr] = 1 some_arg end RUBY end end context 'when a lvar contains a non-local object returned by a method' do it 'accepts' do expect_no_offenses(<<~RUBY) def test some_lvar = Foo.shared_object some_lvar[:attr] = 1 end RUBY end end it 'is not confused by operators ending with =' do expect_no_offenses(<<~RUBY) def test top.attr == 5 end RUBY end it 'accepts exception assignments without exploding' do expect_no_offenses(<<~RUBY) def foo(bar) begin rescue StandardError => _ end bar[:baz] = true 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/lint/redundant_type_conversion_spec.rb
spec/rubocop/cop/lint/redundant_type_conversion_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantTypeConversion, :config do shared_examples 'accepted' do |source| it "does not register an offense on `#{source}`" do expect_no_offenses(source) end end shared_examples 'offense' do |conversion, receiver, suffix = ''| it "registers an offense and corrects on `#{receiver}.#{conversion}#{suffix}`" do expect_offense(<<~RUBY, receiver: receiver, conversion: conversion) #{receiver}.#{conversion}#{suffix} _{receiver} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction("#{receiver}#{suffix}\n") end it "registers an offense and corrects on `#{receiver}&.#{conversion}#{suffix}`" do expect_offense(<<~RUBY, receiver: receiver, conversion: conversion) #{receiver}&.#{conversion}#{suffix} _{receiver} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction("#{receiver}#{suffix}\n") end it "registers an offense and corrects on `#{receiver}.#{conversion}()`" do expect_offense(<<~RUBY, receiver: receiver, conversion: conversion) #{receiver}.#{conversion}() _{receiver} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction("#{receiver}\n") end it "registers an offense and corrects on `#{receiver}&.#{conversion}()`" do expect_offense(<<~RUBY, receiver: receiver, conversion: conversion) #{receiver}&.#{conversion}() _{receiver} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction("#{receiver}\n") end end shared_examples 'conversion' do |conversion| it_behaves_like 'accepted', conversion.to_s.freeze it_behaves_like 'accepted', "self.#{conversion}" it_behaves_like 'accepted', "foo.#{conversion}" it_behaves_like 'accepted', "foo.#{conversion}(2)" it_behaves_like 'accepted', "(foo).#{conversion}" it_behaves_like 'accepted', "(foo.#{conversion}).bar" it_behaves_like 'accepted', "(foo + 'bar').#{conversion}" it_behaves_like 'accepted', "'string'.#{conversion}" unless conversion == :to_s it_behaves_like 'accepted', ":sym.#{conversion}" unless conversion == :to_sym it_behaves_like 'accepted', "1.#{conversion}" unless conversion == :to_i it_behaves_like 'accepted', "1.0.#{conversion}" unless conversion == :to_f it_behaves_like 'accepted', "1r.#{conversion}" unless conversion == :to_r it_behaves_like 'accepted', "1i.#{conversion}" unless conversion == :to_c it_behaves_like 'accepted', "[].#{conversion}" unless conversion == :to_a it_behaves_like 'accepted', "{}.#{conversion}" unless conversion == :to_h it_behaves_like 'accepted', "Set.new.#{conversion}" unless conversion == :to_set it_behaves_like 'accepted', "'string'.#{conversion}(arg)" it_behaves_like 'accepted', ":sym.#{conversion}(arg)" it_behaves_like 'accepted', "1.#{conversion}(arg)" it_behaves_like 'accepted', "1.0.#{conversion}(arg)" it_behaves_like 'accepted', "1r.#{conversion}(arg)" it_behaves_like 'accepted', "1i.#{conversion}(arg)" it_behaves_like 'accepted', "[].#{conversion}(arg)" it_behaves_like 'accepted', "{}.#{conversion}(arg)" it_behaves_like 'accepted', "Set.new.#{conversion}(arg)" it "does not register an offense when calling `#{conversion}` on an local variable named `#{conversion}`" do expect_no_offenses(<<~RUBY) #{conversion} = foo #{conversion}.#{conversion} RUBY end context "when chaining `#{conversion}` calls" do it "registers an offense and corrects when calling `#{conversion}` on a `#{conversion}` call" do expect_offense(<<~RUBY, conversion: conversion) foo.#{conversion}.#{conversion} _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) foo.#{conversion} RUBY end it 'registers an offense and corrects when calling `to_s` on a `to_s` call with safe navigation' do expect_offense(<<~RUBY, conversion: conversion) foo&.#{conversion}&.#{conversion} _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) foo&.#{conversion} RUBY end it 'registers an offense and corrects when calling `to_s` on a `to_s` call with an argument' do expect_offense(<<~RUBY, conversion: conversion) foo.#{conversion}(2).#{conversion} _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) foo.#{conversion}(2) RUBY end it 'registers an offense and corrects when calling `to_s` on a `to_s` call with an argument and safe navigation' do expect_offense(<<~RUBY, conversion: conversion) foo&.#{conversion}(2)&.#{conversion} _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) foo&.#{conversion}(2) RUBY end it 'registers an offense and corrects when the redundant `to_s` is chained further' do expect_offense(<<~RUBY, conversion: conversion) foo.#{conversion}.#{conversion}.bar _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) foo.#{conversion}.bar RUBY end it 'registers an offense and corrects when the redundant `to_s` is chained further with safe navigation' do expect_offense(<<~RUBY, conversion: conversion) foo&.#{conversion}&.#{conversion}&.bar _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) foo&.#{conversion}&.bar RUBY end it 'registers an offense for a `to_s` call wrapped in parens' do expect_offense(<<~RUBY, conversion: conversion) (foo.#{conversion}).#{conversion} _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) (foo.#{conversion}) RUBY end it 'registers an offense for a `to_s` call wrapped in multiple parens' do expect_offense(<<~RUBY, conversion: conversion) ((foo.#{conversion})).#{conversion} _{conversion} ^{conversion} Redundant `#{conversion}` detected. RUBY expect_correction(<<~RUBY) ((foo.#{conversion})) RUBY end end end shared_examples 'chained typed method' do |conversion, method| it "registers an offense and corrects for `#{method}.#{conversion}" do expect_offense(<<~RUBY, method: method, conversion: conversion) %{method}.%{conversion} _{method} ^{conversion} Redundant `%{conversion}` detected. RUBY expect_correction(<<~RUBY) #{method} RUBY end it "registers an offense and corrects for `foo.#{method}.#{conversion}" do expect_offense(<<~RUBY, method: method, conversion: conversion) foo.%{method}.%{conversion} _{method} ^{conversion} Redundant `%{conversion}` detected. RUBY expect_correction(<<~RUBY) foo.#{method} RUBY end end it 'does not register an offense for chaining different conversion methods' do expect_no_offenses(<<~RUBY) foo.to_i.to_s RUBY end describe '`to_s`' do it_behaves_like 'conversion', :to_s it_behaves_like 'offense', :to_s, %('string') it_behaves_like 'offense', :to_s, %("string") it_behaves_like 'offense', :to_s, '%{string}' it_behaves_like 'offense', :to_s, '%q{string}' it_behaves_like 'offense', :to_s, '%Q{string}' it_behaves_like 'offense', :to_s, 'String.new("string")' it_behaves_like 'offense', :to_s, '::String.new("string")' it_behaves_like 'offense', :to_s, 'String("string")' it_behaves_like 'offense', :to_s, 'Kernel::String("string")' it_behaves_like 'offense', :to_s, '::Kernel::String("string")' it_behaves_like 'offense', :to_s, %{('string')} it_behaves_like 'offense', :to_s, %{(('string'))} it_behaves_like 'offense', :to_s, %('string'), '.bar' it_behaves_like 'chained typed method', :to_s, 'inspect' it_behaves_like 'chained typed method', :to_s, 'to_json' it 'registers an offense and corrects with a heredoc' do expect_offense(<<~RUBY) <<~STR.to_s ^^^^ Redundant `to_s` detected. string STR RUBY expect_correction(<<~RUBY) <<~STR string STR RUBY end end describe '`to_sym`' do it_behaves_like 'conversion', :to_sym it_behaves_like 'offense', :to_sym, ':sym' it_behaves_like 'offense', :to_sym, ':"#{sym}"' end describe '`to_i`' do it_behaves_like 'conversion', :to_i it_behaves_like 'offense', :to_i, '42' it_behaves_like 'offense', :to_i, 'Integer(42)' it_behaves_like 'offense', :to_i, 'Integer("42", 5)' it_behaves_like 'offense', :to_i, 'Kernel::Integer(42)' it_behaves_like 'offense', :to_i, '::Kernel::Integer(42)' it_behaves_like 'offense', :to_i, 'Integer("number", exception: true)' it_behaves_like 'accepted', 'Integer("number", exception: false).to_i' it_behaves_like 'accepted', 'Integer(obj, base, exception: false).to_i' it 'does not register an offense with `inspect.to_i`' do expect_no_offenses(<<~RUBY) inspect.to_i RUBY end end describe '`to_f`' do it_behaves_like 'conversion', :to_f it_behaves_like 'offense', :to_f, '42.0' it_behaves_like 'offense', :to_f, 'Float(42)' it_behaves_like 'offense', :to_f, 'Kernel::Float(42)' it_behaves_like 'offense', :to_f, '::Kernel::Float(42)' it_behaves_like 'offense', :to_f, 'Float("number", exception: true)' it_behaves_like 'accepted', 'Float("number", exception: false).to_f' end describe '`to_d`' do it_behaves_like 'conversion', :to_d it_behaves_like 'offense', :to_d, 'BigDecimal(42)' it_behaves_like 'offense', :to_d, 'Kernel::BigDecimal(42)' it_behaves_like 'offense', :to_d, '::Kernel::BigDecimal(42)' it_behaves_like 'offense', :to_d, 'BigDecimal("number", exception: true)' it_behaves_like 'accepted', 'BigDecimal("number", exception: false).to_d' it_behaves_like 'accepted', 'BigDecimal(obj, n, exception: false).to_d' end describe '`to_r`' do it_behaves_like 'conversion', :to_r it_behaves_like 'offense', :to_r, '5r' it_behaves_like 'offense', :to_r, 'Rational(42)' it_behaves_like 'offense', :to_r, 'Rational(3, 8)' it_behaves_like 'offense', :to_r, 'Kernel::Rational(42)' it_behaves_like 'offense', :to_r, '::Kernel::Rational(42)' it_behaves_like 'offense', :to_r, 'Rational("number", exception: true)' it_behaves_like 'accepted', 'Rational("number", exception: false).to_r' it_behaves_like 'accepted', 'Rational(x, y, exception: false).to_r' end describe '`to_c`' do it_behaves_like 'conversion', :to_c it_behaves_like 'offense', :to_c, '5i' it_behaves_like 'offense', :to_c, '5ri' it_behaves_like 'offense', :to_c, 'Complex(42)' it_behaves_like 'offense', :to_c, 'Complex(5, 3)' it_behaves_like 'offense', :to_c, 'Kernel::Complex(42)' it_behaves_like 'offense', :to_c, '::Kernel::Complex(42)' it_behaves_like 'offense', :to_c, 'Complex("number", exception: true)' it_behaves_like 'accepted', 'Complex("number", exception: false).to_c' it_behaves_like 'accepted', 'Complex(real, imag, exception: false).to_c' end describe '`to_a`' do it_behaves_like 'conversion', :to_a it_behaves_like 'offense', :to_a, '[1, 2, 3]' it_behaves_like 'offense', :to_a, 'Array.new([1, 2, 3])' it_behaves_like 'offense', :to_a, '::Array.new([1, 2, 3])' it_behaves_like 'offense', :to_a, 'Array([1, 2, 3])' it_behaves_like 'offense', :to_a, 'Kernel::Array([1, 2, 3])' it_behaves_like 'offense', :to_a, '::Kernel::Array([1, 2, 3])' it_behaves_like 'offense', :to_a, 'Array[1, 2, 3]' it_behaves_like 'offense', :to_a, '::Array[1, 2, 3]' end describe '`to_h`' do it_behaves_like 'conversion', :to_h it_behaves_like 'offense', :to_h, '{ foo: bar }' it_behaves_like 'offense', :to_h, 'Hash.new(default)' it_behaves_like 'offense', :to_h, '::Hash.new(default)' it_behaves_like 'offense', :to_h, 'Hash.new { |key, value| default }' it_behaves_like 'offense', :to_h, '::Hash.new { |key, value| default }' it_behaves_like 'offense', :to_h, 'Hash({ foo: bar })' it_behaves_like 'offense', :to_h, 'Kernel::Hash({ foo: bar })' it_behaves_like 'offense', :to_h, '::Kernel::Hash({ foo: bar })' it_behaves_like 'offense', :to_h, 'Hash[foo: bar]' it_behaves_like 'offense', :to_h, '::Hash[foo: bar]' it_behaves_like 'accepted', '{ key: value }.to_h { |key, value| [foo(key), bar(value)] }' it_behaves_like 'accepted', '{ key: value }.to_h { [foo(_1), bar(_2)] }' it_behaves_like 'accepted', '{ key: value }.to_h(&:baz)' end describe '`to_set`' do it_behaves_like 'conversion', :to_set it_behaves_like 'offense', :to_set, 'Set.new([1, 2, 3])' it_behaves_like 'offense', :to_set, '::Set.new([1, 2, 3])' it_behaves_like 'offense', :to_set, 'Set[1, 2, 3]' it_behaves_like 'offense', :to_set, '::Set[1, 2, 3]' it_behaves_like 'accepted', 'Set[1, 2, 3].to_set { |item| foo(item) }' it_behaves_like 'accepted', 'Set[1, 2, 3].to_set { foo(_1) }' it_behaves_like 'accepted', 'Set[1, 2, 3].to_set(&:foo)' end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/literal_in_interpolation_spec.rb
spec/rubocop/cop/lint/literal_in_interpolation_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::LiteralInInterpolation, :config do it 'accepts empty interpolation' do expect_no_offenses('"this is #{a} silly"') end it 'accepts interpolation of xstr' do expect_no_offenses('"this is #{`a`} silly"') end it 'accepts interpolation of irange where endpoints are not literals' do expect_no_offenses('"this is an irange: #{var1..var2}"') end it 'accepts interpolation of erange where endpoints are not literals' do expect_no_offenses('"this is an erange: #{var1...var2}"') end shared_examples 'literal interpolation' do |literal, expected = literal| it "registers an offense for #{literal} in interpolation " \ 'and removes interpolation around it' do expect_offense(<<~'RUBY', literal: literal) "this is the #{%{literal}}" ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) "this is the #{expected}" RUBY end it "removes interpolation around #{literal} when there is more text" do expect_offense(<<~'RUBY', literal: literal) "this is the #{%{literal}} literally" ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) "this is the #{expected} literally" RUBY end it "removes interpolation around multiple #{literal}" do expect_offense(<<~'RUBY', literal: literal) "some #{%{literal}} with #{%{literal}} too" ^{literal} Literal interpolation detected. _{literal} ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) "some #{expected} with #{expected} too" RUBY end context 'when there is non-literal and literal interpolation' do context 'when literal interpolation is before non-literal' do it 'only removes interpolation around literal' do expect_offense(<<~'RUBY', literal: literal) "this is #{%{literal}} with #{a} now" ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) "this is #{expected} with \#{a} now" RUBY end end context 'when literal interpolation is after non-literal' do it 'only removes interpolation around literal' do expect_offense(<<~'RUBY', literal: literal) "this is #{a} with #{%{literal}} now" ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) "this is \#{a} with #{expected} now" RUBY end end end it "registers an offense only for final #{literal} in interpolation" do expect_offense(<<~'RUBY', literal: literal) "this is the #{%{literal};%{literal}}" _{literal} ^{literal} Literal interpolation detected. RUBY end end describe 'type int' do it_behaves_like('literal interpolation', 1) it_behaves_like('literal interpolation', -1) it_behaves_like('literal interpolation', '1_123', '1123') it_behaves_like('literal interpolation', '123_456_789_123_456_789', '123456789123456789') it_behaves_like('literal interpolation', '0xaabb', '43707') it_behaves_like('literal interpolation', '0o377', '255') end describe 'type float' do it_behaves_like('literal interpolation', '1.2e-3', '0.0012') it_behaves_like('literal interpolation', 2.0) end describe 'type str' do it_behaves_like('literal interpolation', '"double_quot_string"', 'double_quot_string') it_behaves_like('literal interpolation', "'single_quot_string'", 'single_quot_string') it_behaves_like('literal interpolation', '"double_quot_string: \'"', "double_quot_string: '") it_behaves_like('literal interpolation', "'single_quot_string: \"'", 'single_quot_string: \"') end describe 'type sym' do it_behaves_like('literal interpolation', ':symbol', 'symbol') it_behaves_like('literal interpolation', ':"symbol"', 'symbol') it_behaves_like('literal interpolation', ':"single quot in symbol: \'"', "single quot in symbol: '") it_behaves_like('literal interpolation', ":'double quot in symbol: \"'", 'double quot in symbol: \"') end describe 'type array' do it_behaves_like('literal interpolation', '[]', '[]') it_behaves_like('literal interpolation', '["a", "b"]', '[\"a\", \"b\"]') it_behaves_like('literal interpolation', '%w[]', '[]') it_behaves_like('literal interpolation', '%w[v1]', '[\"v1\"]') it_behaves_like('literal interpolation', '%w[v1 v2]', '[\"v1\", \"v2\"]') it_behaves_like('literal interpolation', '%i[s1 s2]', '[\"s1\", \"s2\"]') it_behaves_like('literal interpolation', '%I[s1 s2]', '[\"s1\", \"s2\"]') it_behaves_like('literal interpolation', '%i[s1 s2]', '[\"s1\", \"s2\"]') it_behaves_like('literal interpolation', '%i[ s1 s2 ]', '[\"s1\", \"s2\"]') end describe 'type hash' do it_behaves_like('literal interpolation', '{"a" => "b"}', '{\"a\"=>\"b\"}') it_behaves_like('literal interpolation', "{ foo: 'bar', :fiz => \"buzz\" }", '{:foo=>\"bar\", :fiz=>\"buzz\"}') it_behaves_like('literal interpolation', "{ foo: { fiz: 'buzz' } }", '{:foo=>{:fiz=>\"buzz\"}}') it_behaves_like( 'literal interpolation', '{ num: { separate: 1_123, long_separate: 123_456_789_123_456_789, exponent: 1.2e-3 } }', '{:num=>{:separate=>1123, :long_separate=>123456789123456789, :exponent=>0.0012}}' ) it_behaves_like('literal interpolation', '{ n_adic_num: { hex: 0xaabb, oct: 0o377 } }', '{:n_adic_num=>{:hex=>43707, :oct=>255}}') it_behaves_like( 'literal interpolation', '{ double_quot: { simple: "double_quot", single_in_double: "double_quot: \'" } }', '{:double_quot=>{:simple=>\"double_quot\", :single_in_double=>\"double_quot: \'\"}}' ) it_behaves_like( 'literal interpolation', "{ single_quot: { simple: 'single_quot', double_in_single: 'single_quot: \"' } }", '{:single_quot=>{:simple=>\"single_quot\", :double_in_single=>\"single_quot: \\\\\\"\"}}' ) it_behaves_like('literal interpolation', '{ bool: { key: true } }', '{:bool=>{:key=>true}}') it_behaves_like('literal interpolation', '{ bool: { key: false } }', '{:bool=>{:key=>false}}') it_behaves_like('literal interpolation', '{ nil: { key: nil } }', '{:nil=>{:key=>nil}}') it_behaves_like('literal interpolation', '{ symbol: { key: :symbol } }', '{:symbol=>{:key=>:symbol}}') it_behaves_like('literal interpolation', '{ symbol: { key: :"symbol" } }', '{:symbol=>{:key=>:symbol}}') it_behaves_like('literal interpolation', '{ single_quot_symbol: { key: :"single_quot_in_symbol: \'" } }', '{:single_quot_symbol=>{:key=>:\"single_quot_in_symbol: \'\"}}') it_behaves_like('literal interpolation', "{ double_quot_symbol: { key: :'double_quot_in_symbol: \"' } }", '{:double_quot_symbol=>{:key=>:\"double_quot_in_symbol: \\\\\"\"}}') it_behaves_like('literal interpolation', '{ single_quot_symbol_not_in_space: { key: :"single_quot_in_symbol:\'" } }', '{:single_quot_symbol_not_in_space=>{:key=>:\"single_quot_in_symbol:\'\"}}') it_behaves_like('literal interpolation', '{ single_quot_symbol_in_space: { key: :"single_quot_in_symbol: " } }', '{:single_quot_symbol_in_space=>{:key=>:\"single_quot_in_symbol: \"}}') it_behaves_like('literal interpolation', '{ range: { key: 1..2 } }', '{:range=>{:key=>1..2}}') it_behaves_like('literal interpolation', '{ range: { key: 1...2 } }', '{:range=>{:key=>1...2}}') it_behaves_like('literal interpolation', '{ array: { key: %w[] } }', '{:array=>{:key=>[]}}') it_behaves_like('literal interpolation', '{ array: { key: %w[v1] } }', '{:array=>{:key=>[\"v1\"]}}') it_behaves_like('literal interpolation', '{ array: { key: %w[v1 v2] } }', '{:array=>{:key=>[\"v1\", \"v2\"]}}') it_behaves_like('literal interpolation', '{ array: { key: %i[s1 s2] } }', '{:array=>{:key=>[\"s1\", \"s2\"]}}') it_behaves_like('literal interpolation', '{ array: { key: %I[s1 s2] } }', '{:array=>{:key=>[\"s1\", \"s2\"]}}') it_behaves_like('literal interpolation', '{ array: { key: %i[s1 s2] } }', '{:array=>{:key=>[\"s1\", \"s2\"]}}') it_behaves_like('literal interpolation', '{ array: { key: %i[ s1 s2 ] } }', '{:array=>{:key=>[\"s1\", \"s2\"]}}') end describe 'type else' do it_behaves_like('literal interpolation', 'nil', '') it_behaves_like('literal interpolation', 1..2) it_behaves_like('literal interpolation', 1...2) it_behaves_like('literal interpolation', true) it_behaves_like('literal interpolation', false) end shared_examples 'literal interpolation in words literal' do |prefix| let(:word) { 'interpolation' } it "accepts interpolation of a string literal with space in #{prefix}[]" do expect_no_offenses(<<~RUBY) #{prefix}[\#{"this interpolation"} is significant] RUBY end it "accepts interpolation of an empty string literal in #{prefix}[]" do expect_no_offenses(<<~RUBY) #{prefix}[\#{""} is significant] RUBY end it "accepts interpolation of a symbol literal with space in #{prefix}[]" do expect_no_offenses(<<~RUBY) #{prefix}[\#{:"this interpolation"} is significant] RUBY end it "accepts interpolation of an array literal containing a string with space in #{prefix}[]" do expect_no_offenses(<<~RUBY) #{prefix}[\#{["this interpolation"]} is significant] RUBY end it "accepts interpolation of an array literal containing a symbol with space in #{prefix}[]" do expect_no_offenses(<<~RUBY) #{prefix}[\#{[:"this interpolation"]} is significant] RUBY end it "removes interpolation of a string literal without space in #{prefix}[]" do expect_offense(<<~'RUBY', prefix: prefix, literal: word.inspect) %{prefix}[this #{%{literal}} is not significant] _{prefix} ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) #{prefix}[this #{word} is not significant] RUBY end it "removes interpolation of a symbol literal without space in #{prefix}[]" do expect_offense(<<~'RUBY', prefix: prefix, literal: word.to_sym.inspect) %{prefix}[this #{%{literal}} is not significant] _{prefix} ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) #{prefix}[this #{word} is not significant] RUBY end it "removes interpolation of an array containing a string literal without space in #{prefix}[]" do expect_offense(<<~'RUBY', prefix: prefix, literal: [word].inspect) %{prefix}[this #{%{literal}} is not significant] _{prefix} ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) #{prefix}[this #{[word].inspect.gsub('"', '\"')} is not significant] RUBY end it "removes interpolation of an array containing a symbol literal without space in #{prefix}[]" do expect_offense(<<~'RUBY', prefix: prefix, literal: [word.to_sym].inspect) %{prefix}[this #{%{literal}} is not significant] _{prefix} ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) #{prefix}[this #{[word.to_sym].inspect} is not significant] RUBY end end it_behaves_like('literal interpolation in words literal', '%W') it_behaves_like('literal interpolation in words literal', '%I') it 'handles nested interpolations when autocorrecting' do expect_offense(<<~'RUBY') "this is #{"#{1}"} silly" ^ Literal interpolation detected. RUBY # next iteration fixes this expect_correction(<<~'RUBY', loop: false) "this is #{"1"} silly" RUBY end shared_examples 'special keywords' do |keyword| it "accepts strings like #{keyword}" do expect_no_offenses(<<~RUBY) %("this is \#{#{keyword}} silly") RUBY end it "registers an offense and autocorrects interpolation after #{keyword}" do expect_offense(<<~'RUBY', keyword: keyword) "this is the #{%{keyword}} #{1}" _{keyword} ^ Literal interpolation detected. RUBY expect_correction(<<~RUBY) "this is the \#{#{keyword}} 1" RUBY end end it_behaves_like('special keywords', '__FILE__') it_behaves_like('special keywords', '__LINE__') it_behaves_like('special keywords', '__END__') it_behaves_like('special keywords', '__ENCODING__') shared_examples 'non-special string literal interpolation' do |string| it "registers an offense for #{string} and removes the interpolation " \ "and quotes around #{string}" do expect_offense(<<~'RUBY', string: string) "this is the #{%{string}}" ^{string} Literal interpolation detected. RUBY expect_correction(<<~RUBY) "this is the #{string.gsub(/'|"/, '')}" RUBY end end it_behaves_like('non-special string literal interpolation', %('foo')) it_behaves_like('non-special string literal interpolation', %("foo")) it 'handles double quotes in single quotes when autocorrecting' do expect_offense(<<~'RUBY') "this is #{'"'} silly" ^^^ Literal interpolation detected. RUBY expect_correction(<<~'RUBY') "this is \" silly" RUBY end it 'handles backslash in single quotes when autocorrecting' do expect_offense(<<~'RUBY') x = "ABC".gsub(/(A)(B)(C)/, "D#{'\2'}F") ^^^^ Literal interpolation detected. "this is #{'\n'} silly" ^^^^ Literal interpolation detected. "this is #{%q(\n)} silly" ^^^^^^ Literal interpolation detected. RUBY expect_correction(<<~'RUBY') x = "ABC".gsub(/(A)(B)(C)/, "D\\2F") "this is \\n silly" "this is \\n silly" RUBY end it 'handles backslash in double quotes when autocorrecting' do expect_offense(<<~'RUBY') "this is #{"\n"} silly" ^^^^ Literal interpolation detected. "this is #{%(\n)} silly" ^^^^^ Literal interpolation detected. "this is #{%Q(\n)} silly" ^^^^^^ Literal interpolation detected. RUBY expect_correction(<<~RUBY) "this is#{trailing_whitespace} silly" "this is#{trailing_whitespace} silly" "this is#{trailing_whitespace} silly" RUBY end it 'does not register an offense when space literal at the end of heredoc line' do expect_no_offenses(<<~RUBY) <<~HERE Line with explicit space literal at the end. \#{' '} HERE RUBY end context 'in string-like contexts' do let(:literal) { '42' } let(:expected) { '42' } it 'removes interpolation in symbols' do expect_offense(<<~'RUBY', literal: literal) :"this is the #{%{literal}}" ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) :"this is the #{expected}" RUBY end it 'removes interpolation in backticks' do expect_offense(<<~'RUBY', literal: literal) `this is the #{%{literal}}` ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) `this is the #{expected}` RUBY end it 'removes interpolation in regular expressions' do expect_offense(<<~'RUBY', literal: literal) /this is the #{%{literal}}/ ^{literal} Literal interpolation detected. RUBY expect_correction(<<~RUBY) /this is the #{expected}/ RUBY end end context 'handling regexp special characters' do context 'when inside a `regexp` literal' do it 'properly escapes a forward slash' do expect_offense(<<~'RUBY') /test#{'/'}test/ ^^^ Literal interpolation detected. RUBY expect_correction(<<~'RUBY') /test\/test/ RUBY end it 'properly escapes multiple forward slashes' do expect_offense(<<~'RUBY') /test#{'/a/b/c/'}test/ ^^^^^^^^^ Literal interpolation detected. RUBY expect_correction(<<~'RUBY') /test\/a\/b\/c\/test/ RUBY end it 'handles escaped forward slashes' do expect_offense(<<~'RUBY') /test#{'\\/'}test/ ^^^^^ Literal interpolation detected. RUBY expect_correction(<<~'RUBY') /test\/test/ RUBY end it 'handles escaped backslashes' do expect_offense(<<~'RUBY') /test#{'\\\\/'}test/ ^^^^^^^ Literal interpolation detected. RUBY expect_correction(<<~'RUBY') /test\\\/test/ RUBY end end context 'when inside a %r{} `regexp`' do it 'does not escape the autocorrection' do expect_offense(<<~'RUBY') %r{test#{'/'}test} ^^^ Literal interpolation detected. RUBY expect_correction(<<~RUBY) %r{test/test} RUBY end end context 'when inside a non-`regexp` node' do it 'does not escape the autocorrection' do expect_offense(<<~'RUBY') "test#{'/'}test" ^^^ Literal interpolation detected. RUBY expect_correction(<<~RUBY) "test/test" RUBY end end context 'with invalid string literal' do it 'registers an offense' do expect_offense(<<~'RUBY') "#{"\201\203"}" ^^^^^^^^^^ Literal interpolation detected. RUBY expect_correction(<<~'RUBY') "\201\203" RUBY end end end it 'does not register an offense for an array inside a regexp' do expect_no_offenses(<<~'RUBY') /#{%w[a b c]}/ RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/useless_ruby2_keywords_spec.rb
spec/rubocop/cop/lint/useless_ruby2_keywords_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessRuby2Keywords, :config do context 'when `ruby2_keywords` is given a `def` node' do it 'registers an offense for a method without arguments' do expect_offense(<<~RUBY) ruby2_keywords def foo ^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. end RUBY end it 'registers an offense for a method with only positional args' do expect_offense(<<~RUBY) ruby2_keywords def foo(arg) ^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. end RUBY end it 'registers an offense for a method with only `kwrestarg`' do expect_offense(<<~RUBY) ruby2_keywords def foo(**kwargs) ^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. end RUBY end it 'registers an offense for a method with only keyword args' do expect_offense(<<~RUBY) ruby2_keywords def foo(i:, j:) ^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. end RUBY end it 'registers an offense for a method with a `restarg` and keyword args' do expect_offense(<<~RUBY) ruby2_keywords def foo(*args, i:, j:) ^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. end RUBY end it 'registers an offense for a method with a `restarg` and `kwoptarg`' do expect_offense(<<~RUBY) ruby2_keywords def foo(*args, i: 1) ^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. end RUBY end it 'registers an offense for a method with a `restarg` and `kwrestarg`' do expect_offense(<<~RUBY) ruby2_keywords def foo(*args, **kwargs) ^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. end RUBY end it 'does not register an offense for a method with a `restarg` and no `kwrestarg`' do expect_no_offenses(<<~RUBY) ruby2_keywords def foo(*args) end RUBY end it 'does not register an offense for a method with a `restarg` other positional args' do expect_no_offenses(<<~RUBY) ruby2_keywords def foo(arg1, arg2, *rest) end RUBY end it 'does not register an offense for a method with a `restarg` other optional args' do expect_no_offenses(<<~RUBY) ruby2_keywords def foo(arg1 = 5, *rest) end RUBY end it 'does not register an offense for a method with a `restarg` and `blockarg`' do expect_no_offenses(<<~RUBY) ruby2_keywords def foo(*rest, &block) end RUBY end end context 'when `ruby2_keywords` is given a symbol' do it 'registers an offense for an unnecessary `ruby2_keywords`' do expect_offense(<<~RUBY) def foo(**kwargs) end ruby2_keywords :foo ^^^^^^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. RUBY end it 'registers an offense for an unnecessary `ruby2_keywords` in a condition' do expect_offense(<<~RUBY) def foo(**kwargs) end ruby2_keywords :foo if respond_to?(:ruby2_keywords, true) ^^^^^^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. RUBY end it 'does not register an offense for an allowed def' do expect_no_offenses(<<~RUBY) def foo(*args) end ruby2_keywords :foo RUBY end it 'does not register an offense when there is no `def`' do expect_no_offenses(<<~RUBY) ruby2_keywords :foo RUBY end it 'does not register an offense when the `def` is at a different depth' do expect_no_offenses(<<~RUBY) class C class D def foo(**kwargs) end end ruby2_keywords :foo end RUBY end end context 'with a dynamically defined method' do it 'registers an offense for an unnecessary `ruby2_keywords`' do expect_offense(<<~RUBY) define_method(:foo) { |**kwargs| } ruby2_keywords :foo ^^^^^^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. RUBY end it 'does not register an offense for an allowed `ruby2_keywords`' do expect_no_offenses(<<~RUBY) define_method(:foo) { |*args| } ruby2_keywords :foo RUBY end it 'registers an offense when the method has a `shadowarg`' do expect_offense(<<~RUBY) define_method(:foo) { |x; y| } ruby2_keywords :foo ^^^^^^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. RUBY end it 'does not register an offense when the method has a `restarg` and a `shadowarg`' do expect_no_offenses(<<~RUBY) define_method(:foo) { |*args; y| } ruby2_keywords :foo RUBY end it 'registers an offense for a numblock', :ruby27 do expect_offense(<<~RUBY) define_method(:foo) { _1 } ruby2_keywords :foo ^^^^^^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. RUBY end it 'registers an offense for an itblock', :ruby34 do expect_offense(<<~RUBY) define_method(:foo) { it } ruby2_keywords :foo ^^^^^^^^^^^^^^^^^^^ `ruby2_keywords` is unnecessary for method `foo`. RUBY end it 'does not register an offense for `Proc#ruby2_keywords`' do expect_no_offenses(<<~RUBY) block = proc { |_, *args| klass.new(*args) } block.ruby2_keywords if block.respond_to?(:ruby2_keywords) 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/lint/deprecated_class_methods_spec.rb
spec/rubocop/cop/lint/deprecated_class_methods_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DeprecatedClassMethods, :config do context 'prefer `File.exist?` over `File.exists?`' do it 'registers an offense and corrects File.exists?' do expect_offense(<<~RUBY) File.exists?(o) ^^^^^^^^^^^^ `File.exists?` is deprecated in favor of `File.exist?`. RUBY expect_correction(<<~RUBY) File.exist?(o) RUBY end it 'registers an offense and corrects ::File.exists?' do expect_offense(<<~RUBY) ::File.exists?(o) ^^^^^^^^^^^^^^ `::File.exists?` is deprecated in favor of `::File.exist?`. RUBY expect_correction(<<~RUBY) ::File.exist?(o) RUBY end it 'does not register an offense for File.exist?' do expect_no_offenses('File.exist?(o)') end end context 'prefer `Dir.exist?` over `Dir.exists?`' do it 'registers an offense and corrects Dir.exists?' do expect_offense(<<~RUBY) Dir.exists?(o) ^^^^^^^^^^^ `Dir.exists?` is deprecated in favor of `Dir.exist?`. RUBY expect_correction(<<~RUBY) Dir.exist?(o) RUBY end it 'registers an offense and corrects ::Dir.exists?' do expect_offense(<<~RUBY) ::Dir.exists?(o) ^^^^^^^^^^^^^ `::Dir.exists?` is deprecated in favor of `::Dir.exist?`. RUBY expect_correction(<<~RUBY) ::Dir.exist?(o) RUBY end it 'does not register an offense for Dir.exist?' do expect_no_offenses('Dir.exist?(o)') end it 'does not register an offense for offensive method `exists?`on other receivers' do expect_no_offenses('Foo.exists?(o)') end end context 'prefer `block_given?` over `iterator?`' do it 'registers an offense and corrects iterator?' do expect_offense(<<~RUBY) iterator? ^^^^^^^^^ `iterator?` is deprecated in favor of `block_given?`. RUBY expect_correction(<<~RUBY) block_given? RUBY end it 'does not register an offense for block_given?' do expect_no_offenses('block_given?') end it 'does not register an offense for offensive method `iterator?`on other receivers' do expect_no_offenses('Foo.iterator?') end end context 'prefer `attr_accessor :name` over `attr :name, true`' do it 'registers an offense and corrects `attr :name` with boolean argument' do expect_offense(<<~RUBY) attr :name, true ^^^^^^^^^^^^^^^^ `attr :name, true` is deprecated in favor of `attr_accessor :name`. RUBY expect_correction(<<~RUBY) attr_accessor :name RUBY end it "registers an offense and corrects `attr 'name'` with boolean argument" do expect_offense(<<~RUBY) attr 'name', true ^^^^^^^^^^^^^^^^^ `attr 'name', true` is deprecated in favor of `attr_accessor 'name'`. RUBY expect_correction(<<~RUBY) attr_accessor 'name' RUBY end it 'does not register an offense for `attr` without boolean argument' do expect_no_offenses('attr :name') end it 'does not register an offense for `attr` with variable argument' do expect_no_offenses('attr :name, attribute') end it 'does not register an offense for `attr_accessor`' do expect_no_offenses('attr_accessor :name') end end context 'prefer `attr_reader :name` over `attr :name, false`' do it 'registers an offense and corrects `attr :name` with boolean argument' do expect_offense(<<~RUBY) attr :name, false ^^^^^^^^^^^^^^^^^ `attr :name, false` is deprecated in favor of `attr_reader :name`. RUBY expect_correction(<<~RUBY) attr_reader :name RUBY end it "registers an offense and corrects `attr 'name'` with boolean argument" do expect_offense(<<~RUBY) attr 'name', false ^^^^^^^^^^^^^^^^^^ `attr 'name', false` is deprecated in favor of `attr_reader 'name'`. RUBY expect_correction(<<~RUBY) attr_reader 'name' RUBY end it 'does not register an offense for `attr_reader` without boolean argument' do expect_no_offenses('attr_reader :name') end end context 'when using `ENV.freeze`' do it 'registers an offense' do expect_offense(<<~RUBY) ENV.freeze ^^^^^^^^^^ `ENV.freeze` is deprecated in favor of `ENV`. RUBY expect_correction(<<~RUBY) ENV RUBY end it 'does not register an offense for method calls to `ENV` other than `freeze`' do expect_no_offenses('ENV.values') end end context 'when using `ENV.clone`' do it 'registers an offense' do expect_offense(<<~RUBY) ENV.clone ^^^^^^^^^ `ENV.clone` is deprecated in favor of `ENV.to_h`. RUBY expect_correction(<<~RUBY) ENV.to_h RUBY end it 'does not register an offense for method calls to `ENV` other than `clone`' do expect_no_offenses('ENV.values') end end context 'when using `ENV.dup`' do it 'registers an offense' do expect_offense(<<~RUBY) ENV.dup ^^^^^^^ `ENV.dup` is deprecated in favor of `ENV.to_h`. RUBY expect_correction(<<~RUBY) ENV.to_h RUBY end it 'does not register an offense for method calls to `ENV` other than `dup`' do expect_no_offenses('ENV.values') end end context 'prefer `Addrinfo#getnameinfo` over `Socket.gethostbyaddr`' do it 'registers an offense for Socket.gethostbyaddr' do expect_offense(<<~RUBY) Socket.gethostbyaddr([221,186,184,68].pack("CCCC")) ^^^^^^^^^^^^^^^^^^^^ `Socket.gethostbyaddr` is deprecated in favor of `Addrinfo#getnameinfo`. RUBY expect_no_corrections end it 'registers an offense for ::Socket.gethostbyaddr' do expect_offense(<<~RUBY) ::Socket.gethostbyaddr([221,186,184,68].pack("CCCC")) ^^^^^^^^^^^^^^^^^^^^^^ `::Socket.gethostbyaddr` is deprecated in favor of `Addrinfo#getnameinfo`. RUBY expect_no_corrections end it 'registers an offense for Socket.gethostbyaddr with address type argument' do expect_offense(<<~RUBY) Socket.gethostbyaddr([221,186,184,68].pack("CCCC"), Socket::AF_INET) ^^^^^^^^^^^^^^^^^^^^ `Socket.gethostbyaddr` is deprecated in favor of `Addrinfo#getnameinfo`. RUBY expect_no_corrections end it 'does not register an offense for method `gethostbyaddr` on other receivers' do expect_no_offenses('Foo.gethostbyaddr') end end context 'prefer `Addrinfo.getaddrinfo` over `Socket.gethostbyname`' do it 'registers an offense for Socket.gethostbyname' do expect_offense(<<~RUBY) Socket.gethostbyname("hal") ^^^^^^^^^^^^^^^^^^^^ `Socket.gethostbyname` is deprecated in favor of `Addrinfo.getaddrinfo`. RUBY expect_no_corrections end it 'registers an offense for ::Socket.gethostbyname' do expect_offense(<<~RUBY) ::Socket.gethostbyname("hal") ^^^^^^^^^^^^^^^^^^^^^^ `::Socket.gethostbyname` is deprecated in favor of `Addrinfo.getaddrinfo`. RUBY expect_no_corrections end it 'does not register an offense for method `gethostbyname` on other receivers' do expect_no_offenses('Foo.gethostbyname') 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/lint/unused_method_argument_spec.rb
spec/rubocop/cop/lint/unused_method_argument_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnusedMethodArgument, :config do let(:cop_config) do { 'AllowUnusedKeywordArguments' => false, 'IgnoreEmptyMethods' => false, 'IgnoreNotImplementedMethods' => false } end describe 'inspection' do context 'when a method takes multiple arguments' do context 'and an argument is unused' do it 'registers an offense and adds underscore-prefix' do message = 'Unused method argument - `foo`. ' \ "If it's necessary, use `_` or `_foo` " \ "as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it." expect_offense(<<~RUBY) def some_method(foo, bar) ^^^ #{message} puts bar end RUBY expect_correction(<<~RUBY) def some_method(_foo, bar) puts bar end RUBY end context 'and there is some whitespace around the unused argument' do it 'registers an offense and preserves whitespace' do message = 'Unused method argument - `bar`. ' \ "If it's necessary, use `_` or `_bar` " \ "as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it." expect_offense(<<~RUBY) def some_method(foo, bar) ^^^ #{message} puts foo end RUBY expect_correction(<<~RUBY) def some_method(foo, _bar) puts foo end RUBY end end context 'and arguments are swap-assigned' do it 'accepts' do expect_no_offenses(<<~RUBY) def foo(a, b) a, b = b, a end RUBY end end context "and one argument is assigned to another, whilst other's value is not used" do it 'registers an offense' do message = "Unused method argument - `a`. If it's necessary, use " \ '`_` or `_a` as an argument name to indicate that ' \ "it won't be used. If it's unnecessary, remove it." expect_offense(<<~RUBY) def foo(a, b) ^ #{message} a, b = b, 42 end RUBY expect_correction(<<~RUBY) def foo(_a, b) a, b = b, 42 end RUBY end end end context 'and all the arguments are unused' do it 'registers offenses and suggests the use of `*` and ' \ 'autocorrects to add underscore-prefix to all arguments' do (foo_message, bar_message) = %w[foo bar].map do |arg| "Unused method argument - `#{arg}`. " \ "If it's necessary, use `_` or `_#{arg}` " \ "as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it. " \ 'You can also write as `some_method(*)` if you want the method ' \ "to accept any arguments but don't care about them." end expect_offense(<<~RUBY) def some_method(foo, bar) ^^^ #{bar_message} ^^^ #{foo_message} end RUBY expect_correction(<<~RUBY) def some_method(_foo, _bar) end RUBY end end end context 'when a splat argument is unused' do it 'registers an offense and preserves the splat' do message = 'Unused method argument - `bar`. ' \ "If it's necessary, use `_` or `_bar` " \ "as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it." expect_offense(<<~RUBY) def some_method(foo, *bar) ^^^ #{message} puts foo end RUBY expect_correction(<<~RUBY) def some_method(foo, *_bar) puts foo end RUBY end end context 'when an argument with a default value is unused' do it 'registers an offense and preserves the default value' do message = 'Unused method argument - `bar`. ' \ "If it's necessary, use `_` or `_bar` " \ "as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it." expect_offense(<<~RUBY) def some_method(foo, bar = 1) ^^^ #{message} puts foo end RUBY expect_correction(<<~RUBY) def some_method(foo, _bar = 1) puts foo end RUBY end end context 'when a required keyword argument is unused', ruby: 2.1 do context 'when a required keyword argument is unused' do it 'registers an offense but does not suggest underscore-prefix' do expect_offense(<<~RUBY) def self.some_method(foo, bar:) ^^^ Unused method argument - `bar`. puts foo end RUBY expect_no_corrections end end end context 'when an optional keyword argument is unused' do it 'registers an offense but does not suggest underscore-prefix' do expect_offense(<<~RUBY) def self.some_method(foo, bar: 1) ^^^ Unused method argument - `bar`. puts foo end RUBY expect_no_corrections end context 'and AllowUnusedKeywordArguments set' do let(:cop_config) { { 'AllowUnusedKeywordArguments' => true } } it 'does not care' do expect_no_offenses(<<~RUBY) def self.some_method(foo, bar: 1) puts foo end RUBY end end end context 'when a trailing block argument is unused' do it 'registers an offense and removes the unused block arg' do message = 'Unused method argument - `block`. ' \ "If it's necessary, use `_` or `_block` " \ "as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it." expect_offense(<<~RUBY) def some_method(foo, bar, &block) ^^^^^ #{message} foo + bar end RUBY expect_correction(<<~RUBY) def some_method(foo, bar) foo + bar end RUBY end end context 'when a singleton method argument is unused' do it 'registers an offense' do message = "Unused method argument - `foo`. If it's necessary, use " \ '`_` or `_foo` as an argument name to indicate that it ' \ "won't be used. If it's unnecessary, remove it. " \ 'You can also write as `some_method(*)` if you want the ' \ "method to accept any arguments but don't care about them." expect_offense(<<~RUBY) def self.some_method(foo) ^^^ #{message} end RUBY expect_correction(<<~RUBY) def self.some_method(_foo) end RUBY end end context 'when an underscore-prefixed method argument is unused' do let(:source) { <<~RUBY } def some_method(_foo) end RUBY it 'accepts' do expect_no_offenses(source) end end context 'when a method argument is used' do let(:source) { <<~RUBY } def some_method(foo) puts foo end RUBY it 'accepts' do expect_no_offenses(source) end end context 'when a variable is unused' do let(:source) { <<~RUBY } def some_method foo = 1 end RUBY it 'does not care' do expect_no_offenses(source) end end context 'when a block argument is unused' do let(:source) { <<~RUBY } 1.times do |foo| end RUBY it 'does not care' do expect_no_offenses(source) end end context 'in a method calling `super` without arguments' do context 'when a method argument is not used explicitly' do it 'accepts since the arguments are guaranteed to be the same as ' \ "superclass' ones and the user has no control on them" do expect_no_offenses(<<~RUBY) def some_method(foo) super end RUBY end end end context 'in a method calling `super` with arguments' do context 'when a method argument is unused' do it 'registers an offense' do message = "Unused method argument - `foo`. If it's necessary, use " \ '`_` or `_foo` as an argument name to indicate that ' \ "it won't be used. If it's unnecessary, remove it. " \ 'You can also write as `some_method(*)` if you want ' \ "the method to accept any arguments but don't care about " \ 'them.' expect_offense(<<~RUBY) def some_method(foo) ^^^ #{message} super(:something) end RUBY expect_correction(<<~RUBY) def some_method(_foo) super(:something) end RUBY end end end context 'in a method calling `binding` without arguments' do let(:source) { <<~RUBY } def some_method(foo, bar) do_something binding end RUBY it 'accepts all arguments' do expect_no_offenses(source) end context 'inside another method definition' do (foo_message, bar_message) = %w[foo bar].map do |arg| "Unused method argument - `#{arg}`. If it's necessary, use `_` or " \ "`_#{arg}` as an argument name to indicate that it won't be " \ "used. If it's unnecessary, remove it. You can also write as " \ '`some_method(*)` if you want the method to accept any arguments ' \ "but don't care about them." end it 'registers offenses' do expect_offense(<<~RUBY) def some_method(foo, bar) ^^^ #{bar_message} ^^^ #{foo_message} def other(a) puts something(binding) end end RUBY expect_correction(<<~RUBY) def some_method(_foo, _bar) def other(a) puts something(binding) end end RUBY end end end context 'in a method calling `binding` with arguments' do context 'when a method argument is unused' do it 'registers an offense' do message = "Unused method argument - `foo`. If it's necessary, use " \ '`_` or `_foo` as an argument name to indicate that it ' \ "won't be used. If it's unnecessary, remove it. You can " \ 'also write as `some_method(*)` if you want the method ' \ "to accept any arguments but don't care about them." expect_offense(<<~RUBY) def some_method(foo) ^^^ #{message} binding(:something) end RUBY expect_correction(<<~RUBY) def some_method(_foo) binding(:something) end RUBY end end end end context 'when IgnoreEmptyMethods config parameter is set' do let(:cop_config) { { 'IgnoreEmptyMethods' => true } } it 'accepts an empty method with a single unused parameter' do expect_no_offenses(<<~RUBY) def method(arg) end RUBY end it 'accepts an empty singleton method with a single unused parameter' do expect_no_offenses(<<~RUBY) def self.method(unused) end RUBY end it 'registers an offense for a non-empty method with a single unused parameter' do message = "Unused method argument - `arg`. If it's necessary, use " \ '`_` or `_arg` as an argument name to indicate that it ' \ "won't be used. If it's unnecessary, remove it. You can also write " \ 'as `method(*)` if you want the method to accept any arguments ' \ "but don't care about them." expect_offense(<<~RUBY) def method(arg) ^^^ #{message} 1 end RUBY expect_correction(<<~RUBY) def method(_arg) 1 end RUBY end it 'accepts an empty method with multiple unused parameters' do expect_no_offenses(<<~RUBY) def method(a, b, *others) end RUBY end it 'registers an offense for a non-empty method with multiple unused parameters' do (a_message, b_message, others_message) = %w[a b others].map do |arg| "Unused method argument - `#{arg}`. If it's necessary, use `_` or " \ "`_#{arg}` as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it. " \ 'You can also write as `method(*)` if you want the method ' \ "to accept any arguments but don't care about them." end expect_offense(<<~RUBY) def method(a, b, *others) ^^^^^^ #{others_message} ^ #{b_message} ^ #{a_message} 1 end RUBY expect_correction(<<~RUBY) def method(_a, _b, *_others) 1 end RUBY end end context 'when IgnoreNotImplementedMethods config parameter is set' do let(:cop_config) { { 'IgnoreNotImplementedMethods' => true } } it 'accepts a method with a single unused parameter & raises NotImplementedError' do expect_no_offenses(<<~RUBY) def method(arg) raise NotImplementedError end RUBY end it 'accepts a method with a single unused parameter & raises NotImplementedError, message' do expect_no_offenses(<<~RUBY) def method(arg) raise NotImplementedError, message end RUBY end it 'accepts a method with a single unused parameter & raises ::NotImplementedError' do expect_no_offenses(<<~RUBY) def method(arg) raise ::NotImplementedError end RUBY end it 'accepts a method with a single unused parameter & fails with message' do expect_no_offenses(<<~RUBY) def method(arg) fail "TODO" end RUBY end it 'accepts a method with a single unused parameter & fails without message' do expect_no_offenses(<<~RUBY) def method(arg) fail end RUBY end it 'accepts an empty singleton method with a single unused parameter &' \ 'raise NotImplementedError' do expect_no_offenses(<<~RUBY) def self.method(unused) raise NotImplementedError end RUBY end it 'registers an offense for a non-empty method with a single unused parameter' do message = "Unused method argument - `arg`. If it's necessary, use " \ '`_` or `_arg` as an argument name to indicate that it ' \ "won't be used. If it's unnecessary, remove it. You can also " \ 'write as `method(*)` if you want the method to accept any ' \ "arguments but don't care about them." expect_offense(<<~RUBY) def method(arg) ^^^ #{message} 1 end RUBY expect_correction(<<~RUBY) def method(_arg) 1 end RUBY end it 'accepts an empty method with multiple unused parameters' do expect_no_offenses(<<~RUBY) def method(a, b, *others) raise NotImplementedError end RUBY end it 'registers an offense for a non-empty method with multiple unused parameters' do (a_message, b_message, others_message) = %w[a b others].map do |arg| "Unused method argument - `#{arg}`. If it's necessary, use `_` or " \ "`_#{arg}` as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it. " \ 'You can also write as `method(*)` if you want the method ' \ "to accept any arguments but don't care about them." end expect_offense(<<~RUBY) def method(a, b, *others) ^^^^^^ #{others_message} ^ #{b_message} ^ #{a_message} 1 end RUBY expect_correction(<<~RUBY) def method(_a, _b, *_others) 1 end RUBY end context 'when `NotImplementedExceptions` is configured' do let(:cop_config) do { 'IgnoreNotImplementedMethods' => true, 'NotImplementedExceptions' => ['AbstractMethodError'] } end it 'accepts a method with a single unused parameter & raises AbstractMethodError' do expect_no_offenses(<<~RUBY) def method(arg) raise AbstractMethodError end RUBY end it 'accepts a method with a single unused parameter & raises AbstractMethodError, message' do expect_no_offenses(<<~RUBY) def method(arg) raise AbstractMethodError, message end RUBY end it 'accepts a method with a single unused parameter & raises ::AbstractMethodError' do expect_no_offenses(<<~RUBY) def method(arg) raise ::AbstractMethodError end RUBY end context 'when `NotImplementedExceptions` contains a namespaced exception class' do let(:cop_config) do { 'IgnoreNotImplementedMethods' => true, 'NotImplementedExceptions' => ['Library::AbstractMethodError'] } end it 'accepts a method with a single unused parameter & raises Library::AbstractMethodError' do expect_no_offenses(<<~RUBY) def method(arg) raise Library::AbstractMethodError end RUBY end it 'accepts a method with a single unused parameter & raises Library::AbstractMethodError, message' do expect_no_offenses(<<~RUBY) def method(arg) raise Library::AbstractMethodError, message end RUBY end it 'accepts a method with a single unused parameter & raises ::Library::AbstractMethodError' do expect_no_offenses(<<~RUBY) def method(arg) raise ::Library::AbstractMethodError 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/lint/useless_constant_scoping_spec.rb
spec/rubocop/cop/lint/useless_constant_scoping_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessConstantScoping, :config do it 'registers an offense when using constant after `private` access modifier' do expect_offense(<<~RUBY) class Foo private CONST = 42 ^^^^^^^^^^ Useless `private` access modifier for constant scope. end RUBY end it 'registers an offense when using constant not defined in `private_constant`' do expect_offense(<<~RUBY) class Foo private CONST = 42 ^^^^^^^^^^ Useless `private` access modifier for constant scope. private_constant :X end RUBY end it 'does not crash an offense when using constant and `private_constant` with variable argument' do expect_offense(<<~RUBY) class Foo private CONST = 42 ^^^^^^^^^^ Useless `private` access modifier for constant scope. private_constant var end RUBY end it 'registers an offense when multiple assigning to constants after `private` access modifier' do expect_offense(<<~RUBY) class Foo private FOO = BAR = 42 ^^^^^^^^^^^^^^ Useless `private` access modifier for constant scope. end RUBY end it 'does not register an offense when using constant' do expect_no_offenses(<<~RUBY) class Foo CONST = 42 end RUBY end it 'registers an offense when using constant after `private` access modifier in `class << self`' do expect_offense(<<~RUBY) class Foo class << self private CONST = 42 ^^^^^^^^^^ Useless `private` access modifier for constant scope. end end RUBY end it 'does not register an offense when using constant after `private` access modifier in `class << self` with `private_constant`' do expect_no_offenses(<<~RUBY) class Foo class << self private CONST = 42 private_constant :CONST end end RUBY end it 'does not register an offense when using constant defined in symbol argument of `private_constant`' do expect_no_offenses(<<~RUBY) class Foo private CONST = 42 private_constant :CONST end RUBY end it 'does not register an offense when using constant defined in multiple symbol arguments of `private_constant`' do expect_no_offenses(<<~RUBY) class Foo private CONST = 42 private_constant :CONST, :X end RUBY end it 'does not register an offense when using constant defined in string argument of `private_constant`' do expect_no_offenses(<<~RUBY) class Foo private CONST = 42 private_constant 'CONST' end RUBY end it 'does not register an offense when using constant after `private` access modifier with arguments' do expect_no_offenses(<<~RUBY) class Foo private do_something CONST = 42 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/lint/missing_cop_enable_directive_spec.rb
spec/rubocop/cop/lint/missing_cop_enable_directive_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::MissingCopEnableDirective, :config do context 'when the maximum range size is infinite' do let(:cop_config) { { 'MaximumRangeSize' => Float::INFINITY } } let(:other_cops) { { 'Layout/SpaceAroundOperators' => { 'Enabled' => true } } } it 'registers an offense when a cop is disabled and never re-enabled' do expect_offense(<<~RUBY) # rubocop:disable Layout/SpaceAroundOperators ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Re-enable Layout/SpaceAroundOperators cop with `# rubocop:enable` after disabling it. x = 0 # Some other code RUBY end it 'does not register an offense when the disable cop is re-enabled' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout/SpaceAroundOperators x = 0 # rubocop:enable Layout/SpaceAroundOperators # Some other code RUBY end it 'registers an offense when a department is disabled and never re-enabled' do expect_offense(<<~RUBY) # rubocop:disable Layout ^^^^^^^^^^^^^^^^^^^^^^^^ Re-enable Layout department with `# rubocop:enable` after disabling it. x = 0 # Some other code RUBY end it 'does not register an offense when the disable department is re-enabled' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout x = 0 # rubocop:enable Layout # Some other code RUBY end end context 'when the maximum range size is finite' do let(:cop_config) { { 'MaximumRangeSize' => 2 } } it 'registers an offense when a cop is disabled for too many lines' do expect_offense(<<~RUBY) # rubocop:disable Layout/SpaceAroundOperators ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Re-enable Layout/SpaceAroundOperators cop within 2 lines after disabling it. x = 0 y = 1 # Some other code # rubocop:enable Layout/SpaceAroundOperators RUBY end it 'registers an offense when a cop is disabled and never re-enabled' do expect_offense(<<~RUBY) # rubocop:disable Layout/SpaceAroundOperators ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Re-enable Layout/SpaceAroundOperators cop within 2 lines after disabling it. x = 0 # Some other code RUBY end it 'does not register an offense when the disable cop is re-enabled within the limit' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout/SpaceAroundOperators x = 0 y = 1 # rubocop:enable Layout/SpaceAroundOperators # Some other code RUBY end it 'registers an offense when a department is disabled for too many lines' do expect_offense(<<~RUBY) # rubocop:disable Layout ^^^^^^^^^^^^^^^^^^^^^^^^ Re-enable Layout department within 2 lines after disabling it. x = 0 y = 1 # Some other code # rubocop:enable Layout RUBY end it 'registers an offense when a department is disabled and never re-enabled' do expect_offense(<<~RUBY) # rubocop:disable Layout ^^^^^^^^^^^^^^^^^^^^^^^^ Re-enable Layout department within 2 lines after disabling it. x = 0 # Some other code RUBY end it 'does not register an offense when the disable department is re-enabled within the limit' do expect_no_offenses(<<~RUBY) # rubocop:disable Layout x = 0 y = 1 # rubocop:enable Layout # Some other code RUBY end end context 'when the cop is disabled in the config' do let(:other_cops) { { 'Layout/LineLength' => { 'Enabled' => false } } } it 'reports no offense when re-disabling it until EOF' do expect_no_offenses(<<~RUBY) # rubocop:enable Layout/LineLength # rubocop:disable Layout/LineLength 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/lint/interpolation_check_spec.rb
spec/rubocop/cop/lint/interpolation_check_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::InterpolationCheck, :config do it 'registers an offense and corrects for interpolation in single quoted string' do expect_offense(<<~'RUBY') 'foo #{bar}' ^^^^^^^^^^^^ Interpolation in single quoted string detected. Use double quoted strings if you need interpolation. RUBY expect_correction(<<~'RUBY') "foo #{bar}" RUBY end it 'registers an offense and corrects when including interpolation and double quoted string in single quoted string' do expect_offense(<<~'RUBY') 'foo "#{bar}"' ^^^^^^^^^^^^^^ Interpolation in single quoted string detected. Use double quoted strings if you need interpolation. RUBY expect_correction(<<~'RUBY') %{foo "#{bar}"} RUBY end it 'registers an offense for interpolation in single quoted split string' do expect_offense(<<~'RUBY') 'x' \ 'foo #{bar}' ^^^^^^^^^^^^ Interpolation in single quoted string detected. Use double quoted strings if you need interpolation. RUBY end it 'registers an offense for interpolation in double + single quoted split string' do expect_offense(<<~'RUBY') "x" \ 'foo #{bar}' ^^^^^^^^^^^^ Interpolation in single quoted string detected. Use double quoted strings if you need interpolation. RUBY end it 'does not register an offense for properly interpolation strings' do expect_no_offenses(<<~'RUBY') hello = "foo #{bar}" RUBY end it 'does not register an offense for interpolation in nested strings' do expect_no_offenses(<<~'RUBY') foo = "bar '#{baz}' qux" RUBY end it 'does not register an offense for interpolation in a regexp' do expect_no_offenses(<<~'RUBY') /\#{20}/ RUBY end it 'does not register an offense for an escaped interpolation' do expect_no_offenses(<<~'RUBY') "\#{msg}" RUBY end it 'does not crash for \xff' do expect_no_offenses(<<~'RUBY') foo = "\xff" RUBY end it 'does not register an offense for escaped crab claws in dstr' do expect_no_offenses(<<~'RUBY') foo = "alpha #{variable} beta \#{gamma}\" delta" RUBY end it 'does not register offense for strings in %w()' do expect_no_offenses(<<~'RUBY') %w("#{a}-foo") RUBY end it 'does not register an offense when using invalid syntax in interpolation' do expect_no_offenses(<<~'RUBY') '#{%<expression>s}' RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/implicit_string_concatenation_spec.rb
spec/rubocop/cop/lint/implicit_string_concatenation_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ImplicitStringConcatenation, :config do context 'on a single string literal' do it 'does not register an offense' do expect_no_offenses('abc') end end context 'on adjacent string literals on the same line' do it 'registers an offense' do expect_offense(<<~RUBY) class A; "abc" "def"; end ^^^^^^^^^^^ Combine "abc" and "def" into a single string literal, rather than using implicit string concatenation. class B; 'ghi' 'jkl'; end ^^^^^^^^^^^ Combine 'ghi' and 'jkl' into a single string literal, rather than using implicit string concatenation. RUBY expect_correction(<<~RUBY) class A; "abc" + "def"; end class B; 'ghi' + 'jkl'; end RUBY end end context 'on adjacent string interpolation literals on the same line' do it 'registers an offense' do expect_offense(<<~'RUBY') "string#{interpolation}" "def" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine "string#{interpolation}" and "def" into a single string literal, rather than using implicit string concatenation. RUBY expect_correction(<<~'RUBY') "string#{interpolation}" + "def" RUBY end end context 'on adjacent string interpolation literals on the same line with multiple concatenations' do it 'registers an offense' do expect_offense(<<~'RUBY') "foo""string#{interpolation}""bar" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine "string#{interpolation}" and "bar" into a single string literal, rather than using implicit string concatenation. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine "foo" and "string#{interpolation}" into a single string literal, rather than using implicit string concatenation. RUBY expect_correction(<<~'RUBY') "foo" + "string#{interpolation}" + "bar" RUBY end end context 'on adjacent string literals with triple quotes' do it 'registers an offense' do expect_offense(<<~RUBY) """string""" ^^^^^^^^^^ Combine "string" and "" into a single string literal, rather than using implicit string concatenation. ^^^^^^^^^^ Combine "" and "string" into a single string literal, rather than using implicit string concatenation. RUBY expect_correction(<<~RUBY) "string" RUBY end end context 'on adjacent string literals on different lines' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') array = [ 'abc'\ 'def' ] RUBY end end context 'when implicitly concatenating a string literal with a line break and string interpolation' do it 'registers an offense' do expect_offense(<<~'RUBY') 'single-quoted string'"string ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine 'single-quoted string' and "string\n" into a single string literal, rather than using implicit string concatenation. #{interpolation}" RUBY expect_correction(<<~'RUBY') 'single-quoted string' + "string #{interpolation}" RUBY end end context 'when the string literals contain newlines' do it 'registers an offense' do expect_offense(<<~'RUBY') def method "ab ^^^ Combine "ab\nc" and "de\nf" into a single string literal, [...] c" "de f" end RUBY expect_correction(<<~RUBY) def method "ab c" + "de f" end RUBY end it 'does not register an offense for a single string' do expect_no_offenses(<<~RUBY) 'abc def' RUBY end end context 'on a string with interpolations' do it 'does register an offense' do expect_no_offenses("array = [\"abc\#{something}def\#{something_else}\"]") end end context 'when inside an array' do it 'notes that the strings could be separated by a comma instead' do expect_offense(<<~RUBY) array = ["abc" "def"] ^^^^^^^^^^^ Combine "abc" and "def" into a single string literal, rather than using implicit string concatenation. Or, if they were intended to be separate array elements, separate them with a comma. RUBY expect_correction(<<~RUBY) array = ["abc" + "def"] RUBY end end context "when in a method call's argument list" do it 'notes that the strings could be separated by a comma instead' do expect_offense(<<~RUBY) method("abc" "def") ^^^^^^^^^^^ Combine "abc" and "def" into a single string literal, rather than using implicit string concatenation. Or, if they were intended to be separate method arguments, separate them with a comma. RUBY expect_correction(<<~RUBY) method("abc" + "def") 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/lint/uri_regexp_spec.rb
spec/rubocop/cop/lint/uri_regexp_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UriRegexp, :config do it 'does not register an offense when using `regexp` without receiver' do expect_no_offenses(<<~RUBY) regexp('http://example.com') RUBY end it 'does not register an offense when using `regexp` with variable receiver' do expect_no_offenses(<<~RUBY) m.regexp('http://example.com') RUBY end context 'Ruby <= 3.3', :ruby33 do it 'registers an offense and corrects using `URI.regexp` with argument' do expect_offense(<<~RUBY) URI.regexp('http://example.com') ^^^^^^ `URI.regexp('http://example.com')` is obsolete and should not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp('http://example.com')`. RUBY expect_correction(<<~RUBY) URI::DEFAULT_PARSER.make_regexp('http://example.com') RUBY end it 'registers an offense and corrects using `::URI.regexp` with argument' do expect_offense(<<~RUBY) ::URI.regexp('http://example.com') ^^^^^^ `::URI.regexp('http://example.com')` is obsolete and should not be used. Instead, use `::URI::DEFAULT_PARSER.make_regexp('http://example.com')`. RUBY expect_correction(<<~RUBY) ::URI::DEFAULT_PARSER.make_regexp('http://example.com') RUBY end it 'registers an offense and corrects using `URI.regexp` without argument' do expect_offense(<<~RUBY) URI.regexp ^^^^^^ `URI.regexp` is obsolete and should not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp`. RUBY expect_correction(<<~RUBY) URI::DEFAULT_PARSER.make_regexp RUBY end it 'registers an offense and corrects using `::URI.regexp` without argument' do expect_offense(<<~RUBY) ::URI.regexp ^^^^^^ `::URI.regexp` is obsolete and should not be used. Instead, use `::URI::DEFAULT_PARSER.make_regexp`. RUBY expect_correction(<<~RUBY) ::URI::DEFAULT_PARSER.make_regexp RUBY end context 'array argument' do it 'registers an offense and corrects using `URI.regexp` with literal arrays' do expect_offense(<<~RUBY) URI.regexp(['http', 'https']) ^^^^^^ `URI.regexp(['http', 'https'])` is obsolete and should not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp(['http', 'https'])`. RUBY expect_correction(<<~RUBY) URI::DEFAULT_PARSER.make_regexp(['http', 'https']) RUBY end it 'registers an offense and corrects using `URI.regexp` with %w arrays' do expect_offense(<<~RUBY) URI.regexp(%w[http https]) ^^^^^^ `URI.regexp(%w[http https])` is obsolete and should not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp(%w[http https])`. RUBY expect_correction(<<~RUBY) URI::DEFAULT_PARSER.make_regexp(%w[http https]) RUBY end it 'registers an offense and corrects using `URI.regexp` with %i arrays' do expect_offense(<<~RUBY) URI.regexp(%i[http https]) ^^^^^^ `URI.regexp(%i[http https])` is obsolete and should not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp(%i[http https])`. RUBY expect_correction(<<~RUBY) URI::DEFAULT_PARSER.make_regexp(%i[http https]) RUBY end end end context 'Ruby >= 3.4', :ruby34 do it 'registers an offense and corrects using `URI.regexp` with argument' do expect_offense(<<~RUBY) URI.regexp('http://example.com') ^^^^^^ `URI.regexp('http://example.com')` is obsolete and should not be used. Instead, use `URI::RFC2396_PARSER.make_regexp('http://example.com')`. RUBY expect_correction(<<~RUBY) URI::RFC2396_PARSER.make_regexp('http://example.com') 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/lint/to_enum_arguments_spec.rb
spec/rubocop/cop/lint/to_enum_arguments_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ToEnumArguments, :config do it 'registers an offense when required arg is missing' do expect_offense(<<~RUBY) def m(x) return to_enum(:m) unless block_given? ^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'registers an offense when optional arg is missing' do expect_offense(<<~RUBY) def m(x, y = 1) return to_enum(:m, x) unless block_given? ^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'registers an offense when splat arg is missing' do expect_offense(<<~RUBY) def m(x, y = 1, *args) return to_enum(:m, x, y) unless block_given? ^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'registers an offense when required keyword arg is missing' do expect_offense(<<~RUBY) def m(x, y = 1, *args, required:) return to_enum(:m, x, y, *args) unless block_given? ^^^^^^^^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'registers an offense when optional keyword arg is missing' do expect_offense(<<~RUBY) def m(x, y = 1, *args, required:, optional: true) return to_enum(:m, x, y, *args, required: required) unless block_given? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'registers an offense when splat keyword arg is missing' do expect_offense(<<~RUBY) def m(x, y = 1, *args, required:, optional: true, **kwargs) return to_enum(:m, x, y, *args, required: required, optional: optional) unless block_given? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'registers an offense when arguments are swapped' do expect_offense(<<~RUBY) def m(x, y = 1) return to_enum(:m, y, x) unless block_given? ^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'registers an offense when other values are passed for keyword arguments' do expect_offense(<<~RUBY) def m(required:, optional: true) return to_enum(:m, required: something_else, optional: optional) unless block_given? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'does not register an offense when not inside method definition' do expect_no_offenses(<<~RUBY) to_enum(:m) RUBY end it 'does not register an offense when method call has a receiver other than `self`' do expect_no_offenses(<<~RUBY) def m(x) return foo.to_enum(:m) unless block_given? end RUBY end it 'registers an offense when method is called on `self`' do expect_offense(<<~RUBY) def m(x) return self.to_enum(:m) unless block_given? ^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'ignores the block argument' do expect_no_offenses(<<~RUBY) def m(x, &block) return to_enum(:m, x) unless block_given? end RUBY end it 'does not register an offense when enumerator is created for another method' do expect_no_offenses(<<~RUBY) def m(x) return to_enum(:not_m) unless block_given? end RUBY end it 'does not register an offense when enumerator is created for another method in no arguments method definition' do expect_no_offenses(<<~RUBY) def m return to_enum(:not_m) unless block_given? end RUBY end it 'registers an offense when enumerator is created for `__method__` with missing arguments' do expect_offense(<<~RUBY) def m(x) return to_enum(__method__) unless block_given? ^^^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'does not register an offense when enumerator is not created for `__method__` and `__callee__` methods' do expect_no_offenses(<<~RUBY) def m(x) return to_enum(never_nullable(value), x) end RUBY end it 'does not register an offense when enumerator is not created for `__method__` and `__callee__` methods ' \ 'and using safe navigation operator' do expect_no_offenses(<<~RUBY) def m(x) return to_enum(obj&.never_nullable(value), x) end RUBY end %w[:m __callee__ __method__].each do |code| it "does not register an offense when enumerator is created with `#{code}` and the correct arguments" do expect_no_offenses(<<~RUBY) def m(x, y = 1, *args, required:, optional: true, **kwargs, &block) return to_enum(#{code}, x, y, *args, required: required, optional: optional, **kwargs) unless block_given? end RUBY end end context 'arguments forwarding', :ruby30 do it 'registers an offense when enumerator is created with non matching arguments' do expect_offense(<<~RUBY) def m(...) return to_enum(:m, x, ...) unless block_given? ^^^^^^^^^^^^^^^^^^^ Ensure you correctly provided all the arguments. end RUBY end it 'does not register an offense when enumerator is created with the correct arguments' do expect_no_offenses(<<~RUBY) def m(...) return to_enum(:m, ...) unless block_given? end RUBY end end context 'anonymous positional arguments forwarding', :ruby32 do it 'does not register an offense when enumerator is created with the correct arguments' do expect_no_offenses(<<~RUBY) def do_something(*) return to_enum(:do_something, *) unless block_given? do_something_else end RUBY end end context 'anonymous keyword arguments forwarding', :ruby32 do it 'does not register an offense when enumerator is created with the correct arguments' do expect_no_offenses(<<~RUBY) def do_something(**) return to_enum(:do_something, **) unless block_given? do_something_else end RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/empty_class_spec.rb
spec/rubocop/cop/lint/empty_class_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyClass, :config do let(:cop_config) { { 'AllowComments' => false } } it 'registers an offense for empty class' do expect_offense(<<~RUBY) class Foo ^^^^^^^^^ Empty class detected. end RUBY end it 'registers an offense for empty class metaclass' do expect_offense(<<~RUBY) class Foo class << self ^^^^^^^^^^^^^ Empty metaclass detected. end end RUBY end it 'registers an offense for empty object metaclass' do expect_offense(<<~RUBY) class << obj ^^^^^^^^^^^^ Empty metaclass detected. end RUBY end it 'registers an offense when empty metaclass contains only comments' do expect_offense(<<~RUBY) class Foo class << self ^^^^^^^^^^^^^ Empty metaclass detected. # Comment. end end RUBY end it 'does not register an offense when class is not empty' do expect_no_offenses(<<~RUBY) class Foo attr_reader :bar end RUBY end it 'does not register an offense when empty has a parent' do expect_no_offenses(<<~RUBY) class Child < Parent end RUBY end it 'does not register an offense when metaclass is not empty' do expect_no_offenses(<<~RUBY) class Foo class << self attr_reader :bar end end RUBY end context 'when AllowComments is true' do let(:cop_config) { { 'AllowComments' => true } } it 'does not register an offense when empty class contains only comments' do expect_no_offenses(<<~RUBY) class Foo # Comment. end RUBY end it 'does not register an offense when empty metaclass contains only comments' do expect_no_offenses(<<~RUBY) class Foo class << self # Comment. 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/lint/loop_spec.rb
spec/rubocop/cop/lint/loop_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::Loop, :config do it 'registers an offense and corrects for begin/end/while' do expect_offense(<<~RUBY) begin something end while test ^^^^^ Use `Kernel#loop` with `break` rather than `begin/end/until`(or `while`). RUBY expect_correction(<<~RUBY) loop do something break unless test end RUBY end it 'registers an offense for begin/end/until' do expect_offense(<<~RUBY) begin something end until test ^^^^^ Use `Kernel#loop` with `break` rather than `begin/end/until`(or `while`). RUBY expect_correction(<<~RUBY) loop do something break if test end RUBY end it 'accepts loop/break unless' do expect_no_offenses('loop do; one; two; break unless test; end') end it 'accepts loop/break if' do expect_no_offenses('loop do; one; two; break if test; 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/lint/redundant_splat_expansion_spec.rb
spec/rubocop/cop/lint/redundant_splat_expansion_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantSplatExpansion, :config do it 'allows assigning to a splat' do expect_no_offenses('*, rhs = *node') end it 'allows assigning to a splat variable' do expect_no_offenses('lhs, *args = *node') end it 'allows assigning a variable to a splat expansion of a variable' do expect_no_offenses('a = *b') end it 'allows assigning to an expanded range' do expect_no_offenses('a = *1..10') end it 'allows splat expansion inside of an array' do expect_no_offenses('a = [10, 11, *1..9]') end it 'accepts expanding a variable as a method parameter' do expect_no_offenses(<<~RUBY) foo = [1, 2, 3] array.push(*foo) RUBY end shared_examples 'splat literal assignment' do |literal, corrects, as_array: literal| it "registers an offense and #{corrects}" do expect_offense(<<~RUBY, literal: literal) a = *%{literal} ^^{literal} Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) a = #{as_array} RUBY end end shared_examples 'array splat expansion' do |literal, as_args: nil| context 'method parameters' do it 'registers an offense and converts to a list of arguments' do expect_offense(<<~RUBY, literal: literal) array.push(*%{literal}) ^^{literal} Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) array.push(#{as_args}) RUBY end end it_behaves_like 'splat literal assignment', literal, 'removes the splat from array', as_array: literal end shared_examples 'splat expansion' do |literal, as_array: literal| context 'method parameters' do it 'registers an offense and converts to an array' do expect_offense(<<~RUBY, literal: literal) array.push(*%{literal}) ^^{literal} Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) array.push(#{literal}) RUBY end end it_behaves_like 'splat literal assignment', literal, 'converts to an array', as_array: as_array end it_behaves_like 'array splat expansion', '[1, 2, 3]', as_args: '1, 2, 3' it_behaves_like 'splat expansion', "'a'", as_array: "['a']" it_behaves_like 'splat expansion', '"#{a}"', as_array: '["#{a}"]' it_behaves_like 'splat expansion', '1', as_array: '[1]' it_behaves_like 'splat expansion', '1.1', as_array: '[1.1]' context 'assignment to splat expansion' do it 'registers an offense and corrects an array using a constructor' do expect_offense(<<~RUBY) a = *Array.new(3) { 42 } ^^^^^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) a = Array.new(3) { 42 } RUBY end it 'registers and corrects an array using top-level const' do expect_offense(<<~RUBY) a = *::Array.new(3) { 42 } ^^^^^^^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) a = ::Array.new(3) { 42 } RUBY end end context 'expanding an array literal in a when condition' do it 'registers an offense and corrects an array using []' do expect_offense(<<~RUBY) case foo when *[first, second] ^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. bar end RUBY expect_correction(<<~RUBY) case foo when first, second bar end RUBY end it 'registers an offense and corrects an array using %w' do expect_offense(<<~RUBY) case foo when *%w(first second) ^^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. bar end RUBY expect_correction(<<~RUBY) case foo when 'first', 'second' bar end RUBY end it 'registers an offense and corrects an array using %W' do expect_offense(<<~RUBY) case foo when *%W(\#{first} second) ^^^^^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. bar end RUBY expect_correction(<<~RUBY) case foo when "\#{first}", "second" bar end RUBY end it 'registers an offense and corrects %i to a list of symbols' do expect_offense(<<~RUBY) case foo when *%i(first second) ^^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. baz end RUBY expect_correction(<<~RUBY) case foo when :first, :second baz end RUBY end it 'registers an offense and corrects %I to a list of symbols' do expect_offense(<<~RUBY) case foo when *%I(\#{first} second) ^^^^^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. baz end RUBY expect_correction(<<~RUBY) case foo when :"\#{first}", :"second" baz end RUBY end it 'allows an array that is assigned to a variable' do expect_no_offenses(<<~RUBY) baz = [1, 2, 3] case foo when *baz bar end RUBY end it 'allows an array using a constructor' do expect_no_offenses(<<~RUBY) case foo when *Array.new(3) { 42 } bar end RUBY end end it 'registers an offense and corrects an array literal being expanded in a rescue' do expect_offense(<<~RUBY) begin foo rescue *[First, Second] ^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. bar end RUBY expect_correction(<<~RUBY) begin foo rescue First, Second bar end RUBY end it 'allows expansions of an array that is assigned to a variable in rescue' do expect_no_offenses(<<~RUBY) ERRORS = [FirstError, SecondError] begin foo rescue *ERRORS bar end RUBY end it 'allows an array using a constructor' do expect_no_offenses(<<~RUBY) begin foo rescue *Array.new(3) { 42 } bad_example end RUBY end context 'splat expansion inside of an array' do it 'registers an offense and corrects the expansion of an array literal' \ 'inside of an array literal' do expect_offense(<<~RUBY) [1, 2, *[3, 4, 5], 6, 7] ^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) [1, 2, 3, 4, 5, 6, 7] RUBY end it 'registers an offense and corrects expansion of %w to a list of words' do expect_offense(<<~RUBY) ['a', 'b', *%w(c d e), 'f', 'g'] ^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) ['a', 'b', 'c', 'd', 'e', 'f', 'g'] RUBY end it 'registers an offense and corrects expansion of %W to a list of words' do expect_offense(<<~RUBY) ["a", "b", *%W(\#{one} two)] ^^^^^^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) ["a", "b", "\#{one}", "two"] RUBY end it 'registers an offense and corrects expansion of splatted string literal' do expect_offense(<<~RUBY) ["a", "b", *"c"] ^^^^ Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) ["a", "b", "c"] RUBY end end it 'allows expanding a method call on an array literal' do expect_no_offenses('[1, 2, *[3, 4, 5].map(&:to_s), 6, 7]') end describe 'expanding Array.new call on array literal' do context 'when the array literal contains exactly one element' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) [*Array.new(foo)] ^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) Array.new(foo) RUBY end end context 'when the array literal contains more than one element' do it 'accepts' do expect_no_offenses('[1, 2, *Array.new(foo), 6]') end end context 'with ::Array.new' do context 'when the array literal contains exactly one element' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) [*::Array.new(foo)] ^^^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) ::Array.new(foo) RUBY end end end end describe 'expanding Array.new call on method argument' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) send(method, *Array.new(foo)) ^^^^^^^^^^^^^^^ Replace splat expansion with comma separated values. RUBY expect_correction(<<~RUBY) send(method, Array.new(foo)) RUBY end end context 'arrays being expanded with %i variants using splat expansion' do context 'splat expansion inside of an array' do it 'registers an offense and corrects %i to a list of symbols' do expect_offense(<<~RUBY) [:a, :b, *%i(c d), :e] ^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) [:a, :b, :c, :d, :e] RUBY end it 'registers an offense and changes %I to a list of symbols' do expect_offense(<<~'RUBY') [:a, :b, *%I(#{one} two), :e] ^^^^^^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~'RUBY') [:a, :b, :"#{one}", :"two", :e] RUBY end end end context 'when `AllowPercentLiteralArrayArgument: true`' do let(:cop_config) { { 'AllowPercentLiteralArrayArgument' => true } } it 'does not register an offense when using percent string literal array' do expect_no_offenses(<<~RUBY) do_something(*%w[foo bar baz]) RUBY end it 'does not register an offense when using percent string literal array in safe navigation' do expect_no_offenses(<<~RUBY) maybe_nil&.do_something(*%w[foo bar baz]) RUBY end it 'does not register an offense when using percent symbol literal array' do expect_no_offenses(<<~RUBY) do_something(*%i[foo bar baz]) RUBY end end context 'when `AllowPercentLiteralArrayArgument: false`' do let(:cop_config) { { 'AllowPercentLiteralArrayArgument' => false } } it_behaves_like 'array splat expansion', '%w(one two three)', as_args: "'one', 'two', 'three'" it_behaves_like 'array splat expansion', '%W(one #{two} three)', as_args: '"one", "#{two}", "three"' it 'registers an offense when using percent literal array' do expect_offense(<<~RUBY) do_something(*%w[foo bar baz]) ^^^^^^^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) do_something('foo', 'bar', 'baz') RUBY end it 'registers an offense when using percent literal array in safe navigation' do expect_offense(<<~RUBY) maybe_nil&.do_something(*%w[foo bar baz]) ^^^^^^^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) maybe_nil&.do_something('foo', 'bar', 'baz') RUBY end it_behaves_like 'array splat expansion', '%i(first second)', as_args: ':first, :second' it_behaves_like 'array splat expansion', '%I(first second #{third})', as_args: ':"first", :"second", :"#{third}"' it 'registers an offense when using percent symbol literal array' do expect_offense(<<~RUBY) do_something(*%i[foo bar baz]) ^^^^^^^^^^^^^^^^ Pass array contents as separate arguments. RUBY end context 'splat expansion of method parameters' do it 'registers an offense and corrects an array literal %i' do expect_offense(<<~RUBY) array.push(*%i(first second)) ^^^^^^^^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) array.push(:first, :second) RUBY end it 'registers an offense and corrects an array literal %I' do expect_offense(<<~RUBY) array.push(*%I(\#{first} second)) ^^^^^^^^^^^^^^^^^^^^ Pass array contents as separate arguments. RUBY expect_correction(<<~RUBY) array.push(:"\#{first}", :"second") 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/lint/regexp_as_condition_spec.rb
spec/rubocop/cop/lint/regexp_as_condition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RegexpAsCondition, :config do it 'registers an offense and corrects for a regexp literal in `if` condition' do expect_offense(<<~RUBY) if /foo/ ^^^^^ Do not use regexp literal as a condition. The regexp literal matches `$_` implicitly. end RUBY expect_correction(<<~RUBY) if /foo/ =~ $_ end RUBY end it 'registers an offense and corrects for a regexp literal with bang in `if` condition' do expect_offense(<<~RUBY) if !/foo/ ^^^^^ Do not use regexp literal as a condition. The regexp literal matches `$_` implicitly. end RUBY expect_correction(<<~RUBY) if !/foo/ =~ $_ end RUBY end it 'does not register an offense for a regexp literal outside conditions' do expect_no_offenses(<<~RUBY) /foo/ RUBY end it 'does not register an offense for a regexp literal with bang outside conditions' do expect_no_offenses(<<~RUBY) !/foo/ RUBY end it 'does not register an offense for a regexp literal with `=~` operator' do expect_no_offenses(<<~RUBY) if /foo/ =~ str 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/lint/duplicate_require_spec.rb
spec/rubocop/cop/lint/duplicate_require_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateRequire, :config do it 'registers and corrects an offense when duplicate `require` is detected' do expect_offense(<<~RUBY) require 'foo' require 'foo' ^^^^^^^^^^^^^ Duplicate `require` detected. RUBY expect_correction(<<~RUBY) require 'foo' RUBY end it 'registers and corrects an offense when duplicate `require_relative` is detected' do expect_offense(<<~RUBY) require_relative '../bar' require_relative '../bar' ^^^^^^^^^^^^^^^^^^^^^^^^^ Duplicate `require_relative` detected. RUBY expect_correction(<<~RUBY) require_relative '../bar' RUBY end it 'registers and corrects an offense when duplicate `require` through `Kernel` is detected' do expect_offense(<<~RUBY) require 'foo' Kernel.require 'foo' ^^^^^^^^^^^^^^^^^^^^ Duplicate `require` detected. RUBY expect_correction(<<~RUBY) require 'foo' RUBY end it 'registers and corrects an offense for multiple duplicate requires' do expect_offense(<<~RUBY) require 'foo' require_relative '../bar' require 'foo/baz' require_relative '../bar' ^^^^^^^^^^^^^^^^^^^^^^^^^ Duplicate `require_relative` detected. Kernel.require 'foo' ^^^^^^^^^^^^^^^^^^^^ Duplicate `require` detected. require 'quux' RUBY expect_correction(<<~RUBY) require 'foo' require_relative '../bar' require 'foo/baz' require 'quux' RUBY end it 'registers and corrects an offense when duplicate requires are interleaved with some other code' do expect_offense(<<~RUBY) require 'foo' def m end require 'foo' ^^^^^^^^^^^^^ Duplicate `require` detected. RUBY expect_correction(<<~RUBY) require 'foo' def m end RUBY end it 'registers and corrects an offense for duplicate non top-level requires' do expect_offense(<<~RUBY) def m require 'foo' require 'foo' ^^^^^^^^^^^^^ Duplicate `require` detected. end RUBY expect_correction(<<~RUBY) def m require 'foo' end RUBY end it 'does not register an offense when there are no duplicate `require`s' do expect_no_offenses(<<~RUBY) require 'foo' require 'bar' RUBY end it 'does not register an offense when using single `require`' do expect_no_offenses(<<~RUBY) require 'foo' RUBY end it 'does not register an offense when same feature argument but different require method' do expect_no_offenses(<<~RUBY) require 'feature' require_relative 'feature' RUBY end it 'does not register an offense when calling user-defined `require` method' do expect_no_offenses(<<~RUBY) params.require(:user) params.require(:user) 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/lint/it_without_arguments_in_block_spec.rb
spec/rubocop/cop/lint/it_without_arguments_in_block_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ItWithoutArgumentsInBlock, :config do context '>= Ruby 3.4', :ruby34 do it 'does not register an offense when using `it` without arguments in a single line block' do expect_no_offenses(<<~RUBY) 0.times { it } RUBY end it 'does not register an offense when using `it` without arguments in a multiline block' do expect_no_offenses(<<~RUBY) 0.times do it it = 1 it end RUBY end end it 'registers an offense when using `it` without arguments in a single line block' do expect_offense(<<~RUBY) 0.times { it } ^^ `it` calls without arguments will refer to the first block param in Ruby 3.4; use `it()` or `self.it`. RUBY end it 'registers an offense when using `it` without arguments in a multiline block' do expect_offense(<<~RUBY) 0.times do it ^^ `it` calls without arguments will refer to the first block param in Ruby 3.4; use `it()` or `self.it`. it = 1 it end RUBY end it 'does not register an offense when using `it` with arguments in a single line block' do expect_no_offenses(<<~RUBY) 0.times { it(42) } RUBY end it 'does not register an offense when using `it` with block argument in a single line block' do expect_no_offenses(<<~RUBY) 0.times { it { do_something } } RUBY end it 'does not register an offense when using `it()` in a single line block' do expect_no_offenses(<<~RUBY) 0.times { it() } RUBY end it 'does not register an offense when using `self.it` in a single line block' do expect_no_offenses(<<~RUBY) 0.times { self.it } RUBY end it 'does not register an offense when using `it` with arguments in a multiline block' do expect_no_offenses(<<~RUBY) 0.times do it(42) it = 1 it end RUBY end it 'does not register an offense when using `it` with block argument in a multiline block' do expect_no_offenses(<<~RUBY) 0.times do it { do_something } it = 1 it end RUBY end it 'does not register an offense when using `it()` in a multiline block' do expect_no_offenses(<<~RUBY) 0.times do it() it = 1 it end RUBY end it 'does not register an offense when using `self.it` without arguments in a multiline block' do expect_no_offenses(<<~RUBY) 0.times do self.it it = 1 it end RUBY end it 'does not register an offense when using `it` without arguments in `if` body' do expect_no_offenses(<<~RUBY) if false it end RUBY end it 'does not register an offense when using `it` without arguments in `def` body' do expect_no_offenses(<<~RUBY) def foo it end RUBY end it 'does not register an offense when using `it` without arguments in a block with empty block parameter' do expect_no_offenses(<<~RUBY) 0.times { || it } RUBY end it 'does not register an offense when using `it` without arguments in a block with useless block parameter' do expect_no_offenses(<<~RUBY) 0.times { |_n| it } RUBY end it 'does not register an offense when using `it` inner local variable in block' do expect_no_offenses(<<~RUBY) 0.times do it = 1 it end RUBY end it 'does not register an offense when using `it` outer local variable in block' do expect_no_offenses(<<~RUBY) it = 1 0.times { it } RUBY end it 'does not register an offense when using empty block' do expect_no_offenses(<<~RUBY) 0.times {} 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/lint/inherit_exception_spec.rb
spec/rubocop/cop/lint/inherit_exception_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::InheritException, :config do context 'when class inherits from `Exception`' do context 'with enforced style set to `runtime_error`' do let(:cop_config) { { 'EnforcedStyle' => 'runtime_error' } } it 'registers an offense and corrects' do expect_offense(<<~RUBY) class C < Exception; end ^^^^^^^^^ Inherit from `RuntimeError` instead of `Exception`. RUBY expect_correction(<<~RUBY) class C < RuntimeError; end RUBY end context 'when creating a subclass using Class.new' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) Class.new(Exception) ^^^^^^^^^ Inherit from `RuntimeError` instead of `Exception`. RUBY expect_correction(<<~RUBY) Class.new(RuntimeError) RUBY end end context 'when inheriting `Exception`' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) module Foo class C < Exception; end # This `Exception` is the same as `::Exception`. ^^^^^^^^^ Inherit from `RuntimeError` instead of `Exception`. class Exception < RuntimeError; end end RUBY expect_correction(<<~RUBY) module Foo class C < RuntimeError; end # This `Exception` is the same as `::Exception`. class Exception < RuntimeError; end end RUBY end end context 'when inheriting `Exception` and has non-constant siblings' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) module Foo include Bar class C < Exception; end # This `Exception` is the same as `::Exception`. ^^^^^^^^^ Inherit from `RuntimeError` instead of `Exception`. class Exception < RuntimeError; end end RUBY expect_correction(<<~RUBY) module Foo include Bar class C < RuntimeError; end # This `Exception` is the same as `::Exception`. class Exception < RuntimeError; end end RUBY end end context 'when inheriting `::Exception`' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) module Foo class Exception < RuntimeError; end class C < ::Exception; end ^^^^^^^^^^^ Inherit from `RuntimeError` instead of `Exception`. end RUBY expect_correction(<<~RUBY) module Foo class Exception < RuntimeError; end class C < RuntimeError; end end RUBY end end context 'when inheriting a standard lib exception class that is not a subclass of `StandardError`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class C < Interrupt; end RUBY end end context 'when inheriting `Exception` with omitted namespace' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) module Foo class Exception < RuntimeError; end # This `Exception` is the same as `Foo::Exception`. class C < Exception; end end RUBY end end end context 'with enforced style set to `standard_error`' do let(:cop_config) { { 'EnforcedStyle' => 'standard_error' } } it 'registers an offense and corrects' do expect_offense(<<~RUBY) class C < Exception; end ^^^^^^^^^ Inherit from `StandardError` instead of `Exception`. RUBY expect_correction(<<~RUBY) class C < StandardError; end RUBY end context 'when creating a subclass using Class.new' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) Class.new(Exception) ^^^^^^^^^ Inherit from `StandardError` instead of `Exception`. RUBY expect_correction(<<~RUBY) Class.new(StandardError) RUBY end end context 'when inheriting `Exception`' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) module Foo class C < Exception; end # This `Exception` is the same as `::Exception`. ^^^^^^^^^ Inherit from `StandardError` instead of `Exception`. class Exception < RuntimeError; end end RUBY expect_correction(<<~RUBY) module Foo class C < StandardError; end # This `Exception` is the same as `::Exception`. class Exception < RuntimeError; end end RUBY end end context 'when inheriting `::Exception`' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) module Foo class Exception < RuntimeError; end class C < ::Exception; end ^^^^^^^^^^^ Inherit from `StandardError` instead of `Exception`. end RUBY expect_correction(<<~RUBY) module Foo class Exception < RuntimeError; end class C < StandardError; end end RUBY end end context 'when inheriting a standard lib exception class that is not a subclass of `StandardError`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class C < Interrupt; end RUBY end end context 'when inheriting `Exception` with omitted namespace' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) module Foo class Exception < StandardError; end # This `Exception` is the same as `Foo::Exception`. class C < Exception; end end RUBY end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/hash_new_with_keyword_arguments_as_default_spec.rb
spec/rubocop/cop/lint/hash_new_with_keyword_arguments_as_default_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::HashNewWithKeywordArgumentsAsDefault, :config do it 'registers an offense when using `Hash.new` with keyword arguments for default' do expect_offense(<<~RUBY) Hash.new(key: :value) ^^^^^^^^^^^ Use a hash literal instead of keyword arguments. RUBY expect_correction(<<~RUBY) Hash.new({key: :value}) RUBY end it 'registers an offense when using `Hash.new` with keyword arguments including `capacity` for default' do # NOTE: This `capacity` is used as a hash element for the initial value. expect_offense(<<~RUBY) Hash.new(capacity: 42, key: :value) ^^^^^^^^^^^^^^^^^^^^^^^^^ Use a hash literal instead of keyword arguments. RUBY expect_correction(<<~RUBY) Hash.new({capacity: 42, key: :value}) RUBY end it 'registers an offense when using `::Hash.new` with keyword arguments for default' do expect_offense(<<~RUBY) ::Hash.new(key: :value) ^^^^^^^^^^^ Use a hash literal instead of keyword arguments. RUBY expect_correction(<<~RUBY) ::Hash.new({key: :value}) RUBY end it 'registers an offense when using `Hash.new` with hash rocket argument for default' do expect_offense(<<~RUBY) Hash.new(:key => :value) ^^^^^^^^^^^^^^ Use a hash literal instead of keyword arguments. RUBY expect_correction(<<~RUBY) Hash.new({:key => :value}) RUBY end it 'registers an offense when using `Hash.new` with key as method call and hash rocket argument for default' do expect_offense(<<~RUBY) Hash.new(key => 'value') ^^^^^^^^^^^^^^ Use a hash literal instead of keyword arguments. RUBY expect_correction(<<~RUBY) Hash.new({key => 'value'}) RUBY end it 'does not register an offense when using `Hash.new` with hash for default' do expect_no_offenses(<<~RUBY) Hash.new({key: :value}) RUBY end it 'does not register an offense when using `Hash.new` with `capacity` keyword' do # NOTE: `capacity` is correctly used as a keyword argument. expect_no_offenses(<<~RUBY) Hash.new(capacity: 42) RUBY end it 'does not register an offense when using `Hash.new` with no arguments' do expect_no_offenses(<<~RUBY) Hash.new RUBY end it 'does not register an offense when using `.new` for no `Hash` receiver' do expect_no_offenses(<<~RUBY) Foo.new(key: :value) RUBY end it 'does not register an offense when using `Hash.new` with non hash object for default' do expect_no_offenses(<<~RUBY) Hash.new(42) RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/generator/require_file_injector_spec.rb
spec/rubocop/cop/generator/require_file_injector_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Generator::RequireFileInjector do let(:stdout) { StringIO.new } let(:root_file_path) { 'lib/root.rb' } let(:injector) do described_class.new(source_path: source_path, root_file_path: root_file_path, output: stdout) end around do |example| Dir.mktmpdir('rubocop-require_file_injector_spec-') do |dir| Dir.chdir(dir) do Dir.mkdir('lib') example.run end end end context 'when a `require_relative` entry does not exist from before' do let(:source_path) { 'lib/rubocop/cop/style/fake_cop.rb' } before do File.write(root_file_path, <<~RUBY) # frozen_string_literal: true require 'parser' require 'rainbow' require 'English' require 'set' require 'forwardable' require_relative 'rubocop/version' require_relative 'rubocop/cop/lint/flip_flop' require_relative 'rubocop/cop/style/end_block' require_relative 'rubocop/cop/style/even_odd' require_relative 'rubocop/cop/style/file_name' require_relative 'rubocop/cop/rails/action_filter' require_relative 'rubocop/cop/team' RUBY end it 'injects a `require_relative` statement on the right line in the root file' do generated_source = <<~RUBY # frozen_string_literal: true require 'parser' require 'rainbow' require 'English' require 'set' require 'forwardable' require_relative 'rubocop/version' require_relative 'rubocop/cop/lint/flip_flop' require_relative 'rubocop/cop/style/end_block' require_relative 'rubocop/cop/style/even_odd' require_relative 'rubocop/cop/style/fake_cop' require_relative 'rubocop/cop/style/file_name' require_relative 'rubocop/cop/rails/action_filter' require_relative 'rubocop/cop/team' RUBY injector.inject expect(File.read(root_file_path)).to eq generated_source expect(stdout.string).to eq(<<~MESSAGE) [modify] lib/root.rb - `require_relative 'rubocop/cop/style/fake_cop'` was injected. MESSAGE end end context 'when a cop of style department already exists' do let(:source_path) { 'lib/rubocop/cop/style/the_end_of_style.rb' } before do File.write(root_file_path, <<~RUBY) # frozen_string_literal: true require 'parser' require 'rainbow' require 'English' require 'set' require 'forwardable' require_relative 'rubocop/version' require_relative 'rubocop/cop/lint/flip_flop' require_relative 'rubocop/cop/style/end_block' require_relative 'rubocop/cop/style/even_odd' require_relative 'rubocop/cop/style/file_name' require_relative 'rubocop/cop/rails/action_filter' require_relative 'rubocop/cop/team' RUBY end it 'injects a `require_relative` statement on the end of style department' do generated_source = <<~RUBY # frozen_string_literal: true require 'parser' require 'rainbow' require 'English' require 'set' require 'forwardable' require_relative 'rubocop/version' require_relative 'rubocop/cop/lint/flip_flop' require_relative 'rubocop/cop/style/end_block' require_relative 'rubocop/cop/style/even_odd' require_relative 'rubocop/cop/style/file_name' require_relative 'rubocop/cop/style/the_end_of_style' require_relative 'rubocop/cop/rails/action_filter' require_relative 'rubocop/cop/team' RUBY injector.inject expect(File.read(root_file_path)).to eq generated_source expect(stdout.string).to eq(<<~MESSAGE) [modify] lib/root.rb - `require_relative 'rubocop/cop/style/the_end_of_style'` was injected. MESSAGE end end context 'when a `require` entry already exists' do let(:source_path) { 'lib/rubocop/cop/style/fake_cop.rb' } let(:source) { <<~RUBY } # frozen_string_literal: true require 'parser' require 'rainbow' require 'English' require 'set' require 'forwardable' require_relative 'rubocop/version' require_relative 'rubocop/cop/lint/flip_flop' require_relative 'rubocop/cop/style/end_block' require_relative 'rubocop/cop/style/even_odd' require_relative 'rubocop/cop/style/fake_cop' require_relative 'rubocop/cop/style/file_name' require_relative 'rubocop/cop/rails/action_filter' require_relative 'rubocop/cop/team' RUBY before { File.write(root_file_path, source) } it 'does not write to any file' do injector.inject expect(File.read(root_file_path)).to eq source expect(stdout.string).to be_empty end end context 'when using an unknown department' do let(:source_path) { 'lib/rubocop/cop/unknown/fake_cop.rb' } let(:source) { <<~RUBY } # frozen_string_literal: true require 'parser' require 'rainbow' require 'English' require 'set' require 'forwardable' require_relative 'rubocop/version' require_relative 'rubocop/cop/lint/flip_flop' require_relative 'rubocop/cop/style/end_block' require_relative 'rubocop/cop/style/even_odd' require_relative 'rubocop/cop/style/fake_cop' require_relative 'rubocop/cop/style/file_name' require_relative 'rubocop/cop/rails/action_filter' require_relative 'rubocop/cop/team' RUBY before { File.write(root_file_path, source) } it 'inserts a `require_relative` statement to the bottom of the file' do generated_source = <<~RUBY # frozen_string_literal: true require 'parser' require 'rainbow' require 'English' require 'set' require 'forwardable' require_relative 'rubocop/version' require_relative 'rubocop/cop/lint/flip_flop' require_relative 'rubocop/cop/style/end_block' require_relative 'rubocop/cop/style/even_odd' require_relative 'rubocop/cop/style/fake_cop' require_relative 'rubocop/cop/style/file_name' require_relative 'rubocop/cop/rails/action_filter' require_relative 'rubocop/cop/team' require_relative 'rubocop/cop/unknown/fake_cop' RUBY injector.inject expect(File.read(root_file_path)).to eq generated_source expect(stdout.string).to eq(<<~MESSAGE) [modify] lib/root.rb - `require_relative 'rubocop/cop/unknown/fake_cop'` was injected. MESSAGE end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/hash_slice_spec.rb
spec/rubocop/cop/style/hash_slice_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::HashSlice, :config do shared_examples 'include?' do context 'using `include?`' do it 'does not register an offense when using `select` and calling `!include?` method with symbol array' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !%i[foo bar].include?(k) } RUBY end it 'registers and corrects an offense when using `reject` and calling `!include?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| !%i[foo bar].include?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using `filter` and calling `include?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.filter { |k, v| [:foo, :bar].include?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using `select` and calling `include?` method with dynamic symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| %I[\#{foo} bar].include?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:"\#{foo}", :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:"\#{foo}", :bar) RUBY end it 'registers and corrects an offense when using `select` and calling `include?` method with dynamic string array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| %W[\#{foo} bar].include?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice("\#{foo}", 'bar')` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice("\#{foo}", 'bar') RUBY end it 'does not register an offense when using `select` and calling `!include?` method with variable' do expect_no_offenses(<<~RUBY) array = %i[foo bar] {foo: 1, bar: 2, baz: 3}.select { |k, v| !array.include?(k) } RUBY end it 'does not register an offense when using `select` and calling `!include?` method with method call' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !array.include?(k) } RUBY end it 'registers an offense when using `select` and `include?`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| [:bar].include?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it 'does not register an offense when using `select` and calling `!include?` method with symbol array and second block value' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| ![1, 2].include?(v) } RUBY end it 'does not register an offense when using `select` and calling `include?` method on a key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.include?('oo') } RUBY end it 'does not register an offense when using `select` and calling `!include?` method on a key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !k.include?('oo') } RUBY end it 'does not register an offense when using `select` with `include?` with an inclusive range receiver' do expect_no_offenses(<<~RUBY) { foo: 1, bar: 2, baz: 3 }.select{ |k, v| (:baa..:bbb).include?(k) } RUBY end it 'does not register an offense when using `select` with `include?` with an exclusive range receiver' do expect_no_offenses(<<~RUBY) { foo: 1, bar: 2, baz: 3 }.select{ |k, v| (:baa...:bbb).include?(k) } RUBY end it 'does not register an offense when using `select` with `include?` called on the key block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| k.include?('foo') } RUBY end it 'does not register an offense when using `select` with `include?` called on the value block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| v.include?(k) } RUBY end end end context 'Ruby 2.5 or higher', :ruby25 do it 'registers and corrects an offense when using `select` and comparing with `lvar == :sym`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k == :bar } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it 'registers and corrects an offense when using safe navigation `select` call and comparing with `lvar == :sym`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.select { |k, v| k == :bar } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.slice(:bar) RUBY end it 'registers and corrects an offense when using `select` and comparing with `:sym == lvar`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| :bar == k } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it 'registers and corrects an offense when using `reject` and comparing with `lvar != :sym`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| k != :bar } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it 'registers and corrects an offense when using `reject` and comparing with `:sym != lvar`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar != k } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it "registers and corrects an offense when using `select` and comparing with `lvar == 'str'`" do expect_offense(<<~RUBY) hash.select { |k, v| k == 'str' } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice('str')` instead. RUBY expect_correction(<<~RUBY) hash.slice('str') RUBY end it 'registers and corrects an offense when using `select` and other than comparison by string and symbol using `eql?`' do expect_offense(<<~RUBY) hash.select { |k, v| k.eql?(0.0) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(0.0)` instead. RUBY expect_correction(<<~RUBY) hash.slice(0.0) RUBY end it 'registers and corrects an offense when using `filter` and comparing with `lvar == :sym`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.filter { |k, v| k == :bar } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it_behaves_like 'include?' context 'using `in?`' do it 'does not register offenses when using `select` and calling `key.in?` method with symbol array' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.in?(%i[foo bar]) } RUBY end it 'does not register offenses when using safe navigation `select` and calling `key.in?` method with symbol array' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.select { |k, v| k.in?(%i[foo bar]) } RUBY end it 'does not register offenses when using `select` and calling `in?` method with key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| %i[foo bar].in?(k) } RUBY end it 'does not register an offense when using `select` with `include?` called on the value block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| k.in?(v) } RUBY end end context 'using `exclude?`' do it 'does not register offenses when using `select` and calling `!exclude?` method with symbol array' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !%i[foo bar].exclude?(k) } RUBY end it 'does not register offenses when using safe navigation `select` and calling `!exclude?` method with symbol array' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.select { |k, v| !%i[foo bar].exclude?(k) } RUBY end it 'does not register an offense when using `select` and calling `exclude?` method on a key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.exclude?('oo') } RUBY end it 'does not register an offense when using `select` and calling `!exclude?` method on a key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !k.exclude?('oo') } RUBY end it 'does not register an offense when using `select` with `!exclude?` called on the value block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| !v.exclude?(k) } RUBY end end it 'does not register an offense when using `select` and other than comparison by string and symbol using `==`' do expect_no_offenses(<<~RUBY) hash.select { |k, v| k == 0.0 } RUBY end it 'does not register an offense when using `reject` and other than comparison by string and symbol using `!=`' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| k != 0.0 } RUBY end it 'does not register an offense when using `reject` and other than comparison by string and symbol using `==` with bang' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| !(k == 0.0) } RUBY end it 'does not register an offense when using `select` and other than comparison by string and symbol using `!=` with bang' do expect_no_offenses(<<~RUBY) hash.select { |k, v| !(k != 0.0) } RUBY end it 'does not register an offense when using `delete_if` and comparing with `lvar == :sym`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.delete_if { |k, v| k == :bar } RUBY end it 'does not register an offense when using `keep_if` and comparing with `lvar != :sym`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.keep_if { |k, v| k != :bar } RUBY end it 'does not register an offense when comparing with hash value' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| v.eql? :bar } RUBY end it 'does not register an offense when using more than two block arguments' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v, o| k == :bar } RUBY end it 'does not register an offense when calling `include?` method without a param' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| %i[foo bar].include? } RUBY end context 'when `AllCops/ActiveSupportExtensionsEnabled: true`' do let(:config) do RuboCop::Config.new('AllCops' => { 'TargetRubyVersion' => '3.0', 'ActiveSupportExtensionsEnabled' => true }) end it 'registers and corrects an offense when using `select` and comparing with `lvar == :sym`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k == :bar } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it 'registers and corrects an offense when using `select` and comparing with `:sym == lvar`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| :bar == k } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it 'registers and corrects an offense when using `reject` and comparing with `lvar != :sym`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| k != :bar } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it 'registers and corrects an offense when using `reject` and comparing with `:sym != lvar`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar != k } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it "registers and corrects an offense when using `select` and comparing with `lvar == 'str'`" do expect_offense(<<~RUBY) hash.select { |k, v| k == 'str' } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice('str')` instead. RUBY expect_correction(<<~RUBY) hash.slice('str') RUBY end it 'registers and corrects an offense when using `select` and other than comparison by string and symbol using `eql?`' do expect_offense(<<~RUBY) hash.select { |k, v| k.eql?(0.0) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(0.0)` instead. RUBY expect_correction(<<~RUBY) hash.slice(0.0) RUBY end it 'registers and corrects an offense when using `filter` and comparing with `lvar == :sym`' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.filter { |k, v| k == :bar } ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end it_behaves_like 'include?' context 'using `in?`' do it 'registers and corrects an offense when using `select` and calling `key.in?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.in?(%i[foo bar]) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using safe navigation `select` and calling `key.in?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.select { |k, v| k.in?(%i[foo bar]) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using `reject` and calling `!key.in?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| !k.in?(%i[foo bar]) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using `filter` and calling `key.in?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.filter { |k, v| k.in?(%i[foo bar]) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using `select` and calling `key.in?` method with dynamic symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.in?(%I[\#{foo} bar]) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:"\#{foo}", :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:"\#{foo}", :bar) RUBY end it 'registers and corrects an offense when using `select` and calling `key.in?` method with dynamic string array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.in?(%W[\#{foo} bar]) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice("\#{foo}", 'bar')` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice("\#{foo}", 'bar') RUBY end it 'registers and corrects an offense when using `select` and calling `key.in?` method with variable' do expect_offense(<<~RUBY) array = %i[foo bar] {foo: 1, bar: 2, baz: 3}.select { |k, v| k.in?(array) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(*array)` instead. RUBY expect_correction(<<~RUBY) array = %i[foo bar] {foo: 1, bar: 2, baz: 3}.slice(*array) RUBY end it 'registers and corrects an offense when using `select` and calling `key.in?` method with method call' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.in?(array) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(*array)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(*array) RUBY end it 'does not register an offense when using `select` and calling `!key.in?` method with symbol array' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !k.in?(%i[foo bar]) } RUBY end it 'does not register an offense when using `select` and calling `in?` method with key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| %i[foo bar].in?(k) } RUBY end it 'does not register an offense when using `select` and calling `in?` method with symbol array and second block value' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| v.in?([1, 2]) } RUBY end it 'does not register an offense when using `select` with `in?` with an inclusive range argument' do expect_no_offenses(<<~RUBY) { foo: 1, bar: 2, baz: 3 }.select{ |k, v| k.in?(:baa..:bbb) } RUBY end it 'does not register an offense when using `select` with `in?` with an exclusive range argument' do expect_no_offenses(<<~RUBY) { foo: 1, bar: 2, baz: 3 }.select{ |k, v| k.in?(:baa...:bbb) } RUBY end it 'does not register an offense when using `select` with `in?` called on the key block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| 'foo'.in?(k) } RUBY end it 'does not register an offense when using `select` with `in?` called on the value block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| k.in?(v) } RUBY end it 'does not register an offense when using `reject` with `!in?` called on the key block variable' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| !'foo'.in?(k) } RUBY end it 'does not register an offense when using `reject` with `!in?` called on the value block variable' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| !k.in?(v) } RUBY end end context 'using `exclude?`' do it 'registers and corrects an offense when using `select` and calling `!exclude?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !%i[foo bar].exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using safe navigation `select` and calling `!exclude?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.select { |k, v| !%i[foo bar].exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}&.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using `reject` and calling `exclude?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| %i[foo bar].exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'does not register an offense when using `reject` and calling `!exclude?` method with symbol array' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| !%i[foo bar].exclude?(k) } RUBY end it 'registers and corrects an offense when using `filter` and calling `!exclude?` method with symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.filter { |k, v| ![:foo, :bar].exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:foo, :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:foo, :bar) RUBY end it 'registers and corrects an offense when using `select` and calling `!exclude?` method with dynamic symbol array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !%I[\#{foo} bar].exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(:"\#{foo}", :bar)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:"\#{foo}", :bar) RUBY end it 'registers and corrects an offense when using `select` and calling `!exclude?` method with dynamic string array' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !%W[\#{foo} bar].exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice("\#{foo}", 'bar')` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice("\#{foo}", 'bar') RUBY end it 'registers and corrects an offense when using `select` and calling `!exclude?` method with variable' do expect_offense(<<~RUBY) array = %i[foo bar] {foo: 1, bar: 2, baz: 3}.select { |k, v| !array.exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(*array)` instead. RUBY expect_correction(<<~RUBY) array = %i[foo bar] {foo: 1, bar: 2, baz: 3}.slice(*array) RUBY end it 'registers and corrects an offense when using `select` and calling `!exclude?` method with method call' do expect_offense(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !array.exclude?(k) } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `slice(*array)` instead. RUBY expect_correction(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(*array) RUBY end it 'does not register an offense when using `select` and calling `exclude?` method with symbol array and second block value' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| ![1, 2].exclude?(v) } RUBY end it 'does not register an offense when using `select` and calling `exclude?` method on a key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k.exclude?('oo') } RUBY end it 'does not register an offense when using `select` and calling `!exclude?` method on a key' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| !k.exclude?('oo') } RUBY end it 'does not register an offense when using `select` with `!exclude?` called on the key block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| !k.exclude?('foo') } RUBY end it 'does not register an offense when using `select` with `!exclude?` called on the value block variable' do expect_no_offenses(<<~RUBY) hash.select { |k, v| !v.exclude?(k) } RUBY end it 'does not register an offense when using `reject` with `exclude?` called on the key block variable' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| k.exclude?('foo') } RUBY end it 'does not register an offense when using `reject` with `exclude?` called on the value block variable' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| v.exclude?(k) } RUBY end end it 'does not register an offense when using `select` and other than comparison by string and symbol using `==`' do expect_no_offenses(<<~RUBY) hash.select { |k, v| k == 0.0 } RUBY end it 'does not register an offense when using `reject` and other than comparison by string and symbol using `!=`' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| k != 0.0 } RUBY end it 'does not register an offense when using `reject` and other than comparison by string and symbol using `==` with bang' do expect_no_offenses(<<~RUBY) hash.reject { |k, v| !(k == 0.0) } RUBY end it 'does not register an offense when using `select` and other than comparison by string and symbol using `!=` with bang' do expect_no_offenses(<<~RUBY) hash.select { |k, v| !(k != 0.0) } RUBY end it 'does not register an offense when using `delete_if` and comparing with `lvar == :sym`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.delete_if { |k, v| k == :bar } RUBY end it 'does not register an offense when using `keep_if` and comparing with `lvar != :sym`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.keep_if { |k, v| k != :bar } RUBY end it 'does not register an offense when comparing with hash value' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| v.eql? :bar } RUBY end it 'does not register an offense when using more than two block arguments' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v, z| k == :bar } RUBY end it 'does not register an offense when calling `include?` method without a param' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| %i[foo bar].include? } RUBY end end it 'does not register an offense when using `select` and comparing with `lvar != :key`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k != :bar } RUBY end it 'does not register an offense when using `select` and comparing with `:key != lvar`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| :bar != key } RUBY end it 'does not register an offense when using `reject` and comparing with `lvar == :key`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| k == :bar } RUBY end it 'does not register an offense when using `reject` and comparing with `:key == lvar`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar == key } RUBY end it 'does not register an offense when not using key block argument`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| do_something != :bar } RUBY end it 'does not register an offense when not using block`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select RUBY end it 'does not register an offense when using `Hash#slice`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.slice(:bar) RUBY end end context 'Ruby 2.4 or lower', :ruby24, unsupported_on: :prism do it 'does not register an offense when using `select` and comparing with `lvar == :key`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| k == :bar } RUBY end it 'does not register an offense when using `select` and comparing with `:key == lvar`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.select { |k, v| :bar == k } RUBY end it 'does not register an offense when using `reject` and comparing with `lvar != :key`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| k != :bar } RUBY end it 'does not register an offense when using `reject` and comparing with `:key != lvar`' do expect_no_offenses(<<~RUBY) {foo: 1, bar: 2, baz: 3}.reject { |k, v| :bar != k } RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trailing_comma_in_array_literal_spec.rb
spec/rubocop/cop/style/trailing_comma_in_array_literal_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::TrailingCommaInArrayLiteral, :config do shared_examples 'single line lists' do |extra_info| it 'registers an offense for trailing comma' do expect_offense(<<~RUBY) VALUES = [1001, 2020, 3333, ] ^ Avoid comma after the last item of an array#{extra_info}. RUBY expect_correction(<<~RUBY) VALUES = [1001, 2020, 3333 ] RUBY end it 'accepts literal without trailing comma' do expect_no_offenses('VALUES = [1001, 2020, 3333]') end it 'accepts single element literal without trailing comma' do expect_no_offenses('VALUES = [1001]') end it 'accepts empty literal' do expect_no_offenses('VALUES = []') end it 'accepts rescue clause' do # The list of rescued classes is an array. expect_no_offenses(<<~RUBY) begin do_something rescue RuntimeError end RUBY end end context 'with single line list of values' do context 'when EnforcedStyleForMultiline is no_comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'no_comma' } } it_behaves_like 'single line lists', '' end context 'when EnforcedStyleForMultiline is comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'comma' } } it_behaves_like 'single line lists', ', unless each item is on its own line' end context 'when EnforcedStyleForMultiline is diff_comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'diff_comma' } } it_behaves_like 'single line lists', ', unless that item immediately precedes a newline' end context 'when EnforcedStyleForMultiline is consistent_comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } } it_behaves_like 'single line lists', ', unless items are split onto multiple lines' end end context 'with multi-line list of values' do context 'when EnforcedStyleForMultiline is no_comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'no_comma' } } it 'registers an offense for trailing comma' do expect_offense(<<~RUBY) VALUES = [ 1001, 2020, 3333, ^ Avoid comma after the last item of an array. ] RUBY expect_correction(<<~RUBY) VALUES = [ 1001, 2020, 3333 ] RUBY end it 'accepts a literal with no trailing comma' do expect_no_offenses(<<~RUBY) VALUES = [ 1001, 2020, 3333 ] RUBY end it 'accepts HEREDOC with commas' do expect_no_offenses(<<~RUBY) [ <<-TEXT, 123 Something with a , in it TEXT ] RUBY end it 'autocorrects unwanted comma where HEREDOC has commas' do expect_offense(<<~RUBY) [ <<-TEXT, 123, ^ Avoid comma after the last item of an array. Something with a , in it TEXT ] RUBY expect_correction(<<~RUBY) [ <<-TEXT, 123 Something with a , in it TEXT ] RUBY end end context 'when EnforcedStyleForMultiline is comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'comma' } } context 'when closing bracket is on same line as last value' do it 'accepts literal with no trailing comma' do expect_no_offenses(<<~RUBY) VALUES = [ 1001, 2020, 3333] RUBY end end it 'accepts literal with two of the values on the same line' do expect_no_offenses(<<~RUBY) VALUES = [ 1001, 2020, 3333 ] RUBY end it 'registers an offense for a literal with two of the values ' \ 'on the same line and a trailing comma' do expect_offense(<<~RUBY) VALUES = [ 1001, 2020, 3333, ^ Avoid comma after the last item of an array, unless each item is on its own line. ] RUBY expect_correction(<<~RUBY) VALUES = [ 1001, 2020, 3333 ] RUBY end it 'accepts trailing comma' do expect_no_offenses(<<~RUBY) VALUES = [1001, 2020, 3333, ] RUBY end it 'accepts a multiline word array' do expect_no_offenses(<<~RUBY) ingredients = %w( sausage anchovies olives ) RUBY end it 'accepts an empty array being passed as a method argument' do expect_no_offenses(<<~RUBY) Foo.new([ ]) RUBY end it 'accepts a multiline array with a single item and trailing comma' do expect_no_offenses(<<~RUBY) foo = [ 1, ] RUBY end end context 'when EnforcedStyleForMultiline is diff_comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'diff_comma' } } context 'when closing bracket is on same line as last value' do it 'accepts no trailing comma' do expect_no_offenses(<<~RUBY) VALUES = [ 1001, 2020, 3333] RUBY end end it 'accepts two values on the same line' do expect_no_offenses(<<~RUBY) VALUES = [ 1001, 2020, 3333, ] RUBY end it 'registers an offense for literal with two of the values ' \ 'on the same line and no trailing comma' do expect_offense(<<~RUBY) VALUES = [ 1001, 2020, 3333 ^^^^ Put a comma after the last item of a multiline array. ] RUBY expect_correction(<<~RUBY) VALUES = [ 1001, 2020, 3333, ] RUBY end it 'accepts trailing comma' do expect_no_offenses(<<~RUBY) VALUES = [1001, 2020, 3333, ] RUBY end it 'accepts trailing comma with comment' do expect_no_offenses(<<~RUBY) VALUES = [1001, 2020, 3333, # comment ] RUBY end it 'registers an offense for a trailing comma on same line as closing bracket' do expect_offense(<<~RUBY) VALUES = [1001, 2020, 3333,] ^ Avoid comma after the last item of an array, unless that item immediately precedes a newline. RUBY expect_correction(<<~RUBY) VALUES = [1001, 2020, 3333] RUBY end it 'accepts a multiline word array' do expect_no_offenses(<<~RUBY) ingredients = %w( sausage anchovies olives ) RUBY end it 'accepts a multiline array with a single item and trailing comma' do expect_no_offenses(<<~RUBY) foo = [ 1, ] RUBY end it 'accepts a multiline array with items on a single line and trailing comma' do expect_no_offenses(<<~RUBY) foo = [ 1, 2, ] RUBY end end context 'when EnforcedStyleForMultiline is consistent_comma' do let(:cop_config) { { 'EnforcedStyleForMultiline' => 'consistent_comma' } } context 'when closing bracket is on same line as last value' do it 'registers an offense for no trailing comma' do expect_offense(<<~RUBY) VALUES = [ 1001, 2020, 3333] ^^^^ Put a comma after the last item of a multiline array. RUBY expect_correction(<<~RUBY) VALUES = [ 1001, 2020, 3333,] RUBY end end it 'accepts two values on the same line' do expect_no_offenses(<<~RUBY) VALUES = [ 1001, 2020, 3333, ] RUBY end it 'registers an offense for literal with two of the values ' \ 'on the same line and no trailing comma' do expect_offense(<<~RUBY) VALUES = [ 1001, 2020, 3333 ^^^^ Put a comma after the last item of a multiline array. ] RUBY expect_correction(<<~RUBY) VALUES = [ 1001, 2020, 3333, ] RUBY end it 'accepts trailing comma' do expect_no_offenses(<<~RUBY) VALUES = [1001, 2020, 3333, ] RUBY end it 'registers an offense for no trailing comma on same line as closing bracket' do expect_offense(<<~RUBY) VALUES = [1001, 2020, 3333] ^^^^ Put a comma after the last item of a multiline array. RUBY expect_correction(<<~RUBY) VALUES = [1001, 2020, 3333,] RUBY end it 'accepts a multiline word array' do expect_no_offenses(<<~RUBY) ingredients = %w( sausage anchovies olives ) RUBY end it 'accepts a multiline array with a single item and trailing comma' do expect_no_offenses(<<~RUBY) foo = [ 1, ] RUBY end it 'accepts a multiline array with items on a single line and trailing comma' do expect_no_offenses(<<~RUBY) foo = [ 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/style/numeric_predicate_spec.rb
spec/rubocop/cop/style/numeric_predicate_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::NumericPredicate, :config do context 'when configured to enforce numeric predicate methods' do let(:cop_config) { { 'EnforcedStyle' => 'predicate', 'AutoCorrect' => true } } context 'when checking if a number is zero' do it 'registers an offense' do expect_offense(<<~RUBY) number == 0 ^^^^^^^^^^^ Use `number.zero?` instead of `number == 0`. 0 == number ^^^^^^^^^^^ Use `number.zero?` instead of `0 == number`. RUBY expect_correction(<<~RUBY) number.zero? number.zero? RUBY end it 'registers an offense with a complex expression' do expect_offense(<<~RUBY) foo - 1 == 0 ^^^^^^^^^^^^ Use `(foo - 1).zero?` instead of `foo - 1 == 0`. 0 == foo - 1 ^^^^^^^^^^^^ Use `(foo - 1).zero?` instead of `0 == foo - 1`. RUBY expect_correction(<<~RUBY) (foo - 1).zero? (foo - 1).zero? RUBY end it 'allows comparing against a global variable' do expect_no_offenses('$CHILD_STATUS == 0') expect_no_offenses('0 == $CHILD_STATUS') end context 'when comparing against a method argument variable' do it 'registers an offense' do expect_offense(<<~RUBY) def m(foo) foo == 0 ^^^^^^^^ Use `foo.zero?` instead of `foo == 0`. end RUBY expect_correction(<<~RUBY) def m(foo) foo.zero? end RUBY end it 'registers an offense with complex expression' do expect_offense(<<~RUBY) def m(foo) foo - 1 == 0 ^^^^^^^^^^^^ Use `(foo - 1).zero?` instead of `foo - 1 == 0`. end RUBY expect_correction(<<~RUBY) def m(foo) (foo - 1).zero? end RUBY end end end context 'with checking if a number is not zero' do it 'allows comparing against a variable' do expect_no_offenses('number != 0') expect_no_offenses('0 != number') end it 'allows comparing against a complex expression' do expect_no_offenses('foo - 1 != 0') expect_no_offenses('0 != foo - 1') end it 'allows comparing against a global variable' do expect_no_offenses('$CHILD_STATUS != 0') expect_no_offenses('0 != $CHILD_STATUS') end end context 'when checking if a number is positive' do context 'when target ruby version is 2.3 or higher', :ruby23 do it 'registers an offense' do expect_offense(<<~RUBY) number > 0 ^^^^^^^^^^ Use `number.positive?` instead of `number > 0`. RUBY expect_correction(<<~RUBY) number.positive? RUBY end it 'registers an offense in yoda condition' do expect_offense(<<~RUBY) 0 < number ^^^^^^^^^^ Use `number.positive?` instead of `0 < number`. RUBY expect_correction(<<~RUBY) number.positive? RUBY end context 'with a complex expression' do it 'registers an offense' do expect_offense(<<~RUBY) foo - 1 > 0 ^^^^^^^^^^^ Use `(foo - 1).positive?` instead of `foo - 1 > 0`. RUBY expect_correction(<<~RUBY) (foo - 1).positive? RUBY end it 'registers an offense in yoda condition' do expect_offense(<<~RUBY) 0 < foo - 1 ^^^^^^^^^^^ Use `(foo - 1).positive?` instead of `0 < foo - 1`. RUBY expect_correction(<<~RUBY) (foo - 1).positive? RUBY end end end context 'when target ruby version is 2.2 or lower', :ruby22, unsupported_on: :prism do it 'does not register an offense' do expect_no_offenses('number > 0') end end end context 'when checking if a number is negative' do context 'when target ruby version is 2.3 or higher', :ruby23 do it 'registers an offense' do expect_offense(<<~RUBY) number < 0 ^^^^^^^^^^ Use `number.negative?` instead of `number < 0`. RUBY expect_correction(<<~RUBY) number.negative? RUBY end it 'registers an offense in yoda condition' do expect_offense(<<~RUBY) 0 > number ^^^^^^^^^^ Use `number.negative?` instead of `0 > number`. RUBY expect_correction(<<~RUBY) number.negative? RUBY end context 'with a complex expression' do it 'registers an offense' do expect_offense(<<~RUBY) foo - 1 < 0 ^^^^^^^^^^^ Use `(foo - 1).negative?` instead of `foo - 1 < 0`. RUBY expect_correction(<<~RUBY) (foo - 1).negative? RUBY end it 'registers an offense in yoda condition' do expect_offense(<<~RUBY) 0 > foo - 1 ^^^^^^^^^^^ Use `(foo - 1).negative?` instead of `0 > foo - 1`. RUBY expect_correction(<<~RUBY) (foo - 1).negative? RUBY end end end context 'when target ruby version is 2.2 or lower', :ruby22, unsupported_on: :prism do it 'does not register an offense' do expect_no_offenses('number < 0') end end end end context 'when configured to enforce numeric comparison methods' do let(:cop_config) { { 'EnforcedStyle' => 'comparison', 'AutoCorrect' => true } } it 'registers an offense for checking if a number is zero' do expect_offense(<<~RUBY) number.zero? ^^^^^^^^^^^^ Use `number == 0` instead of `number.zero?`. RUBY expect_correction(<<~RUBY) number == 0 RUBY end it 'registers an offense for checking if a number is not zero' do expect_offense(<<~RUBY) !number.zero? ^^^^^^^^^^^^ Use `(number == 0)` instead of `number.zero?`. RUBY expect_correction(<<~RUBY) !(number == 0) RUBY end it 'allows checking if a number is not zero' do expect_no_offenses('number.nonzero?') end it 'registers an offense for checking if a number is positive' do expect_offense(<<~RUBY) number.positive? ^^^^^^^^^^^^^^^^ Use `number > 0` instead of `number.positive?`. RUBY expect_correction(<<~RUBY) number > 0 RUBY end it 'registers an offense for checking if a number is negative' do expect_offense(<<~RUBY) number.negative? ^^^^^^^^^^^^^^^^ Use `number < 0` instead of `number.negative?`. RUBY expect_correction(<<~RUBY) number < 0 RUBY end end context 'when there are allowed methods' do let(:cop_config) do { 'EnforcedStyle' => 'predicate', 'AutoCorrect' => true, 'AllowedMethods' => ['where'], 'AllowedPatterns' => ['order'] } end context 'simple method call' do context '`EnforcedStyle` is `predicate`' do let(:cop_config) do { 'EnforcedStyle' => 'predicate', 'AllowedMethods' => %w[==], 'AllowedPatterns' => [] } end it 'allows checking if a number is zero' do expect_no_offenses(<<~RUBY) if number == 0 puts 'hello' end RUBY end end context '`EnforcedStyle` is `comparison`' do let(:cop_config) do { 'EnforcedStyle' => 'comparison', 'AllowedMethods' => [], 'AllowedPatterns' => ['zero'] } end it 'allows checking if a number is zero' do expect_no_offenses(<<~RUBY) if number.zero? puts 'hello' end RUBY end end end context 'in argument' do context 'ignored method' do context 'with a string' do it 'allows checking if a number is positive' do expect_no_offenses('where(Sequel[:number] > 0)') end it 'allows checking if a number is negative' do expect_no_offenses('where(Sequel[:number] < 0)') end end context 'with a regex' do it 'allows checking if a number is positive' do expect_no_offenses('order(Sequel[:number] > 0)') end it 'allows checking if a number is negative' do expect_no_offenses('order(Sequel[:number] < 0)') end end end context 'not ignored method' do context 'when checking if a number is positive' do context 'when target ruby version is 2.3 or higher', :ruby23 do it 'registers an offense' do expect_offense(<<~RUBY) exclude(number > 0) ^^^^^^^^^^ Use `number.positive?` instead of `number > 0`. RUBY expect_correction(<<~RUBY) exclude(number.positive?) RUBY end end context 'when target ruby version is 2.2 or lower', :ruby22, unsupported_on: :prism do it 'does not register an offense' do expect_no_offenses('exclude { number > 0 }') end end end context 'when checking if a number is negative' do context 'when target ruby version is 2.3 or higher', :ruby23 do it 'registers an offense' do expect_offense(<<~RUBY) exclude(number < 0) ^^^^^^^^^^ Use `number.negative?` instead of `number < 0`. RUBY expect_correction(<<~RUBY) exclude(number.negative?) RUBY end end context 'when target ruby version is 2.2 or lower', :ruby22, unsupported_on: :prism do it 'does not register an offense' do expect_no_offenses('exclude { number > 0 }') end end end end end context 'in block' do context 'ignored method' do context 'with a string' do it 'allows checking if a number is positive' do expect_no_offenses('where { table[number] > 0 }') end it 'allows checking if a number is negative' do expect_no_offenses('where { table[number] < 0 }') end end context 'with a regex' do it 'allows checking if a number is positive' do expect_no_offenses('order { table[number] > 0 }') end it 'allows checking if a number is negative' do expect_no_offenses('order { table[number] < 0 }') end end end context 'not ignored method' do it 'registers an offense for checking if a number is positive' do expect_offense(<<~RUBY) exclude { number > 0 } ^^^^^^^^^^ Use `number.positive?` instead of `number > 0`. RUBY expect_correction(<<~RUBY) exclude { number.positive? } RUBY end it 'registers an offense for checking if a number is negative' do expect_offense(<<~RUBY) exclude { number < 0 } ^^^^^^^^^^ Use `number.negative?` instead of `number < 0`. RUBY expect_correction(<<~RUBY) exclude { number.negative? } RUBY end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/file_null_spec.rb
spec/rubocop/cop/style/file_null_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::FileNull, :config do it 'does not register an offense for an empty string' do expect_no_offenses(<<~RUBY) "" RUBY end it 'does not register an offense when there is an invalid byte sequence error' do expect_no_offenses(<<~'RUBY') "\xa4" RUBY end it 'registers an offense and corrects when the entire string is `/dev/null`' do expect_offense(<<~RUBY) path = '/dev/null' ^^^^^^^^^^^ Use `File::NULL` instead of `/dev/null`. RUBY expect_correction(<<~RUBY) path = File::NULL RUBY end it "registers an offense and corrects when the entire string is `NUL` or '/dev/null'" do expect_offense(<<~RUBY) CONST = '/dev/null' ^^^^^^^^^^^ Use `File::NULL` instead of `/dev/null`. path = 'NUL' ^^^^^ Use `File::NULL` instead of `NUL`. RUBY expect_correction(<<~RUBY) CONST = File::NULL path = File::NULL RUBY end it "does not register an offense when the entire string is `NUL` without '/dev/null'" do expect_no_offenses(<<~RUBY) path = 'NUL' RUBY end it "registers an offense and corrects when the entire string is `NUL:` or '/dev/null'" do expect_offense(<<~RUBY) path = cond ? '/dev/null' : 'NUL:' ^^^^^^^^^^^ Use `File::NULL` instead of `/dev/null`. ^^^^^^ Use `File::NULL` instead of `NUL:`. RUBY # Different cops will detect duplication of the branch bodies. expect_correction(<<~RUBY) path = cond ? File::NULL : File::NULL RUBY end it "registers an offense when the entire string is `NUL:` without '/dev/null'" do expect_offense(<<~RUBY) path = 'NUL:' ^^^^^^ Use `File::NULL` instead of `NUL:`. RUBY expect_correction(<<~RUBY) path = File::NULL RUBY end it 'is case insensitive' do expect_offense(<<~RUBY) file = "nul" ^^^^^ Use `File::NULL` instead of `nul`. path = "/DEV/NULL" ^^^^^^^^^^^ Use `File::NULL` instead of `/DEV/NULL`. RUBY expect_correction(<<~RUBY) file = File::NULL path = File::NULL RUBY end it 'does not register an offense for a substring' do expect_no_offenses(<<~RUBY) 'the null devices are /dev/null on Unix and NUL on Windows' RUBY end it 'does not register an offense for a string within an array' do expect_no_offenses(<<~RUBY) ['/dev/null', 'NUL'] RUBY end it 'does not register an offense for a string within %w[]' do expect_no_offenses(<<~RUBY) %w[/dev/null NUL] RUBY end it 'does not register an offense for a hash key' do expect_no_offenses(<<~RUBY) { "/dev/null" => true, "nul" => false } RUBY end it 'does not register an offense for a hash value' do expect_no_offenses(<<~RUBY) { unix: "/dev/null", windows: "nul" } RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/if_unless_modifier_of_if_unless_spec.rb
spec/rubocop/cop/style/if_unless_modifier_of_if_unless_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::IfUnlessModifierOfIfUnless, :config do it 'provides a good error message' do expect_offense(<<~RUBY) condition ? then_part : else_part unless external_condition ^^^^^^ Avoid modifier `unless` after another conditional. RUBY expect_correction(<<~RUBY) unless external_condition condition ? then_part : else_part end RUBY end context 'ternary with modifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) condition ? then_part : else_part unless external_condition ^^^^^^ Avoid modifier `unless` after another conditional. RUBY expect_correction(<<~RUBY) unless external_condition condition ? then_part : else_part end RUBY end end context 'using nested mofifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) condition ? then_part : else_part if inner_condition if outer_condition ^^ Avoid modifier `if` after another conditional. ^^ Avoid modifier `if` after another conditional. RUBY expect_correction(<<~RUBY) if outer_condition if inner_condition condition ? then_part : else_part end end RUBY end end context 'conditional with modifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) unless condition then_part end if external_condition ^^ Avoid modifier `if` after another conditional. RUBY expect_correction(<<~RUBY) if external_condition unless condition then_part end end RUBY end end context '`unless` / `else` with modifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) unless condition then_part else else_part end if external_condition ^^ Avoid modifier `if` after another conditional. RUBY expect_correction(<<~RUBY) if external_condition unless condition then_part else else_part end end RUBY end end context 'conditional with modifier in body' do it 'accepts' do expect_no_offenses(<<~RUBY) if condition then_part if maybe? end RUBY end end context 'nested conditionals' do it 'accepts' do expect_no_offenses(<<~RUBY) if external_condition if condition then_part end end RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/send_with_literal_method_name_spec.rb
spec/rubocop/cop/style/send_with_literal_method_name_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::SendWithLiteralMethodName, :config do context 'when calling `public_send` with a symbol literal argument' do it 'registers an offense' do expect_offense(<<~RUBY) obj.public_send(:foo) ^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj.foo RUBY end context 'with safe navigation' do it 'registers an offense' do expect_offense(<<~RUBY) obj&.public_send(:foo) ^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj&.foo RUBY end end end context 'when calling `public_send` with a symbol literal argument and some arguments with parentheses' do it 'registers an offense' do expect_offense(<<~RUBY) obj.public_send(:foo, bar, 42) ^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj.foo(bar, 42) RUBY end context 'with safe navigation' do it 'registers an offense' do expect_offense(<<~RUBY) obj&.public_send(:foo, bar, 42) ^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj&.foo(bar, 42) RUBY end end end context 'when calling `public_send` with a symbol literal argument and some arguments without parentheses' do it 'registers an offense' do expect_offense(<<~RUBY) obj.public_send :foo, bar, 42 ^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj.foo bar, 42 RUBY end context 'with safe navigation' do it 'registers an offense' do expect_offense(<<~RUBY) obj&.public_send :foo, bar, 42 ^^^^^^^^^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj&.foo bar, 42 RUBY end end end context 'when calling `public_send` with a symbol literal argument without a receiver' do it 'registers an offense' do expect_offense(<<~RUBY) public_send(:foo) ^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) foo RUBY end end context 'when calling `public_send` with a string literal argument' do it 'registers an offense' do expect_offense(<<~RUBY) obj.public_send('foo') ^^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj.foo RUBY end context 'with safe navigation' do it 'registers an offense' do expect_offense(<<~RUBY) obj&.public_send('foo') ^^^^^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj&.foo RUBY end end end context 'when calling `public_send` with a method name with underscore' do it 'registers an offense' do expect_offense(<<~RUBY) obj.public_send("name_with_underscore") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `name_with_underscore` method call directly instead. RUBY expect_correction(<<~RUBY) obj.name_with_underscore RUBY end context 'with safe navigation' do it 'registers an offense' do expect_offense(<<~RUBY) obj&.public_send("name_with_underscore") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `name_with_underscore` method call directly instead. RUBY expect_correction(<<~RUBY) obj&.name_with_underscore RUBY end end end context 'when calling `public_send` with a method name with a variable argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send(variable) RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send(variable) RUBY end end end context 'when calling `public_send` with a method name with an interpolated string argument' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') obj.public_send("#{interpolated}string") RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') obj&.public_send("#{interpolated}string") RUBY end end end context 'when calling `public_send` with a method name with a space' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send("name with space") RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send("name with space") RUBY end end end context 'when calling `public_send` with a method name with a hyphen' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send("name-with-hyphen") RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send("name-with-hyphen") RUBY end end end context 'when calling `public_send` with a writer method name' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send("name=") RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send("name=") RUBY end end end context 'when calling `public_send` with a method name with braces' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send("{brackets}") RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send("{brackets}") RUBY end end end context 'when calling `public_send` with a method name with square brackets' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send("[square_brackets]") RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send("[square_brackets]") RUBY end end end context 'when calling `public_send` with a reserved word' do it 'does not register an offense' do described_class::RESERVED_WORDS.each do |reserved_word| expect_no_offenses(<<~RUBY) obj.public_send(:#{reserved_word}) RUBY end end context 'with safe navigation' do it 'does not register an offense' do described_class::RESERVED_WORDS.each do |reserved_word| expect_no_offenses(<<~RUBY) obj&.public_send(:#{reserved_word}) RUBY end end end end context 'when calling `public_send` with a integer literal argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send(42) RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send(42) RUBY end end end context 'when calling `public_send` without arguments' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.public_send RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.public_send RUBY end end end context 'when calling another method other than `public_send`' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.foo RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.foo RUBY end end end context 'when `AllowSend: true`' do let(:cop_config) { { 'AllowSend' => true } } context 'when calling `send` with a symbol literal argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.send(:foo) RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.send(:foo) RUBY end end end context 'when calling `__send__` with a symbol literal argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj.__send__(:foo) RUBY end context 'with safe navigation' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) obj&.__send__(:foo) RUBY end end end end context 'when `AllowSend: false`' do let(:cop_config) { { 'AllowSend' => false } } context 'when calling `send` with a symbol literal argument' do it 'registers an offense' do expect_offense(<<~RUBY) obj.send(:foo) ^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj.foo RUBY end context 'with safe navigation' do it 'registers an offense' do expect_offense(<<~RUBY) obj&.send(:foo) ^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj&.foo RUBY end end end context 'when calling `__send__` with a symbol literal argument' do it 'registers an offense' do expect_offense(<<~RUBY) obj.__send__(:foo) ^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj.foo RUBY end context 'with safe navigation' do it 'registers an offense' do expect_offense(<<~RUBY) obj&.__send__(:foo) ^^^^^^^^^^^^^^ Use `foo` method call directly instead. RUBY expect_correction(<<~RUBY) obj&.foo RUBY end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/string_methods_spec.rb
spec/rubocop/cop/style/string_methods_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::StringMethods, :config do let(:cop_config) { { 'intern' => 'to_sym' } } it 'registers an offense' do expect_offense(<<~RUBY) 'something'.intern ^^^^^^ Prefer `to_sym` over `intern`. RUBY expect_correction(<<~RUBY) 'something'.to_sym RUBY end context 'when using safe navigation operator' do it 'registers an offense' do expect_offense(<<~RUBY) something&.intern ^^^^^^ Prefer `to_sym` over `intern`. RUBY expect_correction(<<~RUBY) something&.to_sym RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/comparable_clamp_spec.rb
spec/rubocop/cop/style/comparable_clamp_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::ComparableClamp, :config do context 'target ruby version >= 2.4', :ruby24 do it 'registers and corrects an offense when using `if x < low` / `elsif high < x` / `else`' do expect_offense(<<~RUBY) if x < low ^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. low elsif high < x high else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `if low > x` / `elsif high < x` / `else`' do expect_offense(<<~RUBY) if low > x ^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. low elsif high < x high else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `if x < low` / `elsif x > high` / `else`' do expect_offense(<<~RUBY) if x < low ^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. low elsif x > high high else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `if low > x` / `elsif x > high` / `else`' do expect_offense(<<~RUBY) if low > x ^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. low elsif x > high high else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `if high < x` / `elsif x < low` / `else`' do expect_offense(<<~RUBY) if high < x ^^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. high elsif x < low low else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `if x > high` / `elsif x < low` / `else`' do expect_offense(<<~RUBY) if x > high ^^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. high elsif x < low low else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `if high < x` / `elsif low > x` / `else`' do expect_offense(<<~RUBY) if high < x ^^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. high elsif low > x low else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `if x > high` / `elsif low > x` / `else`' do expect_offense(<<~RUBY) if x > high ^^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. high elsif low > x low else x end RUBY expect_correction(<<~RUBY) x.clamp(low, high) RUBY end it 'registers and corrects an offense when using `elsif x > high` / `elsif low > x` / `else`' do expect_offense(<<~RUBY) if condition do_something elsif x > high ^^^^^^^^^^^^^^ Use `x.clamp(low, high)` instead of `if/elsif/else`. high elsif low > x low else x end RUBY expect_correction(<<~RUBY) if condition do_something else x.clamp(low, high) end RUBY end it 'does not register an offense when using `if x < low` / `elsif high < x` / `else` and all return values are the same' do expect_no_offenses(<<~RUBY) if x < low x elsif high < x x else x end RUBY end it 'registers an offense when using `[[x, low].max, high].min`' do expect_offense(<<~RUBY) [[x, low].max, high].min ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end it 'registers an offense when using `[[low, x].max, high].min`' do expect_offense(<<~RUBY) [[low, x].max, high].min ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end it 'registers an offense when using `[high, [x, low].max].min`' do expect_offense(<<~RUBY) [high, [x, low].max].min ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end it 'registers an offense when using `[high, [low, x].max].min`' do expect_offense(<<~RUBY) [high, [low, x].max].min ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end it 'registers an offense when using `[[x, high].min, low].max`' do expect_offense(<<~RUBY) [[x, high].min, low].max ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end it 'registers an offense when using `[[high, x].min, low].max`' do expect_offense(<<~RUBY) [[high, x].min, low].max ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end it 'registers but does not correct an offense when using `[[low, high].min].max`' do expect_offense(<<~RUBY) [low, [x, high].min].max ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end it 'registers but does not correct an offense when using `[low, [high, x].min].max`' do expect_offense(<<~RUBY) [low, [high, x].min].max ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Comparable#clamp` instead. RUBY expect_no_corrections end end context 'target ruby version <= 2.3', :ruby23, unsupported_on: :prism do it 'does not register an offense when using `[[x, low].max, high].min`' do expect_no_offenses(<<~RUBY) [[x, low].max, high].min RUBY end it 'does not register an offense when using `[[low, x].max, high].min`' do expect_no_offenses(<<~RUBY) [[low, x].max, high].min RUBY end it 'does not register an offense when using `[high, [x, low].max].min`' do expect_no_offenses(<<~RUBY) [high, [x, low].max].min RUBY end it 'does not register an offense when using `[high, [low, x].max].min`' do expect_no_offenses(<<~RUBY) [high, [low, x].max].min RUBY end end it 'does not register an offense when using `[low, high].min`' do expect_no_offenses(<<~RUBY) [low, high].min RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_assignment_spec.rb
spec/rubocop/cop/style/redundant_assignment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::RedundantAssignment, :config do it 'reports an offense for def ending with assignment and returning' do expect_offense(<<~RUBY) def func some_preceding_statements x = something ^^^^^^^^^^^^^ Redundant assignment before returning detected. x end RUBY expect_correction(<<~RUBY) def func some_preceding_statements something #{trailing_whitespace} end RUBY end context 'when inside begin-end body' do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY) def func some_preceding_statements begin x = something ^^^^^^^^^^^^^ Redundant assignment before returning detected. x end end RUBY expect_correction(<<~RUBY) def func some_preceding_statements begin something #{trailing_whitespace} end end RUBY end end context 'when rescue blocks present' do it 'registers an offense and autocorrects when inside function or rescue block' do expect_offense(<<~RUBY) def func 1 x = 2 ^^^^^ Redundant assignment before returning detected. x rescue SomeException 3 x = 4 ^^^^^ Redundant assignment before returning detected. x rescue AnotherException 5 end RUBY expect_correction(<<~RUBY) def func 1 2 #{trailing_whitespace} rescue SomeException 3 4 #{trailing_whitespace} rescue AnotherException 5 end RUBY end end it 'does not register an offense when ensure block present' do expect_no_offenses(<<~RUBY) def func 1 x = 2 x ensure 3 end RUBY end context 'when inside an if-branch' do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY) def func some_preceding_statements if x z = 1 ^^^^^ Redundant assignment before returning detected. z elsif y 2 else z = 3 ^^^^^ Redundant assignment before returning detected. z end end RUBY expect_correction(<<~RUBY) def func some_preceding_statements if x 1 #{trailing_whitespace} elsif y 2 else 3 #{trailing_whitespace} end end RUBY end end context 'when inside a when-branch' do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY) def func some_preceding_statements case x when y res = 1 ^^^^^^^ Redundant assignment before returning detected. res when z 2 when q else res = 3 ^^^^^^^ Redundant assignment before returning detected. res end end RUBY expect_correction(<<~RUBY) def func some_preceding_statements case x when y 1 #{trailing_whitespace} when z 2 when q else 3 #{trailing_whitespace} end end RUBY end end it 'accepts empty when nodes' do expect_no_offenses(<<~RUBY) def func case x when y then 1 when z # do nothing else 3 end end RUBY end context 'when inside an `in` branch' do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY) def func some_preceding_statements case x in y res = 1 ^^^^^^^ Redundant assignment before returning detected. res in z 2 in q else res = 3 ^^^^^^^ Redundant assignment before returning detected. res end end RUBY expect_correction(<<~RUBY) def func some_preceding_statements case x in y 1 #{trailing_whitespace} in z 2 in q else 3 #{trailing_whitespace} end end RUBY end end it 'accepts empty `in` nodes' do expect_no_offenses(<<~RUBY) def func case x in y then 1 in z # do nothing else 3 end end RUBY end it 'accepts empty method body' do expect_no_offenses(<<~RUBY) def func end RUBY end it 'accepts empty if body' do expect_no_offenses(<<~RUBY) def func if x elsif y else end end RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/it_block_parameter_spec.rb
spec/rubocop/cop/style/it_block_parameter_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::ItBlockParameter, :config do context '>= Ruby 3.4', :ruby34 do context 'EnforcedStyle: allow_single_line' do let(:cop_config) { { 'EnforcedStyle' => 'allow_single_line' } } it 'registers an offense when using multiline `it` parameters', unsupported_on: :parser do expect_offense(<<~RUBY) block do ^^^^^^^^ Avoid using `it` block parameter for multi-line blocks. do_something(it) end RUBY expect_no_corrections end it 'registers no offense when using `it` block parameter with multi-line method chain' do expect_no_offenses(<<~RUBY) collection.each .foo { puts it } RUBY end it 'registers an offense when using a single numbered parameters' do expect_offense(<<~RUBY) block { do_something(_1) } ^^ Use `it` block parameter. RUBY expect_correction(<<~RUBY) block { do_something(it) } RUBY end it 'registers an offense when using twice a single numbered parameters' do expect_offense(<<~RUBY) block do foo(_1) ^^ Use `it` block parameter. bar(_1) ^^ Use `it` block parameter. end RUBY expect_correction(<<~RUBY) block do foo(it) bar(it) end RUBY end it 'does not register an offense when using `it` block parameters' do expect_no_offenses(<<~RUBY) block { do_something(it) } RUBY end it 'does not register an offense when using named block parameters' do expect_no_offenses(<<~RUBY) block { |arg| do_something(arg) } RUBY end it 'does not register an offense when using multiple numbered parameters' do expect_no_offenses(<<~RUBY) block { do_something(_1, _2) } RUBY end it 'does not register an offense when using a single numbered parameters `_2`' do expect_no_offenses(<<~RUBY) block { do_something(_2) } RUBY end end context 'EnforcedStyle: only_numbered_parameters' do let(:cop_config) { { 'EnforcedStyle' => 'only_numbered_parameters' } } it 'registers an offense when using a single numbered parameters' do expect_offense(<<~RUBY) block { do_something(_1) } ^^ Use `it` block parameter. RUBY expect_correction(<<~RUBY) block { do_something(it) } RUBY end it 'registers an offense when using twice a single numbered parameters' do expect_offense(<<~RUBY) block do foo(_1) ^^ Use `it` block parameter. bar(_1) ^^ Use `it` block parameter. end RUBY expect_correction(<<~RUBY) block do foo(it) bar(it) end RUBY end it 'registers an offense when using a single numbered parameter after multiple numbered parameters in a method chain' do expect_offense(<<~RUBY) foo { bar(_1, _2) }.baz { qux(_1) } ^^ Use `it` block parameter. RUBY expect_correction(<<~RUBY) foo { bar(_1, _2) }.baz { qux(it) } RUBY end it 'does not register an offense when using `it` block parameters' do expect_no_offenses(<<~RUBY) block { do_something(it) } RUBY end it 'does not register an offense when using named block parameters' do expect_no_offenses(<<~RUBY) block { |arg| do_something(arg) } RUBY end it 'does not register an offense when using multiple numbered parameters' do expect_no_offenses(<<~RUBY) block { do_something(_1, _2) } RUBY end it 'does not register an offense when using a single numbered parameters `_2`' do expect_no_offenses(<<~RUBY) block { do_something(_2) } RUBY end end context 'EnforcedStyle: always' do let(:cop_config) { { 'EnforcedStyle' => 'always' } } it 'registers an offense when using a single numbered parameters' do expect_offense(<<~RUBY) block { do_something(_1) } ^^ Use `it` block parameter. RUBY expect_correction(<<~RUBY) block { do_something(it) } RUBY end it 'registers an offense when using twice a single numbered parameters' do expect_offense(<<~RUBY) block do foo(_1) ^^ Use `it` block parameter. bar(_1) ^^ Use `it` block parameter. end RUBY expect_correction(<<~RUBY) block do foo(it) bar(it) end RUBY end it 'registers an offense when using a single named block parameters' do expect_offense(<<~RUBY) block { |arg| do_something(arg) } ^^^ Use `it` block parameter. RUBY expect_correction(<<~RUBY) block { do_something(it) } RUBY end it 'registers an offense when using twice a single named parameters' do expect_offense(<<~RUBY) block do |arg| foo(arg) ^^^ Use `it` block parameter. bar(arg) ^^^ Use `it` block parameter. end RUBY expect_correction(<<~RUBY) block do#{' '} foo(it) bar(it) end RUBY end it 'does not register an offense when using `it` block parameters' do expect_no_offenses(<<~RUBY) block { do_something(it) } RUBY end it 'does not register an offense when using multiple numbered parameters' do expect_no_offenses(<<~RUBY) block { do_something(_1, _2) } RUBY end it 'does not register an offense when using a single numbered parameters `_2`' do expect_no_offenses(<<~RUBY) block { do_something(_2) } RUBY end it 'does not register an offense when using multiple named block parameters' do expect_no_offenses(<<~RUBY) block { |foo, bar| do_something(foo, bar) } RUBY end it 'does not register an offense for block with parameter and missing body' do expect_no_offenses(<<~RUBY) block do |_| end RUBY end end context 'EnforcedStyle: disallow' do let(:cop_config) { { 'EnforcedStyle' => 'disallow' } } it 'registers an offense when using `it` block parameters' do expect_offense(<<~RUBY) block { do_something(it) } ^^ Avoid using `it` block parameter. RUBY expect_no_corrections end it 'registers an offense when using twice `it` block parameters' do expect_offense(<<~RUBY) block do foo(it) ^^ Avoid using `it` block parameter. bar(it) ^^ Avoid using `it` block parameter. end RUBY expect_no_corrections end it 'does not register an offense when using a single numbered parameters' do expect_no_offenses(<<~RUBY) block { do_something(_1) } RUBY end it 'does not register an offense when using named block parameters' do expect_no_offenses(<<~RUBY) block { |arg| do_something(arg) } RUBY end it 'does not register an offense when using multiple numbered parameters' do expect_no_offenses(<<~RUBY) block { do_something(_1, _2) } RUBY end it 'does not register an offense when using a single numbered parameters `_2`' do expect_no_offenses(<<~RUBY) block { do_something(_2) } RUBY end end end context '<= Ruby 3.3', :ruby33 do context 'EnforcedStyle: only_numbered_parameters' do let(:cop_config) { { 'EnforcedStyle' => 'only_numbered_parameters' } } it 'does not register an offense when using a single numbered parameters' do expect_no_offenses(<<~RUBY) block { do_something(_1) } RUBY end end context 'EnforcedStyle: always' do let(:cop_config) { { 'EnforcedStyle' => 'always' } } it 'does not register an offense when using a single numbered parameters' do expect_no_offenses(<<~RUBY) block { do_something(_1) } RUBY end it 'does not register an offense when using a single named block parameters' do expect_no_offenses(<<~RUBY) block { |arg| do_something(arg) } RUBY end end context 'EnforcedStyle: disallow' do let(:cop_config) { { 'EnforcedStyle' => 'disallow' } } it 'does not register an offense when using `it` block parameters' do expect_no_offenses(<<~RUBY) block { do_something(it) } RUBY end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/require_order_spec.rb
spec/rubocop/cop/style/require_order_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::RequireOrder, :config do context 'when `require` is sorted' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'a' require 'b' RUBY end it 'registers no offense when single-quoted string and double-quoted string are mixed' do expect_no_offenses(<<~RUBY) require 'a' require "b" RUBY end end context 'when only one `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'a' RUBY end end context 'when `require` is not sorted in different sections' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'b' require 'd' require 'a' require 'c' RUBY end end context 'when `require` is not sorted' do it 'registers an offense' do expect_offense(<<~RUBY) require 'b' require 'a' ^^^^^^^^^^^ Sort `require` in alphabetical order. RUBY expect_correction(<<~RUBY) require 'a' require 'b' RUBY end end context 'when unsorted `require` has some inline comments' do it 'registers an offense' do expect_offense(<<~RUBY) require 'b' # comment require 'a' ^^^^^^^^^^^ Sort `require` in alphabetical order. RUBY expect_correction(<<~RUBY) require 'a' require 'b' # comment RUBY end end context 'when unsorted `require` has some full-line comments' do it 'registers an offense' do expect_offense(<<~RUBY) require 'b' # comment require 'a' ^^^^^^^^^^^ Sort `require` in alphabetical order. RUBY expect_correction(<<~RUBY) # comment require 'a' require 'b' RUBY end end context 'when `require_relative` is not sorted' do it 'registers an offense' do expect_offense(<<~RUBY) require_relative 'b' require_relative 'a' ^^^^^^^^^^^^^^^^^^^^ Sort `require_relative` in alphabetical order. RUBY expect_correction(<<~RUBY) require_relative 'a' require_relative 'b' RUBY end end context 'when multiple `require` are not sorted' do it 'registers an offense' do expect_offense(<<~RUBY) require 'd' require 'a' ^^^^^^^^^^^ Sort `require` in alphabetical order. require 'b' ^^^^^^^^^^^ Sort `require` in alphabetical order. require 'c' ^^^^^^^^^^^ Sort `require` in alphabetical order. RUBY expect_correction(<<~RUBY) require 'a' require 'b' require 'c' require 'd' RUBY end end context 'when both `require` and `require_relative` are in same section' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'b' require_relative 'a' RUBY end end context 'when `require_relative` is put between unsorted `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'c' require_relative 'b' require 'a' RUBY end end context 'when `require` is a method argument' do it 'registers no offense' do expect_no_offenses(<<~RUBY) do_something(require) RUBY end end context 'when `Bundler.require` is put between unsorted `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'e' Bundler.require(:default) require 'c' RUBY end end context 'when `Bundler.require` with no arguments is put between `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'c' Bundler.require require 'a' RUBY end end context 'when something other than a method call is used between `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'a' begin end require 'b' RUBY end end context 'when `if` is used between `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'c' if foo require 'a' end require 'b' RUBY end end context 'when `unless` is used between `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'c' unless foo require 'a' end require 'b' RUBY end end context 'when conditional with multiple `require` is used between `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'd' if foo require 'a' require 'b' end require 'c' RUBY end end context 'when conditional with multiple unsorted `require` is used between `require`' do it 'registers an offense' do expect_offense(<<~RUBY) require 'd' if foo require 'b' require 'a' ^^^^^^^^^^^ Sort `require` in alphabetical order. end require 'c' RUBY expect_correction(<<~RUBY) require 'd' if foo require 'a' require 'b' end require 'c' RUBY end end context 'when nested conditionals is used between `require`' do it 'registers no offense' do expect_no_offenses(<<~RUBY) require 'c' if foo if bar require 'a' end end require 'b' RUBY end end context 'when modifier conditional `if` is used between `require`' do it 'registers an offense' do expect_offense(<<~RUBY) require 'c' require 'a' if foo ^^^^^^^^^^^ Sort `require` in alphabetical order. require 'b' ^^^^^^^^^^^ Sort `require` in alphabetical order. RUBY expect_correction(<<~RUBY) require 'a' if foo require 'b' require 'c' RUBY end end context 'when modifier conditional `unless` is used between `require`' do it 'registers an offense' do expect_offense(<<~RUBY) require 'c' require 'a' unless foo ^^^^^^^^^^^ Sort `require` in alphabetical order. require 'b' ^^^^^^^^^^^ Sort `require` in alphabetical order. RUBY expect_correction(<<~RUBY) require 'a' unless foo require 'b' require 'c' RUBY end end context 'when rescue block' do it 'registers an offense for multiple unsorted `require`s' do expect_offense(<<~RUBY) begin do_something rescue require 'b' require 'a' ^^^^^^^^^^^ Sort `require` in alphabetical order. end RUBY expect_correction(<<~RUBY) begin do_something rescue require 'a' require 'b' end RUBY end it 'registers no offense for single `require`' do expect_no_offenses(<<~RUBY) begin do_something rescue require 'a' end RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/dir_empty_spec.rb
spec/rubocop/cop/style/dir_empty_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::DirEmpty, :config do context 'target ruby version >= 2.4', :ruby24 do it 'registers an offense for `Dir.entries.size == 2`' do expect_offense(<<~RUBY) Dir.entries('path/to/dir').size == 2 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Dir.empty?('path/to/dir')` instead. RUBY expect_correction(<<~RUBY) Dir.empty?('path/to/dir') RUBY end it 'registers an offense for `Dir.entries.size != 2`' do expect_offense(<<~RUBY) Dir.entries('path/to/dir').size != 2 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!Dir.empty?('path/to/dir')` instead. RUBY expect_correction(<<~RUBY) !Dir.empty?('path/to/dir') RUBY end it 'registers an offense for `Dir.entries.size > 2`' do expect_offense(<<~RUBY) Dir.entries('path/to/dir').size > 2 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `!Dir.empty?('path/to/dir')` instead. RUBY expect_correction(<<~RUBY) !Dir.empty?('path/to/dir') RUBY end it 'registers an offense for `Dir.entries.size == 2` with line break' do expect_offense(<<~RUBY) Dir. ^^^^ Use `Dir.empty?('path/to/dir')` instead. entries('path/to/dir').size == 2 RUBY expect_correction(<<~RUBY) Dir.empty?('path/to/dir') RUBY end it 'registers an offense for `Dir.children.empty?`' do expect_offense(<<~RUBY) Dir.children('path/to/dir').empty? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Dir.empty?('path/to/dir')` instead. RUBY expect_correction(<<~RUBY) Dir.empty?('path/to/dir') RUBY end it 'registers an offense for `Dir.children == 0`' do expect_offense(<<~RUBY) Dir.children('path/to/dir').size == 0 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Dir.empty?('path/to/dir')` instead. RUBY expect_correction(<<~RUBY) Dir.empty?('path/to/dir') RUBY end it 'registers an offense for `Dir.each_child.none?`' do expect_offense(<<~RUBY) Dir.each_child('path/to/dir').none? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Dir.empty?('path/to/dir')` instead. RUBY expect_correction(<<~RUBY) Dir.empty?('path/to/dir') RUBY end it 'registers an offense for `!Dir.each_child.none?`' do expect_offense(<<~RUBY) !Dir.each_child('path/to/dir').none? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Dir.empty?('path/to/dir')` instead. RUBY expect_correction(<<~RUBY) !Dir.empty?('path/to/dir') RUBY end it 'does not register an offense for `Dir.empty?`' do expect_no_offenses('Dir.empty?("path/to/dir")') end it 'does not register an offense for non-offending methods' do expect_no_offenses('Dir.exist?("path/to/dir")') end end context 'target ruby version < 2.4', :ruby23, unsupported_on: :prism do it 'does not register an offense for `Dir.entries.size == 2`' do expect_no_offenses('Dir.entries("path/to/dir").size == 2') end it 'does not register an offense for `Dir.children.empty?`' do expect_no_offenses('Dir.children("path/to/dir").empty?') end it 'does not register an offense for `Dir.children == 0`' do expect_no_offenses('Dir.children("path/to/dir") == 0') end it 'does not register an offense for `Dir.each_child.none?`' do expect_no_offenses('Dir.each_child("path/to/dir").none?') end it 'does not register an offense for `Dir.empty?`' do expect_no_offenses('Dir.empty?("path/to/dir")') end it 'does not register an offense for non-offending methods' do expect_no_offenses('Dir.exist?("path/to/dir")') end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/redundant_file_extension_in_require_spec.rb
spec/rubocop/cop/style/redundant_file_extension_in_require_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::RedundantFileExtensionInRequire, :config do it 'registers an offense and corrects when requiring filename ending with `.rb`' do expect_offense(<<~RUBY) require 'foo.rb' ^^^ Redundant `.rb` file extension detected. require_relative '../foo.rb' ^^^ Redundant `.rb` file extension detected. RUBY expect_correction(<<~RUBY) require 'foo' require_relative '../foo' RUBY end it 'does not register an offense when requiring filename ending with `.so`' do expect_no_offenses(<<~RUBY) require 'foo.so' require_relative '../foo.so' RUBY end it 'does not register an offense when requiring filename without an extension' do expect_no_offenses(<<~RUBY) require 'foo' require_relative '../foo' RUBY end it 'does not register an offense when requiring variable as a filename' do expect_no_offenses(<<~RUBY) require name require_relative name RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/nested_modifier_spec.rb
spec/rubocop/cop/style/nested_modifier_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::NestedModifier, :config do shared_examples 'not correctable' do |keyword| it "does not autocorrect when #{keyword} is the outer modifier" do expect_offense(<<~RUBY, keyword: keyword) something if a %{keyword} b ^^ Avoid using nested modifiers. RUBY expect_no_corrections end it "does not autocorrect when #{keyword} is the inner modifier" do expect_offense(<<~RUBY, keyword: keyword) something %{keyword} a if b ^{keyword} Avoid using nested modifiers. RUBY expect_no_corrections end end it 'autocorrects if + if' do expect_offense(<<~RUBY) something if a if b ^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something if b && a RUBY end it 'autocorrects unless + unless' do expect_offense(<<~RUBY) something unless a unless b ^^^^^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something unless b || a RUBY end it 'autocorrects if + unless' do expect_offense(<<~RUBY) something if a unless b ^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something unless b || !a RUBY end it 'autocorrects unless with a comparison operator + if' do expect_offense(<<~RUBY) something unless b > 1 if true ^^^^^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something if true && !(b > 1) RUBY end it 'autocorrects unless + if' do expect_offense(<<~RUBY) something unless a if b ^^^^^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something if b && !a RUBY end it 'adds parentheses when needed in autocorrection' do expect_offense(<<~RUBY) something if a || b if c || d ^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something if (c || d) && (a || b) RUBY end it 'adds parentheses to method arguments when needed in autocorrection' do expect_offense(<<~RUBY) a unless [1, 2].include? a if a ^^^^^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) a if a && ![1, 2].include?(a) RUBY end it 'does not add redundant parentheses in autocorrection' do expect_offense(<<~RUBY) something if a unless c || d ^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something unless c || d || !a RUBY end context 'while' do it_behaves_like 'not correctable', 'while' end context 'until' do it_behaves_like 'not correctable', 'until' end it 'registers one offense for more than two modifiers' do expect_offense(<<~RUBY) something until a while b unless c if d ^^^^^^ Avoid using nested modifiers. RUBY expect_correction(<<~RUBY) something until a while b if d && !c RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/bare_percent_literals_spec.rb
spec/rubocop/cop/style/bare_percent_literals_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::BarePercentLiterals, :config do shared_examples 'accepts other delimiters' do it 'accepts __FILE__' do expect_no_offenses('__FILE__') end it 'accepts regular expressions' do expect_no_offenses('/%Q?/') end it 'accepts ""' do expect_no_offenses('""') end it 'accepts "" string with interpolation' do expect_no_offenses('"#{file}hi"') end it "accepts ''" do expect_no_offenses("'hi'") end it 'accepts %q' do expect_no_offenses('%q(hi)') end it 'accepts heredoc' do expect_no_offenses(<<~RUBY) func <<HEREDOC hi HEREDOC RUBY end end context 'when EnforcedStyle is percent_q' do let(:cop_config) { { 'EnforcedStyle' => 'percent_q' } } context 'and strings are static' do it 'registers an offense for %()' do expect_offense(<<~RUBY) %(hi) ^^ Use `%Q` instead of `%`. RUBY expect_correction(<<~RUBY) %Q(hi) RUBY end it 'accepts %Q()' do expect_no_offenses('%Q(hi)') end it_behaves_like 'accepts other delimiters' end context 'and strings are dynamic' do it 'registers an offense for %()' do expect_offense(<<~'RUBY') %(#{x}) ^^ Use `%Q` instead of `%`. RUBY expect_correction(<<~'RUBY') %Q(#{x}) RUBY end it 'accepts %Q()' do expect_no_offenses('%Q(#{x})') end it_behaves_like 'accepts other delimiters' end end context 'when EnforcedStyle is bare_percent' do let(:cop_config) { { 'EnforcedStyle' => 'bare_percent' } } context 'and strings are static' do it 'registers an offense for %Q()' do expect_offense(<<~RUBY) %Q(hi) ^^^ Use `%` instead of `%Q`. RUBY expect_correction(<<~RUBY) %(hi) RUBY end it 'accepts %()' do expect_no_offenses('%(hi)') end it_behaves_like 'accepts other delimiters' end context 'and strings are dynamic' do it 'registers an offense for %Q()' do expect_offense(<<~'RUBY') %Q(#{x}) ^^^ Use `%` instead of `%Q`. RUBY expect_correction(<<~'RUBY') %(#{x}) RUBY end it 'accepts %()' do expect_no_offenses('%(#{x})') end it_behaves_like 'accepts other delimiters' end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/string_hash_keys_spec.rb
spec/rubocop/cop/style/string_hash_keys_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::StringHashKeys, :config do it 'registers an offense when using strings as keys' do expect_offense(<<~RUBY) { 'one' => 1 } ^^^^^ Prefer symbols instead of strings as hash keys. RUBY expect_correction(<<~RUBY) { :one => 1 } RUBY end it 'registers an offense when using strings as keys mixed with other keys' do expect_offense(<<~RUBY) { 'one' => 1, two: 2, 3 => 3 } ^^^^^ Prefer symbols instead of strings as hash keys. RUBY expect_correction(<<~RUBY) { :one => 1, two: 2, 3 => 3 } RUBY end it 'autocorrects strings as keys into symbols with the correct syntax' do expect_offense(<<~RUBY) { 'one two :' => 1 } ^^^^^^^^^^^ Prefer symbols instead of strings as hash keys. RUBY expect_correction(<<~RUBY) { :"one two :" => 1 } RUBY end it 'does not register an offense when not using strings as keys' do expect_no_offenses(<<~RUBY) { one: 1 } RUBY end it 'does not register an offense when using invalid symbol in encoding UTF-8 as keys' do expect_no_offenses(<<~RUBY) { "Test with malformed utf8 \\251" => 'test-with-malformed-utf8' } RUBY end it 'does not register an offense when string key is used in IO.popen' do expect_no_offenses(<<~RUBY) IO.popen({"RUBYOPT" => '-w'}, 'ruby', 'foo.rb') RUBY end it 'does not register an offense when string key is used in Open3.capture3' do expect_no_offenses(<<~RUBY) Open3.capture3({"RUBYOPT" => '-w'}, 'ruby', 'foo.rb') RUBY end it 'does not register an offense when string key is used in Open3.pipeline' do expect_no_offenses(<<~RUBY) Open3.pipeline([{"RUBYOPT" => '-w'}, 'ruby', 'foo.rb'], ['wc', '-l']) RUBY end it 'does not register an offense when string key is used in gsub' do expect_no_offenses(<<~RUBY) "The sky is green.".gsub(/green/, "green" => "blue") RUBY end it 'does not register an offense when string key is used in gsub!' do expect_no_offenses(<<~RUBY) "The sky is green.".gsub!(/green/, "green" => "blue") RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/each_with_object_spec.rb
spec/rubocop/cop/style/each_with_object_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::EachWithObject, :config do it 'finds inject and reduce with passed in and returned hash' do expect_offense(<<~RUBY) [].inject({}) { |a, e| a } ^^^^^^ Use `each_with_object` instead of `inject`. [].reduce({}) do |a, e| ^^^^^^ Use `each_with_object` instead of `reduce`. a[e] = 1 a[e] = 1 a end RUBY expect_correction(<<~RUBY) [].each_with_object({}) { |e, a| } [].each_with_object({}) do |e, a| a[e] = 1 a[e] = 1 end RUBY end it 'finds inject is safe navigation called with passed in and returned hash' do expect_offense(<<~RUBY) []&.inject({}) { |a, e| a } ^^^^^^ Use `each_with_object` instead of `inject`. RUBY expect_correction(<<~RUBY) []&.each_with_object({}) { |e, a| } RUBY end context 'Ruby 2.7', :ruby27 do it 'finds inject and reduce with passed in and returned hash and numblock' do expect_offense(<<~RUBY) [].reduce({}) do ^^^^^^ Use `each_with_object` instead of `reduce`. _1[_2] = 1 _1 end RUBY expect_correction(<<~RUBY) [].each_with_object({}) do _2[_1] = 1 _2 end RUBY end it 'finds `reduce` is called with passed in and returned hash and numblock' do expect_offense(<<~RUBY) []&.reduce({}) do ^^^^^^ Use `each_with_object` instead of `reduce`. _1[_2] = 1 _1 end RUBY expect_correction(<<~RUBY) []&.each_with_object({}) do _2[_1] = 1 _2 end RUBY end end it 'correctly autocorrects' do expect_offense(<<~RUBY) [1, 2, 3].inject({}) do |h, i| ^^^^^^ Use `each_with_object` instead of `inject`. h[i] = i h end RUBY expect_correction(<<~RUBY) [1, 2, 3].each_with_object({}) do |i, h| h[i] = i end RUBY end it 'correctly autocorrects with return value only' do expect_offense(<<~RUBY) [1, 2, 3].inject({}) do |h, i| ^^^^^^ Use `each_with_object` instead of `inject`. h end RUBY expect_correction(<<~RUBY) [1, 2, 3].each_with_object({}) do |i, h| end RUBY end it 'ignores inject and reduce with block without arguments' do expect_no_offenses(<<~RUBY) [].inject({}) { $GLOBAL[rand] = rand; $GLOBAL } [].reduce({}) do $GLOBAL[rand] = rand $GLOBAL end RUBY end it 'ignores inject and reduce with block with single argument' do expect_no_offenses(<<~RUBY) [].inject({}) { |h| h[rand] = rand; h } [].reduce({}) do |h| h[rand] = rand h end RUBY end it 'ignores inject and reduce with passed in, but not returned hash' do expect_no_offenses(<<~RUBY) [].inject({}) do |a, e| a + e end [].reduce({}) do |a, e| my_method e, a end RUBY end it 'ignores inject and reduce with empty body' do expect_no_offenses(<<~RUBY) [].inject({}) do |a, e| end [].reduce({}) { |a, e| } RUBY end it 'ignores inject and reduce with condition as body' do expect_no_offenses(<<~RUBY) [].inject({}) do |a, e| a = e if e end [].inject({}) do |a, e| if e a = e end end [].reduce({}) do |a, e| a = e ? e : 2 end RUBY end it 'ignores inject and reduce passed in symbol' do expect_no_offenses('[].inject(:+)') end it 'does not blow up for reduce with no arguments' do expect_no_offenses('[1, 2, 3].inject { |a, e| a + e }') end it 'ignores inject/reduce with assignment to accumulator param in block' do expect_no_offenses(<<~RUBY) r = [1, 2, 3].reduce({}) do |memo, item| memo += item > 2 ? item : 0 memo end RUBY end context 'when a simple literal is passed as initial value' do it 'ignores inject/reduce' do expect_no_offenses('array.reduce(0) { |a, e| a }') end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/if_inside_else_spec.rb
spec/rubocop/cop/style/if_inside_else_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::IfInsideElse, :config do let(:cop_config) { { 'AllowIfModifier' => false } } it 'catches an if node nested inside an else' do expect_offense(<<~RUBY) if a blah else if b ^^ Convert `if` nested inside `else` to `elsif`. foo end end RUBY expect_correction(<<~RUBY) if a blah elsif b foo end RUBY end it 'catches an if..else nested inside an else' do expect_offense(<<~RUBY) if a blah else if b ^^ Convert `if` nested inside `else` to `elsif`. foo else # This is expected to be autocorrected by `Layout/IndentationWidth`. bar end end RUBY expect_correction(<<~RUBY) if a blah elsif b foo else # This is expected to be autocorrected by `Layout/IndentationWidth`. bar end RUBY end it 'catches an `if..else` nested inside an `else` and nested inside `if` branch code is empty' do expect_offense(<<~RUBY) if a foo else if b ^^ Convert `if` nested inside `else` to `elsif`. # TODO: comment. else bar end end RUBY expect_correction(<<~RUBY) if a foo elsif b # TODO: comment. else bar end RUBY end it 'catches an `if..else` nested inside an `else` with comments in both branches' do expect_offense(<<~RUBY) if a foo else if b ^^ Convert `if` nested inside `else` to `elsif`. # this is very important bar # this too else # this three baz # this four end end RUBY expect_correction(<<~RUBY) if a foo elsif b # this is very important bar # this too else # this three baz # this four end RUBY end it 'catches an if..elsif..else nested inside an else' do expect_offense(<<~RUBY) if a blah else if b ^^ Convert `if` nested inside `else` to `elsif`. foo elsif c # This is expected to be autocorrected by `Layout/IndentationWidth`. bar elsif d baz else qux end end RUBY expect_correction(<<~RUBY) if a blah elsif b foo elsif c # This is expected to be autocorrected by `Layout/IndentationWidth`. bar elsif d baz else qux end RUBY end it 'catches a modifier if nested inside an else after elsif' do expect_offense(<<~RUBY) if a blah elsif b foo else # important info bar if condition # blabla ^^ Convert `if` nested inside `else` to `elsif`. end RUBY expect_correction(<<~RUBY) if a blah elsif b foo elsif condition # important info bar # blabla end RUBY end it 'handles a nested `if...then...end`' do expect_offense(<<~RUBY) if x 'x' else if y then 'y' end ^^ Convert `if` nested inside `else` to `elsif`. end RUBY expect_correction(<<~RUBY) if x 'x' else if y 'y' end end RUBY end it 'handles a nested `if...then...else...end`' do expect_offense(<<~RUBY) if x 'x' else if y then 'y' else 'z' end ^^ Convert `if` nested inside `else` to `elsif`. end RUBY expect_correction(<<~RUBY) if x 'x' elsif y 'y' else 'z' end RUBY end it 'handles a nested `if...then...elsif...end`' do expect_offense(<<~RUBY) if x 'x' else if y then 'y' elsif z then 'z' end ^^ Convert `if` nested inside `else` to `elsif`. end RUBY expect_correction(<<~RUBY) if x 'x' else if y 'y' elsif z 'z' end end RUBY end it 'handles a nested `if...then...elsif...else...end`' do expect_offense(<<~RUBY) if x 'x' else if y then 'y' elsif z then 'z' else 'a' end ^^ Convert `if` nested inside `else` to `elsif`. end RUBY expect_correction(<<~RUBY) if x 'x' elsif y 'y' elsif z 'z' else 'a' end RUBY end it 'handles a nested multiline `if...then...elsif...else...end`' do expect_offense(<<~RUBY) if x 'x' else if y then 'y' ^^ Convert `if` nested inside `else` to `elsif`. elsif z then 'z' else 'a' end end RUBY expect_correction(<<~RUBY) if x 'x' else if y 'y' elsif z 'z' else 'a' end end RUBY end it 'handles a deep nested multiline `if...then...elsif...else...end`' do expect_offense(<<~RUBY) if cond else if nested_one ^^ Convert `if` nested inside `else` to `elsif`. else if c ^^ Convert `if` nested inside `else` to `elsif`. if d else if e ^^ Convert `if` nested inside `else` to `elsif`. end end end end end RUBY expect_correction(<<~RUBY) if cond elsif nested_one else if c if d else if e end end end end RUBY end context 'when AllowIfModifier is false' do it 'catches a modifier if nested inside an else' do expect_offense(<<~RUBY) if a blah else foo if b ^^ Convert `if` nested inside `else` to `elsif`. end RUBY expect_correction(<<~RUBY) if a blah elsif b foo end RUBY end end context 'when AllowIfModifier is true' do let(:cop_config) { { 'AllowIfModifier' => true } } it 'accepts a modifier if nested inside an else' do expect_no_offenses(<<~RUBY) if a blah else foo if b end RUBY end end it "isn't offended if there is a statement following the if node" do expect_no_offenses(<<~RUBY) if a blah else if b foo end bar end RUBY end it "isn't offended if there is a statement preceding the if node" do expect_no_offenses(<<~RUBY) if a blah else bar if b foo end end RUBY end it "isn't offended by if..elsif..else" do expect_no_offenses(<<~RUBY) if a blah elsif b blah else blah end RUBY end it 'ignores unless inside else' do expect_no_offenses(<<~RUBY) if a blah else unless b foo end end RUBY end it 'ignores if inside unless' do expect_no_offenses(<<~RUBY) unless a if b foo end end RUBY end it 'ignores nested ternary expressions' do expect_no_offenses('a ? b : c ? d : e') end it 'ignores ternary inside if..else' do expect_no_offenses(<<~RUBY) if a blah else a ? b : c end RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/or_assignment_spec.rb
spec/rubocop/cop/style/or_assignment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::OrAssignment, :config do context 'when using var = var ? var : something' do it 'registers an offense with normal variables' do expect_offense(<<~RUBY) foo = foo ? foo : 'default' ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) foo ||= 'default' RUBY end it 'registers an offense with instance variables' do expect_offense(<<~RUBY) @foo = @foo ? @foo : 'default' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) @foo ||= 'default' RUBY end it 'registers an offense with class variables' do expect_offense(<<~RUBY) @@foo = @@foo ? @@foo : 'default' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) @@foo ||= 'default' RUBY end it 'registers an offense with global variables' do expect_offense(<<~RUBY) $foo = $foo ? $foo : 'default' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) $foo ||= 'default' RUBY end it 'does not register an offense if any of the variables are different' do expect_no_offenses('foo = bar ? foo : 3') expect_no_offenses('foo = foo ? bar : 3') end end context 'when using var = if var; var; else; something; end' do it 'registers an offense with normal variables' do expect_offense(<<~RUBY) foo = if foo ^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. foo else 'default' end RUBY expect_correction(<<~RUBY) foo ||= 'default' RUBY end it 'registers an offense with instance variables' do expect_offense(<<~RUBY) @foo = if @foo ^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. @foo else 'default' end RUBY expect_correction(<<~RUBY) @foo ||= 'default' RUBY end it 'registers an offense with class variables' do expect_offense(<<~RUBY) @@foo = if @@foo ^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. @@foo else 'default' end RUBY expect_correction(<<~RUBY) @@foo ||= 'default' RUBY end it 'registers an offense with global variables' do expect_offense(<<~RUBY) $foo = if $foo ^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. $foo else 'default' end RUBY expect_correction(<<~RUBY) $foo ||= 'default' RUBY end it 'does not register an offense if any of the variables are different' do expect_no_offenses(<<~RUBY) foo = if foo bar else 3 end RUBY expect_no_offenses(<<~RUBY) foo = if bar foo else 3 end RUBY end end context 'when using var = something unless var' do it 'registers an offense for normal variables' do expect_offense(<<~RUBY) foo = 'default' unless foo ^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) foo ||= 'default' RUBY end it 'registers an offense for instance variables' do expect_offense(<<~RUBY) @foo = 'default' unless @foo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) @foo ||= 'default' RUBY end it 'registers an offense for class variables' do expect_offense(<<~RUBY) @@foo = 'default' unless @@foo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) @@foo ||= 'default' RUBY end it 'registers an offense for global variables' do expect_offense(<<~RUBY) $foo = 'default' unless $foo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. RUBY expect_correction(<<~RUBY) $foo ||= 'default' RUBY end it 'does not register an offense if any of the variables are different' do expect_no_offenses('foo = 3 unless bar') expect_no_offenses(<<~RUBY) unless foo bar = 3 end RUBY end end context 'when using unless var; var = something; end' do it 'registers an offense for normal variables' do expect_offense(<<~RUBY) foo = nil unless foo ^^^^^^^^^^ Use the double pipe equals operator `||=` instead. foo = 'default' end RUBY expect_correction(<<~RUBY) foo = nil foo ||= 'default' RUBY end it 'registers an offense for instance variables' do expect_offense(<<~RUBY) @foo = nil unless @foo ^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. @foo = 'default' end RUBY expect_correction(<<~RUBY) @foo = nil @foo ||= 'default' RUBY end it 'registers an offense for class variables' do expect_offense(<<~RUBY) @@foo = nil unless @@foo ^^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. @@foo = 'default' end RUBY expect_correction(<<~RUBY) @@foo = nil @@foo ||= 'default' RUBY end it 'registers an offense for global variables' do expect_offense(<<~RUBY) $foo = nil unless $foo ^^^^^^^^^^^ Use the double pipe equals operator `||=` instead. $foo = 'default' end RUBY expect_correction(<<~RUBY) $foo = nil $foo ||= 'default' RUBY end it 'does not register an offense if any of the variables are different' do expect_no_offenses(<<~RUBY) unless foo bar = 3 end RUBY end end context 'when `then` branch body is empty' do it 'registers an offense' do expect_offense(<<~RUBY) foo = nil if foo ^^^^^^ Use the double pipe equals operator `||=` instead. else foo = 2 end RUBY expect_correction(<<~RUBY) foo = nil foo ||= 2 RUBY end end context 'when using `elsif` statement' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) foo = if foo foo elsif bar else 'default' end RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/trailing_underscore_variable_spec.rb
spec/rubocop/cop/style/trailing_underscore_variable_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::TrailingUnderscoreVariable, :config do shared_examples 'common functionality' do it 'registers an offense when the last variable of parallel assignment is an underscore' do expect_offense(<<~RUBY) a, b, _ = foo() ^^ Do not use trailing `_`s in parallel assignment. Prefer `a, b, = foo()`. RUBY expect_correction(<<~RUBY) a, b, = foo() RUBY end it 'registers an offense when multiple underscores are used as the last variables of parallel assignment' do expect_offense(<<~RUBY) a, _, _ = foo() ^^^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, = foo()`. RUBY expect_correction(<<~RUBY) a, = foo() RUBY end it 'registers an offense for splat underscore as the last variable' do expect_offense(<<~RUBY) a, *_ = foo() ^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, = foo()`. RUBY expect_correction(<<~RUBY) a, = foo() RUBY end it 'registers an offense when underscore is the second to last variable ' \ 'and blank is the last variable' do expect_offense(<<~RUBY) a, _, = foo() ^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, = foo()`. RUBY expect_correction(<<~RUBY) a, = foo() RUBY end it 'registers an offense when underscore is the only variable in parallel assignment' do expect_offense(<<~RUBY) _, = foo() ^^^^^ Do not use trailing `_`s in parallel assignment. Prefer `foo()`. RUBY expect_correction(<<~RUBY) foo() RUBY end it 'registers an offense for an underscore as the last param ' \ 'when there is also an underscore as the first param' do expect_offense(<<~RUBY) _, b, _ = foo() ^^ Do not use trailing `_`s in parallel assignment. Prefer `_, b, = foo()`. RUBY expect_correction(<<~RUBY) _, b, = foo() RUBY end it 'does not register an offense when there are no underscores' do expect_no_offenses('a, b, c = foo()') end it 'does not register an offense for underscores at the beginning' do expect_no_offenses('_, a, b = foo()') end it 'does not register an offense for an underscore preceded by a ' \ 'splat variable anywhere in the argument chain' do expect_no_offenses('*a, b, _ = foo()') end it 'does not register an offense for an underscore preceded by a splat variable' do expect_no_offenses('a, *b, _ = foo()') end it 'does not register an offense for an underscore preceded by a ' \ 'splat variable and another underscore' do expect_no_offenses('_, *b, _ = *foo') end it 'does not register an offense for multiple underscores preceded by a splat variable' do expect_no_offenses('a, *b, _, _ = foo()') end it 'does not register an offense for multiple named underscores preceded by a splat variable' do expect_no_offenses('a, *b, _c, _d = foo()') end it 'registers an offense for multiple underscore variables preceded by ' \ 'a splat underscore variable' do expect_offense(<<~RUBY) a, *_, _, _ = foo() ^^^^^^^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, = foo()`. RUBY expect_correction(<<~RUBY) a, = foo() RUBY end it 'registers an offense for nested assignments with trailing underscores' do expect_offense(<<~RUBY) a, (b, _) = foo() ^^ Do not use trailing `_`s in parallel assignment. Prefer `a, (b,) = foo()`. RUBY expect_correction(<<~RUBY) a, (b,) = foo() RUBY end it 'registers an offense for complex nested assignments with trailing underscores' do expect_offense(<<~RUBY) a, (_, (b, _), *_) = foo() ^^ Do not use trailing `_`s in parallel assignment. Prefer `a, (_, (b,), *_) = foo()`. ^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, (_, (b, _),) = foo()`. RUBY expect_correction(<<~RUBY) a, (_, (b,),) = foo() RUBY end it 'does not register an offense for a named underscore variable ' \ 'preceded by a splat variable' do expect_no_offenses('a, *b, _c = foo()') end it 'does not register an offense for a named variable preceded by a ' \ 'names splat underscore variable' do expect_no_offenses('a, *b, _c = foo()') end it 'does not register an offense for nested assignments without trailing underscores' do expect_no_offenses('a, (_, b) = foo()') end it 'does not register an offense for complex nested assignments without trailing underscores' do expect_no_offenses('a, (_, (b,), c, (d, e),) = foo()') end describe 'autocorrect' do context 'with parentheses' do it 'leaves parentheses but removes trailing underscores' do expect_offense(<<~RUBY) (a, b, _) = foo() ^^ Do not use trailing `_`s in parallel assignment. [...] RUBY expect_correction(<<~RUBY) (a, b,) = foo() RUBY end it 'removes assignment part when every assignment is to `_`' do expect_offense(<<~RUBY) (_, _, _,) = foo() ^^^^^^^^^^^^^ Do not use trailing `_`s in parallel assignment. [...] RUBY expect_correction(<<~RUBY) foo() RUBY end it 'removes assignment part when it is the only variable' do expect_offense(<<~RUBY) (_,) = foo() ^^^^^^^ Do not use trailing `_`s in parallel assignment. [...] RUBY expect_correction(<<~RUBY) foo() RUBY end it 'leaves parentheses but removes trailing underscores and commas' do expect_offense(<<~RUBY) (a, _, _,) = foo() ^^^^^^ Do not use trailing `_`s in parallel assignment. [...] RUBY expect_correction(<<~RUBY) (a,) = foo() RUBY end end end end context 'configured to allow named underscore variables' do let(:config) do RuboCop::Config.new( 'Style/TrailingUnderscoreVariable' => { 'Enabled' => true, 'AllowNamedUnderscoreVariables' => true } ) end it_behaves_like 'common functionality' it 'does not register an offense for named variables that start with an underscore' do expect_no_offenses('a, b, _c = foo()') end it 'does not register an offense for a named splat underscore as the last variable' do expect_no_offenses('a, *_b = foo()') end it 'does not register an offense for an underscore variable preceded ' \ 'by a named splat underscore variable' do expect_no_offenses('a, *_b, _ = foo()') end it 'does not register an offense for multiple underscore variables ' \ 'preceded by a named splat underscore variable' do expect_no_offenses('a, *_b, _, _ = foo()') end end context 'configured to not allow named underscore variables' do let(:config) do RuboCop::Config.new( 'Style/TrailingUnderscoreVariable' => { 'Enabled' => true, 'AllowNamedUnderscoreVariables' => false } ) end it_behaves_like 'common functionality' it 'registers an offense for named variables that start with an underscore' do expect_offense(<<~RUBY) a, b, _c = foo() ^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, b, = foo()`. RUBY expect_correction(<<~RUBY) a, b, = foo() RUBY end it 'registers an offense for a named splat underscore as the last variable' do expect_offense(<<~RUBY) a, *_b = foo() ^^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, = foo()`. RUBY expect_correction(<<~RUBY) a, = foo() RUBY end it 'does not register an offense for a named underscore preceded by a splat variable' do expect_no_offenses('a, *b, _c = foo()') end it 'registers an offense for an underscore variable preceded ' \ 'by a named splat underscore variable' do expect_offense(<<~RUBY) a, *_b, _ = foo() ^^^^^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, = foo()`. RUBY expect_correction(<<~RUBY) a, = foo() RUBY end it 'registers an offense for an underscore preceded by a named splat underscore' do expect_offense(<<~RUBY) a, b, *_c, _ = foo() ^^^^^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, b, = foo()`. RUBY expect_correction(<<~RUBY) a, b, = foo() RUBY end it 'registers an offense for multiple underscore variables ' \ 'preceded by a named splat underscore variable' do expect_offense(<<~RUBY) a, *_b, _, _ = foo() ^^^^^^^^^^ Do not use trailing `_`s in parallel assignment. Prefer `a, = foo()`. RUBY expect_correction(<<~RUBY) a, = foo() RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/style/rescue_modifier_spec.rb
spec/rubocop/cop/style/rescue_modifier_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::RescueModifier, :config do let(:config) { RuboCop::Config.new('Layout/IndentationWidth' => { 'Width' => 2 }) } it 'registers an offense for modifier rescue' do expect_offense(<<~RUBY) method rescue handle ^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. RUBY expect_correction(<<~RUBY) begin method rescue handle end RUBY end it 'registers an offense when using modifier rescue for method call with heredoc argument' do expect_offense(<<~RUBY) method(<<~EOS) rescue handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. str EOS RUBY expect_correction(<<~RUBY) begin method(<<~EOS) str EOS rescue handle end RUBY end it 'registers an offense when using modifier rescue for safe navigation method call with heredoc argument' do expect_offense(<<~RUBY) obj&.method(<<~EOS) rescue handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. str EOS RUBY expect_correction(<<~RUBY) begin obj&.method(<<~EOS) str EOS rescue handle end RUBY end it 'registers an offense when using modifier rescue for method call with heredoc argument and variable' do expect_offense(<<~RUBY) method(<<~EOS, var) rescue handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. str EOS RUBY expect_correction(<<~RUBY) begin method(<<~EOS, var) str EOS rescue handle end RUBY end it 'registers an offense when using modifier rescue for method call with multiple heredoc arguments' do expect_offense(<<~RUBY) method(<<~EOS1, <<~EOS2) rescue handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. str1 EOS1 str2 EOS2 RUBY expect_correction(<<~RUBY) begin method(<<~EOS1, <<~EOS2) str1 EOS1 str2 EOS2 rescue handle end RUBY end it 'registers an offense for modifier rescue around parallel assignment', :ruby26, unsupported_on: :prism do expect_offense(<<~RUBY) a, b = 1, 2 rescue nil ^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. RUBY expect_correction(<<~RUBY) begin a, b = 1, 2 rescue nil end RUBY end it 'registers an offense for modifier rescue around parallel assignment', :ruby27 do expect_offense(<<~RUBY) a, b = 1, 2 rescue nil ^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. RUBY expect_correction(<<~RUBY) a, b = begin [1, 2] rescue nil end RUBY end it 'handles more complex expression with modifier rescue' do expect_offense(<<~RUBY) method1 or method2 rescue handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. RUBY end it 'handles modifier rescue in normal rescue' do expect_offense(<<~RUBY) begin test rescue modifier_handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. rescue normal_handle end RUBY expect_correction(<<~RUBY) begin begin test rescue modifier_handle end rescue normal_handle end RUBY end it 'handles modifier rescue in a method' do expect_offense(<<~RUBY) def a_method test rescue nil ^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. end RUBY expect_correction(<<~RUBY) def a_method begin test rescue nil end end RUBY end it 'handles parentheses around a rescue modifier' do expect_offense(<<~RUBY) (foo rescue nil) ^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. RUBY expect_correction(<<~RUBY) begin foo rescue nil end RUBY end it 'does not register an offense for normal rescue' do expect_no_offenses(<<~RUBY) begin test rescue handle end RUBY end it 'does not register an offense for normal rescue with ensure' do expect_no_offenses(<<~RUBY) begin test rescue handle ensure cleanup end RUBY end it 'does not register an offense for nested normal rescue' do expect_no_offenses(<<~RUBY) begin begin test rescue handle_inner end rescue handle_outer end RUBY end context 'when an instance method has implicit begin' do it 'accepts normal rescue' do expect_no_offenses(<<~RUBY) def some_method test rescue handle end RUBY end it 'handles modifier rescue in body of implicit begin' do expect_offense(<<~RUBY) def some_method test rescue modifier_handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. rescue normal_handle end RUBY end end context 'when a singleton method has implicit begin' do it 'accepts normal rescue' do expect_no_offenses(<<~RUBY) def self.some_method test rescue handle end RUBY end it 'handles modifier rescue in body of implicit begin' do expect_offense(<<~RUBY) def self.some_method test rescue modifier_handle ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. rescue normal_handle end RUBY end end context 'autocorrect' do it 'corrects complex rescue modifier' do expect_offense(<<~RUBY) foo || bar rescue bar ^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. RUBY expect_correction(<<~RUBY) begin foo || bar rescue bar end RUBY end it 'corrects doubled rescue modifiers' do expect_offense(<<~RUBY) blah rescue 1 rescue 2 ^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. ^^^^^^^^^^^^^^^^^^^^^^ Avoid using `rescue` in its modifier form. RUBY expect_correction(<<~RUBY) begin begin blah rescue 1 end rescue 2 end RUBY end end describe 'excluded file', :config do let(:config) do RuboCop::Config.new('Style/RescueModifier' => { 'Enabled' => true, 'Exclude' => ['**/**'] }) end it 'processes excluded files with issue' do expect_no_offenses('foo rescue bar', 'foo.rb') end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false