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/formatter/formatter_set_spec.rb
spec/rubocop/formatter/formatter_set_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Formatter::FormatterSet do subject(:formatter_set) { described_class.new } win_close = lambda do |fset| fset.close_output_files fset.each { |f| f.instance_variable_set :@output, nil } end it 'responds to all formatter API methods' do %i[started file_started file_finished finished].each do |method| expect(formatter_set).to respond_to(method) end end describe 'formatter API method' do let(:files) { ['/path/to/file1', '/path/to/file2'] } it 'invokes the same method of all containing formatters' do formatter_set.add_formatter('simple') formatter_set.add_formatter('emacs') expect(formatter_set[0]).to receive(:started).with(files) expect(formatter_set[1]).to receive(:started).with(files) formatter_set.started(files) end end describe 'add_formatter' do it 'adds a formatter to itself' do formatter_set.add_formatter('simple') expect(formatter_set.size).to eq(1) end it 'adds a formatter with specified formatter type' do formatter_set.add_formatter('simple') expect(formatter_set.first.class).to eq(RuboCop::Formatter::SimpleTextFormatter) end it 'can add multiple formatters by being invoked multiple times' do formatter_set.add_formatter('simple') formatter_set.add_formatter('emacs') expect(formatter_set[0].class).to eq(RuboCop::Formatter::SimpleTextFormatter) expect(formatter_set[1].class).to eq(RuboCop::Formatter::EmacsStyleFormatter) end context 'when output path is omitted' do it 'adds a formatter outputs to $stdout' do formatter_set.add_formatter('simple') expect(formatter_set.first.output).to eq($stdout) end end context 'when output path is specified' do it 'adds a formatter outputs to the specified file' do output_path = Tempfile.new('').path formatter_set.add_formatter('simple', output_path) expect(formatter_set.first.output.class).to eq(File) expect(formatter_set.first.output.path).to eq(output_path) win_close.call(formatter_set) if RuboCop::Platform.windows? end context "when parent directories don't exist" do let(:tmpdir) { Dir.mktmpdir } after { FileUtils.rm_rf(tmpdir) } it 'creates them' do output_path = File.join(tmpdir, 'path/does/not/exist') formatter_set.add_formatter('simple', output_path) expect(formatter_set.first.output.class).to eq(File) expect(formatter_set.first.output.path).to eq(output_path) win_close.call(formatter_set) if RuboCop::Platform.windows? end end end end describe '#close_output_files' do include_context 'mock console output' before do 2.times do output_path = Tempfile.new('').path formatter_set.add_formatter('simple', output_path) end formatter_set.add_formatter('simple') end it 'closes all output files' do formatter_set.close_output_files formatter_set[0..1].each { |formatter| expect(formatter.output).to be_closed } win_close.call(formatter_set) if RuboCop::Platform.windows? end it 'does not close non file output' do expect(formatter_set[2].output).not_to be_closed win_close.call(formatter_set) if RuboCop::Platform.windows? end end describe '#builtin_formatter_class' do def builtin_formatter_class(string) described_class.new.send(:builtin_formatter_class, string) end it 'returns class which matches passed alias name exactly' do expect(builtin_formatter_class('simple')).to eq(RuboCop::Formatter::SimpleTextFormatter) end it 'returns class which matches double character alias name' do expect(builtin_formatter_class('pa')).to eq(RuboCop::Formatter::PacmanFormatter) end it 'returns class which matches single character alias name' do expect(builtin_formatter_class('p')).to eq(RuboCop::Formatter::ProgressFormatter) end end describe '#custom_formatter_class' do def custom_formatter_class(string) described_class.new.send(:custom_formatter_class, string) end it 'returns constant represented by the passed string' do expect(custom_formatter_class('RuboCop')).to eq(RuboCop) end it 'can handle namespaced constant name' do expect(custom_formatter_class('RuboCop::CLI')).to eq(RuboCop::CLI) end it 'can handle top level namespaced constant name' do expect(custom_formatter_class('::RuboCop::CLI')).to eq(RuboCop::CLI) end context 'when non-existent constant name is passed' do it 'raises error' do expect { custom_formatter_class('RuboCop::NonExistentClass') }.to raise_error(NameError) 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/formatter/offense_count_formatter_spec.rb
spec/rubocop/formatter/offense_count_formatter_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Formatter::OffenseCountFormatter do subject(:formatter) { described_class.new(output, options) } let(:output) { StringIO.new } let(:options) { { display_style_guide: false } } let(:files) do %w[lib/rubocop.rb spec/spec_helper.rb exe/rubocop].map do |path| File.expand_path(path) end end let(:finish) { files.each { |file| formatter.file_finished(file, offenses) } } describe '#file_finished' do before { formatter.started(files) } context 'when no offenses are detected' do let(:offenses) { [] } it 'does not add to offense_counts' do expect { finish }.not_to change(formatter, :offense_counts) end end context 'when any offenses are detected' do let(:offenses) { [instance_double(RuboCop::Cop::Offense, cop_name: 'OffendedCop')] } before { offenses.each { |o| allow(o).to receive(:message).and_return('') } } it 'increments the count for the cop in offense_counts' do expect { finish }.to change(formatter, :offense_counts) end end end describe '#report_summary' do context 'when an offense is detected' do let(:cop_counts) { { 'Style/FrozenStringLiteralComment' => 3 } } before { formatter.started(files) } it 'shows the cop and the offense count' do formatter.report_summary(cop_counts, 2) expect(output.string).to eq(<<~OUTPUT) 3 Style/FrozenStringLiteralComment [Unsafe Correctable] -- 3 Total in 2 files OUTPUT end end end describe '#finished' do context 'when there are many offenses' do let(:files) { super().take(1) } let(:offenses) do %w[Style/AndOr Style/HashSyntax Naming/ConstantName Naming/ConstantName].map do |cop| instance_double(RuboCop::Cop::Offense, cop_name: cop) end end before do allow(output).to receive(:tty?).and_return(false) formatter.started(files) offenses.each do |o| allow(o).to receive(:message) .and_return(format('Unwanted. (https://rubystyle.guide#no-good-%s)', o.cop_name)) end finish end context 'when --display-style-guide was not given' do it 'sorts by offense count first and then by cop name' do formatter.finished(files) expect(output.string).to eq(<<~OUTPUT) 2 Naming/ConstantName 1 Style/AndOr [Unsafe Correctable] 1 Style/HashSyntax [Safe Correctable] -- 4 Total in 1 files OUTPUT end end context 'when --display-style-guide was given' do let(:options) { { display_style_guide: true } } it 'shows links and sorts by offense count first and then by cop name' do formatter.finished(files) expect(output.string).to eq(<<~OUTPUT) 2 Naming/ConstantName (https://rubystyle.guide#no-good-Naming/ConstantName) 1 Style/AndOr [Unsafe Correctable] (https://rubystyle.guide#no-good-Style/AndOr) 1 Style/HashSyntax [Safe Correctable] (https://rubystyle.guide#no-good-Style/HashSyntax) -- 4 Total in 1 files OUTPUT end end end context 'when output tty is true' do let(:offenses) do %w[Style/AndOr Style/HashSyntax Naming/ConstantName Naming/ConstantName].map do |cop| instance_double(RuboCop::Cop::Offense, cop_name: cop) end end before do allow(output).to receive(:tty?).and_return(true) offenses.each { |o| allow(o).to receive(:message).and_return('') } formatter.started(files) finish end it 'has a progress bar' do formatter.finished(files) expect(formatter.instance_variable_get(:@progressbar).progress).to eq 3 end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/junit_formatter_spec.rb
spec/rubocop/formatter/junit_formatter_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Formatter::JUnitFormatter, :config do subject(:formatter) { described_class.new(output) } let(:output) { StringIO.new } let(:cop_class) { RuboCop::Cop::Layout::SpaceInsideBlockBraces } let(:source) { %w[foo bar baz].join("\n") } before { cop.send(:begin_investigation, processed_source) } describe '#file_finished' do before do cop.add_offense(Parser::Source::Range.new(source_buffer, 0, 1), message: 'message 1') offenses = cop.add_offense( Parser::Source::Range.new(source_buffer, 9, 10), message: 'message 2' ) formatter.file_finished('test_1', offenses) formatter.file_finished('test_2', offenses) formatter.finished(nil) end it 'displays start of parsable text' do expect(output.string).to start_with(<<~XML) <?xml version='1.0'?> <testsuites> <testsuite name='rubocop' tests='2' failures='4'> XML end it 'displays end of parsable text' do expect(output.string).to end_with(<<~XML) </testsuite> </testsuites> XML end it "displays an offense for `classname='test_1'` in parsable text" do expect(output.string).to include(<<-XML) <testcase classname='test_1' name='Layout/SpaceInsideBlockBraces'> <failure type='Layout/SpaceInsideBlockBraces' message='message 1'> test:1:1 </failure> <failure type='Layout/SpaceInsideBlockBraces' message='message 2'> test:3:2 </failure> </testcase> XML end it "displays an offense for `classname='test_2'` in parsable text" do expect(output.string).to include(<<-XML) <testcase classname='test_2' name='Layout/SpaceInsideBlockBraces'> <failure type='Layout/SpaceInsideBlockBraces' message='message 1'> test:1:1 </failure> <failure type='Layout/SpaceInsideBlockBraces' message='message 2'> test:3:2 </failure> </testcase> XML end it 'displays a non-offense element in parsable text' do expect(output.string).to include(<<~XML) <testcase classname='test_1' name='Style/Alias'/> XML end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/clang_style_formatter_spec.rb
spec/rubocop/formatter/clang_style_formatter_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Formatter::ClangStyleFormatter, :config do subject(:formatter) { described_class.new(output) } let(:cop_class) { RuboCop::Cop::Base } let(:output) { StringIO.new } before { cop.send(:begin_investigation, processed_source) } describe '#report_file' do let(:file) { '/path/to/file' } let(:offense) do RuboCop::Cop::Offense.new(:convention, range, 'This is a message.', 'CopName', status) end let(:source) { ('aa'..'az').to_a.join($RS) } let(:range) { source_range(0...1) } it 'displays text containing the offending source line' do cop.add_offense(Parser::Source::Range.new(source_buffer, 0, 2), message: 'message 1') offenses = cop.add_offense( Parser::Source::Range.new(source_buffer, 30, 32), message: 'message 2' ) formatter.report_file('test', offenses) expect(output.string).to eq <<~OUTPUT test:1:1: C: message 1 aa ^^ test:11:1: C: message 2 ak ^^ OUTPUT end context 'when the source line is blank' do let(:source) { [' ', 'yaba'].join($RS) } it 'does not display offending source line' do cop.add_offense(Parser::Source::Range.new(source_buffer, 0, 2), message: 'message 1') offenses = cop.add_offense( Parser::Source::Range.new(source_buffer, 6, 10), message: 'message 2' ) formatter.report_file('test', offenses) expect(output.string).to eq <<~OUTPUT test:1:1: C: message 1 test:2:1: C: message 2 yaba ^^^^ OUTPUT end end context 'when the offending source spans multiple lines' do let(:source) do <<~RUBY do_something([this, is, target]) RUBY end it 'displays the first line with ellipses' do range = source_range(source.index('[')..source.index(']')) offenses = cop.add_offense(range, message: 'message 1') formatter.report_file('test', offenses) expect(output.string) .to eq <<~OUTPUT test:1:14: C: message 1 do_something([this, #{described_class::ELLIPSES} ^^^^^^ OUTPUT end end context 'when the offense is not corrected' do let(:status) { :unsupported } it 'prints message as-is' do formatter.report_file(file, [offense]) expect(output.string).to include(': This is a message.') end end context 'when the offense is correctable' do let(:status) { :uncorrected } it 'prints message as-is' do formatter.report_file(file, [offense]) expect(output.string).to include(': [Correctable] This is a message.') end end context 'when the offense is automatically corrected' do let(:status) { :corrected } it 'prints [Corrected] along with message' do formatter.report_file(file, [offense]) expect(output.string).to include(': [Corrected] This is a message.') end end context 'when the source contains multibyte characters' do let(:source) do <<~RUBY do_something("あああ", ["いいい"]) RUBY end it 'displays text containing the offending source line' do range = source_range(source.index('[')..source.index(']')) offenses = cop.add_offense(range, message: 'message 1') formatter.report_file('test', offenses) expect(output.string) .to eq <<~OUTPUT test:1:21: C: message 1 do_something("あああ", ["いいい"]) ^^^^^^^^^^ OUTPUT 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/formatter/markdown_formatter_spec.rb
spec/rubocop/formatter/markdown_formatter_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Formatter::MarkdownFormatter, :isolated_environment do spec_root = File.expand_path('../..', __dir__) around do |example| project_path = File.join(spec_root, 'fixtures/markdown_formatter/project') FileUtils.cp_r(project_path, '.') Dir.chdir(File.basename(project_path)) { example.run } end # Run without Style/EndOfLine as it gives different results on # different platforms. # Metrics/AbcSize is very strict, exclude it too let(:options) { %w[--except Layout/EndOfLine,Metrics/AbcSize --format markdown --out] } let(:actual_markdown_path) do path = File.expand_path('result.md') RuboCop::CLI.new.run([*options, path]) path end let(:actual_markdown_path_cached) do path = File.expand_path('result_cached.md') 2.times { RuboCop::CLI.new.run([*options, path]) } path end let(:actual_markdown) { File.read(actual_markdown_path, encoding: Encoding::UTF_8) } let(:actual_markdown_cached) { File.read(actual_markdown_path_cached, encoding: Encoding::UTF_8) } let(:expected_markdown_path) { File.join(spec_root, 'fixtures/markdown_formatter/expected.md') } let(:expected_markdown) do markdown = File.read(expected_markdown_path, encoding: Encoding::UTF_8) # Avoid failure on version bump markdown.sub(/(class="version".{0,20})\d+(?:\.\d+){2}/i) do Regexp.last_match(1) + RuboCop::Version::STRING end end it 'outputs the result in Markdown' do expect(actual_markdown).to eq(expected_markdown) end it 'outputs the cached result in Markdown' do expect(actual_markdown_cached).to eq(expected_markdown) end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/progress_formatter_spec.rb
spec/rubocop/formatter/progress_formatter_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Formatter::ProgressFormatter do subject(:formatter) { described_class.new(output) } let(:output) { StringIO.new } let(:files) do %w[lib/rubocop.rb spec/spec_helper.rb exe/rubocop].map do |path| File.expand_path(path) end end describe '#file_finished' do before do formatter.started(files) formatter.file_started(files.first, {}) end shared_examples 'calls #report_file_as_mark' do it 'calls #report_as_with_mark' do expect(formatter).to receive(:report_file_as_mark) formatter.file_finished(files.first, offenses) end end context 'when no offenses are detected' do let(:offenses) { [] } it_behaves_like 'calls #report_file_as_mark' end context 'when any offenses are detected' do let(:offenses) { [instance_double(RuboCop::Cop::Offense).as_null_object] } it_behaves_like 'calls #report_file_as_mark' end end describe '#report_file_as_mark' do before { formatter.report_file_as_mark(offenses) } def offense_with_severity(severity) source_buffer = Parser::Source::Buffer.new('test', 1) source_buffer.source = "a\n" RuboCop::Cop::Offense.new(severity, Parser::Source::Range.new(source_buffer, 0, 1), 'message', 'CopName') end context 'when no offenses are detected' do let(:offenses) { [] } it 'prints "."' do expect(output.string).to eq('.') end end context 'when a refactor severity offense is detected' do let(:offenses) { [offense_with_severity(:refactor)] } it 'prints "R"' do expect(output.string).to eq('R') end end context 'when a refactor convention offense is detected' do let(:offenses) { [offense_with_severity(:convention)] } it 'prints "C"' do expect(output.string).to eq('C') end end context 'when different severity offenses are detected' do let(:offenses) { [offense_with_severity(:refactor), offense_with_severity(:error)] } it 'prints highest level mark' do expect(output.string).to eq('E') end end end describe '#finished' do before { formatter.started(files) } context 'when any offenses are detected' do before do source_buffer = Parser::Source::Buffer.new('test', 1) source = Array.new(9) { |index| "This is line #{index + 1}." } source_buffer.source = source.join("\n") line_length = source[0].length + 1 formatter.file_started(files[0], {}) formatter.file_finished( files[0], [ RuboCop::Cop::Offense.new( :convention, Parser::Source::Range.new(source_buffer, line_length + 2, line_length + 3), 'foo', 'Cop' ) ] ) formatter.file_started(files[1], {}) formatter.file_finished(files[1], []) formatter.file_started(files[2], {}) formatter.file_finished( files[2], [ RuboCop::Cop::Offense.new( :error, Parser::Source::Range.new(source_buffer, (line_length * 4) + 1, (line_length * 4) + 2), 'bar', 'Cop' ), RuboCop::Cop::Offense.new( :convention, Parser::Source::Range.new(source_buffer, line_length * 5, (line_length * 5) + 1), 'foo', 'Cop' ) ] ) end it 'reports all detected offenses for all failed files' do formatter.finished(files) expect(output.string).to include(<<~OUTPUT) Offenses: lib/rubocop.rb:2:3: C: [Correctable] foo This is line 2. ^ exe/rubocop:5:2: E: [Correctable] bar This is line 5. ^ exe/rubocop:6:1: C: [Correctable] foo This is line 6. ^ OUTPUT end end context 'when no offenses are detected' do before do files.each do |file| formatter.file_started(file, {}) formatter.file_finished(file, []) end end it 'does not report offenses' do formatter.finished(files) expect(output.string).not_to include('Offenses:') end end it 'calls #report_summary' do expect(formatter).to receive(:report_summary) formatter.finished(files) end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/formatter/github_actions_formatter_spec.rb
spec/rubocop/formatter/github_actions_formatter_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Formatter::GitHubActionsFormatter, :config do subject(:formatter) { described_class.new(output, formatter_options) } let(:formatter_options) { {} } let(:cop_class) { RuboCop::Cop::Base } let(:output) { StringIO.new } describe '#finished' do let(:file) { '/path/to/file' } let(:message) { 'This is a message.' } let(:status) { :uncorrected } let(:offense) do RuboCop::Cop::Offense.new(:convention, location, message, 'CopName', status) end let(:offenses) { [offense] } let(:source) { ('aa'..'az').to_a.join($RS) } let(:location) { source_range(0...1) } before do formatter.started([file]) formatter.file_finished(file, offenses) formatter.finished([file]) end context 'when offenses are detected' do it 'reports offenses as errors' do expect(output.string).to include("::error file=#{file},line=1,col=1::This is a message.") end end context 'when file is relative to the current directory' do let(:file) { "#{Dir.pwd}/path/to/file" } it 'reports offenses as error with the relative path' do expect(output.string) .to include('::error file=path/to/file,line=1,col=1::This is a message.') end end context 'when no offenses are detected' do let(:offenses) { [] } it 'does not print anything' do expect(output.string).to eq "\n" end end context 'when message contains %' do let(:message) { "All occurrences of %, \r and \n must be escaped" } it 'escapes message' do expect(output.string).to include('::All occurrences of %25, %0D and %0A must be escaped') end end context 'when fail level is defined' do let(:formatter_options) { { fail_level: 'convention' } } let(:offenses) do [ offense, RuboCop::Cop::Offense.new( :refactor, source_range(2...4), 'This is a warning.', 'CopName', status ) ] end it 'reports offenses above or at fail level as errors' do expect(output.string).to include("::error file=#{file},line=1,col=1::This is a message.") end it 'reports offenses below fail level as warnings' do expect(output.string).to include("::warning file=#{file},line=1,col=3::This is a warning.") 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/config_obsoletion/renamed_cop_spec.rb
spec/rubocop/config_obsoletion/renamed_cop_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::ConfigObsoletion::RenamedCop do subject(:rule) { described_class.new(config, old_name, new_name) } let(:config) { instance_double(RuboCop::Config, loaded_path: '.rubocop.yml').as_null_object } let(:old_name) { 'Style/MyCop' } describe '#message' do subject { rule.message } context 'when the cop has changed names but in the same department' do let(:new_name) { 'Style/NewCop' } it { is_expected.to start_with('The `Style/MyCop` cop has been renamed to `Style/NewCop`') } end context 'when the cop has changed names but in a new department' do let(:new_name) { 'Layout/NewCop' } it { is_expected.to start_with('The `Style/MyCop` cop has been renamed to `Layout/NewCop`') } end context 'when the cop has been moved to a new department' do let(:new_name) { 'Layout/MyCop' } it { is_expected.to start_with('The `Style/MyCop` cop has been moved to `Layout/MyCop`') } end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/ext/regexp_node_spec.rb
spec/rubocop/ext/regexp_node_spec.rb
# frozen_string_literal: true require 'timeout' RSpec.describe RuboCop::Ext::RegexpNode do let(:source) { '/(hello)(?<foo>world)(?:not captured)/' } let(:processed_source) { parse_source(source) } let(:ast) { processed_source.ast } let(:node) { ast } describe '#each_capture' do subject(:captures) { node.each_capture(**arg).to_a } let(:named) { be_instance_of(Regexp::Expression::Group::Named) } let(:positional) { be_instance_of(Regexp::Expression::Group::Capture) } context 'when called without argument' do let(:arg) { {} } it { is_expected.to match [positional, named] } end context 'when called with a `named: false`' do let(:arg) { { named: false } } it { is_expected.to match [positional] } end context 'when called with a `named: true`' do let(:arg) { { named: true } } it { is_expected.to match [named] } end end describe '#parsed_tree' do let(:source) { '/foo#{bar}baz/' } context 'with an extended mode regexp with comment' do let(:source) { '/42 # the answer/x' } it 'returns the expected tree' do tree = node.parsed_tree expect(tree).to be_a(Regexp::Expression::Root) expect(tree.map(&:token)).to eq(%i[literal whitespace comment]) end end context 'with a regexp containing interpolation' do it 'returns the expected blanked tree' do tree = node.parsed_tree expect(tree).to be_a(Regexp::Expression::Root) expect(tree.to_s).to eq('foo baz') end end context 'with a regexp containing a multi-line interpolation' do let(:source) do <<~'REGEXP' / foo #{ bar( 42 ) } baz / REGEXP end it 'returns the expected blanked tree' do tree = node.parsed_tree expect(tree).to be_a(Regexp::Expression::Root) expect(tree.to_s.split("\n")).to eq(['', ' foo', ' ' * 32, ' baz']) end end context 'with a regexp not containing interpolation' do let(:source) { '/foobaz/' } it 'returns the expected tree' do tree = node.parsed_tree expect(tree).to be_a(Regexp::Expression::Root) expect(tree.to_s).to eq('foobaz') end end context 'with a regexp with subexpressions' do let(:source) { '/([a-z]+)\d*\s?(?:foo)/' } it 'has location information' do nodes = node.parsed_tree.each_expression.map { |exp, _index| exp } # `Parser::Source::Map` does not have `source_range` method. # rubocop:disable InternalAffairs/LocationExpression sources = nodes.map { |n| n.loc.expression.source } # rubocop:enable InternalAffairs/LocationExpression expect(sources).to eq %w{([a-z]+) [a-z]+ a-z a z \d* \s? (?:foo) foo} loc = nodes[1].loc delim = loc.begin, loc.body, loc.end, loc.quantifier expect(delim.map(&:source)).to eq %w{[ [a-z] ] +} end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/variable_force_spec.rb
spec/rubocop/cop/variable_force_spec.rb
# frozen_string_literal: true require 'rubocop/ast/sexp' RSpec.describe RuboCop::Cop::VariableForce do include RuboCop::AST::Sexp subject(:force) { described_class.new([]) } describe '#process_node' do before { force.variable_table.push_scope(s(:def)) } context 'when processing lvar node' do let(:node) { s(:lvar, :foo) } context 'when the variable is not yet declared' do it 'does not raise error' do expect { force.process_node(node) }.not_to raise_error end end end context 'when processing an empty regex' do let(:node) { parse_source('// =~ ""').ast } it 'does not raise an error' do expect { force.process_node(node) }.not_to raise_error end end context 'when processing a regex with regopt' do let(:node) { parse_source('/\x82/n =~ "a"').ast } it 'does not raise an error' do expect { force.process_node(node) }.not_to raise_error end end context 'when processing a regexp with a line break at the start of capture parenthesis' do let(:node) do parse_source(<<~REGEXP).ast /( pattern )/ =~ string REGEXP end it 'does not raise an error' do expect { force.process_node(node) }.not_to raise_error 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/badge_spec.rb
spec/rubocop/cop/badge_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Badge do subject(:badge) { described_class.new(%w[Test ModuleMustBeAClassCop]) } it 'exposes department name' do expect(badge.department).to be(:Test) end it 'exposes cop name' do expect(badge.cop_name).to eql('ModuleMustBeAClassCop') end describe '.new' do shared_examples 'assignment of department and name' do |class_name_parts, department, name| it 'assigns department' do expect(described_class.new(class_name_parts).department).to eq(department) end it 'assigns name' do expect(described_class.new(class_name_parts).cop_name).to eq(name) end end it_behaves_like 'assignment of department and name', %w[Foo], nil, 'Foo' it_behaves_like 'assignment of department and name', %w[Foo Bar], :Foo, 'Bar' it_behaves_like 'assignment of department and name', %w[Foo Bar Baz], :'Foo/Bar', 'Baz' it_behaves_like 'assignment of department and name', %w[Foo Bar Baz Qux], :'Foo/Bar/Baz', 'Qux' end describe '.parse' do shared_examples 'cop identifier parsing' do |identifier, class_name_parts| it 'parses identifier' do expect(described_class.parse(identifier)).to eq(described_class.new(class_name_parts)) end end it_behaves_like 'cop identifier parsing', 'bar', %w[Bar] it_behaves_like 'cop identifier parsing', 'Bar', %w[Bar] it_behaves_like 'cop identifier parsing', 'snake_case/example', %w[SnakeCase Example] it_behaves_like 'cop identifier parsing', 'Foo/Bar', %w[Foo Bar] it_behaves_like 'cop identifier parsing', 'Foo/Bar/Baz', %w[Foo Bar Baz] it_behaves_like 'cop identifier parsing', 'Foo/Bar/Baz/Qux', %w[Foo Bar Baz Qux] end describe '.for' do shared_examples 'cop class name parsing' do |class_name, class_name_parts| it 'parses cop class name' do expect(described_class.for(class_name)).to eq(described_class.new(class_name_parts)) end end it_behaves_like 'cop class name parsing', 'Foo', %w[Foo] it_behaves_like 'cop class name parsing', 'Foo::Bar', %w[Foo Bar] it_behaves_like 'cop class name parsing', 'RuboCop::Cop::Foo', %w[Cop Foo] it_behaves_like 'cop class name parsing', 'RuboCop::Cop::Foo::Bar', %w[Foo Bar] it_behaves_like 'cop class name parsing', 'RuboCop::Cop::Foo::Bar::Baz', %w[Foo Bar Baz] end it 'compares by value' do badge1 = described_class.new(%w[Foo Bar]) badge2 = described_class.new(%w[Foo Bar]) expect(Set.new([badge1, badge2])).to be_one end it 'can be converted to a string with the Department/CopName format' do expect(described_class.new(%w[Foo Bar]).to_s).to eql('Foo/Bar') end describe '#qualified?' do it 'says `CopName` is not qualified' do expect(described_class.parse('Bar')).not_to be_qualified end it 'says `Department/CopName` is qualified' do expect(described_class.parse('Department/Bar')).to be_qualified end it 'says `Deep/Department/CopName` is qualified' do expect(described_class.parse('Deep/Department/Bar')).to be_qualified end end describe '#camel_case' do it 'converts "lint" to CamelCase' do expect(described_class.camel_case('lint')).to eq('Lint') end it 'converts "foo_bar" to CamelCase' do expect(described_class.camel_case('foo_bar')).to eq('FooBar') end it 'converts "rspec" to CamelCase' do expect(described_class.camel_case('rspec')).to eq('RSpec') end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/commissioner_spec.rb
spec/rubocop/cop/commissioner_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Commissioner do describe '#investigate' do subject(:offenses) { report.offenses } let(:report) { commissioner.investigate(processed_source) } let(:cop_class) do stub_const('Fake::FakeCop', Class.new(RuboCop::Cop::Base) do def on_int(node); end alias_method :on_def, :on_int alias_method :on_send, :on_int alias_method :on_csend, :on_int alias_method :after_int, :on_int alias_method :after_def, :on_int alias_method :after_send, :on_int alias_method :after_csend, :on_int end) end let(:cop) do cop_class.new.tap do |c| allow(c).to receive(:complete_investigation).and_return(cop_report) end end let(:cops) { [cop] } let(:options) { {} } let(:forces) { [] } let(:commissioner) { described_class.new(cops, forces, **options) } let(:errors) { commissioner.errors } let(:source) { <<~RUBY } def method 1 end RUBY let(:processed_source) { parse_source(source, 'file.rb') } let(:cop_offenses) { [] } let(:cop_report) do RuboCop::Cop::Base::InvestigationReport.new(nil, processed_source, cop_offenses, nil) end around { |example| RuboCop::Cop::Registry.with_temporary_global { example.run } } context 'when a cop reports offenses' do let(:cop_offenses) { [Object.new] } it 'returns all offenses found by the cops' do expect(offenses).to eq cop_offenses end end it 'traverses the AST and invoke cops specific callbacks' do expect(cop).to receive(:on_def).once expect(cop).to receive(:on_int).once expect(cop).not_to receive(:after_int) expect(cop).to receive(:after_def).once offenses end context 'traverses the AST with on_send / on_csend' do let(:source) { 'foo; var = bar; var&.baz' } context 'for unrestricted cops' do it 'calls on_send all method calls' do expect(cop).to receive(:on_send).twice expect(cop).to receive(:on_csend).once offenses end end context 'for a restricted cop' do before { stub_const("#{cop_class}::RESTRICT_ON_SEND", restrictions) } let(:restrictions) { [:bar] } it 'calls on_send for the right method calls' do expect(cop).to receive(:on_send).once expect(cop).to receive(:after_send).once expect(cop).not_to receive(:on_csend) expect(cop).not_to receive(:after_csend) offenses end context 'on both csend and send' do let(:restrictions) { %i[bar baz] } it 'calls on_send for the right method calls' do expect(cop).to receive(:on_send).once expect(cop).to receive(:on_csend).once expect(cop).to receive(:after_send).once expect(cop).to receive(:after_csend).once offenses end end end end it 'stores all errors raised by the cops' do allow(cop).to receive(:on_int) { raise RuntimeError } expect(offenses).to eq [] expect(errors.size).to eq(1) expect(errors[0].cause).to be_an_instance_of(RuntimeError) expect(errors[0].line).to eq 2 expect(errors[0].column).to eq 0 end context 'when passed :raise_error option' do let(:options) { { raise_error: true } } it 're-raises the exception received while processing' do allow(cop).to receive(:on_int) { raise RuntimeError } expect { offenses }.to raise_error(RuntimeError) end end context 'when passed :raise_cop_error option' do let(:options) { { raise_cop_error: true } } it 're-raises the exception received while processing' do allow(cop).to receive(:on_int) { raise RuboCop::ErrorWithAnalyzedFileLocation } expect { offenses }.to raise_error(RuboCop::ErrorWithAnalyzedFileLocation) end end context 'when given a force' do let(:force) { instance_double(RuboCop::Cop::Force).as_null_object } let(:forces) { [force] } it 'passes the input params to all cops/forces that implement their own ' \ '#investigate method' do expect(cop).to receive(:on_new_investigation).with(no_args) expect(force).to receive(:investigate).with(processed_source) offenses end end context 'when given a source with parsing errors' do let(:source) { '(' } it 'only calls on_other_file' do expect(cop).not_to receive(:on_new_investigation) expect(cop).to receive(:on_other_file) offenses 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/team_spec.rb
spec/rubocop/cop/team_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Team do subject(:team) { described_class.mobilize(cop_classes, config, options) } let(:cop_classes) { RuboCop::Cop::Registry.global } let(:config) { RuboCop::ConfigLoader.default_configuration } let(:options) { {} } let(:ruby_version) { RuboCop::TargetRuby.supported_versions.last } before { RuboCop::ConfigLoader.default_configuration = nil } context 'when incompatible cops are correcting together' do include FileHelper let(:options) { { formatters: [], autocorrect: true } } let(:runner) { RuboCop::Runner.new(options, RuboCop::ConfigStore.new) } let(:file_path) { 'example.rb' } it 'autocorrects without SyntaxError', :isolated_environment do source = <<~'RUBY' foo.map{ |a| a.nil? } puts 'foo' + 'bar' + "#{baz}" i+1 def a self::b end RUBY corrected = <<~'RUBY' # frozen_string_literal: true foo.map(&:nil?) puts 'foo' \ 'bar' \ "#{baz}" i def a b end RUBY create_file(file_path, source) runner.run([]) expect(File.read(file_path)).to eq(corrected) end end describe '#autocorrect?' do subject { team.autocorrect? } context 'when the option argument of .mobilize is omitted' do subject { described_class.mobilize(cop_classes, config).autocorrect? } it { is_expected.to be_nil } end context 'when { autocorrect: true } is passed to .mobilize' do let(:options) { { autocorrect: true } } it { is_expected.to be(true) } end end describe '#debug?' do subject { team.debug? } context 'when the option argument of .mobilize is omitted' do subject { described_class.mobilize(cop_classes, config).debug? } it { is_expected.to be_nil } end context 'when { debug: true } is passed to .mobilize' do let(:options) { { debug: true } } it { is_expected.to be(true) } end end describe '#inspect_file', :isolated_environment do include FileHelper let(:file_path) { 'example.rb' } let(:source) do source = RuboCop::ProcessedSource.from_file( file_path, ruby_version, parser_engine: parser_engine ) source.config = config source.registry = RuboCop::Cop::Registry.new(cop_classes.cops) source end let(:offenses) { team.inspect_file(source) } before { create_file(file_path, ['#' * 90, 'puts test;']) } it 'returns offenses' do expect(offenses).not_to be_empty expect(offenses).to all(be_a(RuboCop::Cop::Offense)) end context 'when Parser reports non-fatal warning for the file' do before { create_file(file_path, ['#' * 130, 'puts *test']) } let(:cop_names) { offenses.map(&:cop_name) } it 'returns Parser warning offenses' do expect(cop_names).to include('Lint/AmbiguousOperator') end it 'returns offenses from cops' do expect(cop_names).to include('Layout/LineLength') end context 'when a cop has no interest in the file' do it 'returns all offenses except the ones of the cop' do allow_any_instance_of(RuboCop::Cop::Layout::LineLength) .to receive(:excluded_file?).and_return(true) expect(cop_names).to include('Lint/AmbiguousOperator') expect(cop_names).not_to include('Layout/LineLength') end end end context 'when autocorrection is enabled' do let(:options) { { autocorrect: true } } before { create_file(file_path, 'puts "string"') } it 'does autocorrection' do team.inspect_file(source) corrected_source = File.read(file_path) expect(corrected_source).to eq(<<~RUBY) # frozen_string_literal: true puts 'string' RUBY end it 'still returns offenses' do expect(offenses[1].cop_name).to eq('Style/StringLiterals') end end context 'when autocorrection is enabled and file encoding is mismatch' do let(:options) { { autocorrect: true } } before do create_file(file_path, <<~RUBY) # encoding: Shift_JIS puts 'οΌ΄ο½ˆο½‰ο½“ ο½†ο½‰ο½Œο½… ο½…ο½Žο½ƒο½ο½„ο½‰ο½Žο½‡ is ATF-8.' RUBY end it 'no error occurs' do team.inspect_file(source) expect(team.errors).to be_empty end end context 'when Cop#on_* raises an error' do include_context 'mock console output' before do allow_any_instance_of(RuboCop::Cop::Style::NumericLiterals) .to receive(:on_int).and_raise(StandardError) create_file(file_path, '10_00_000') end let(:error_message) do 'An error occurred while Style/NumericLiterals cop was inspecting ' \ 'example.rb:1:0.' end it 'records Team#errors' do team.inspect_file(source) expect(team.errors).to eq([error_message]) expect($stderr.string).to include(error_message) end end context "when a cop's joining forces callback raises an error" do include_context 'mock console output' before do allow_any_instance_of(RuboCop::Cop::Lint::ShadowedArgument) .to receive(:after_leaving_scope).and_raise(exception_message) create_file(file_path, 'foo { |bar| bar = 42 }') end let(:options) { { debug: true } } let(:exception_message) { 'my message' } let(:error_message) do 'An error occurred while Lint/ShadowedArgument cop was inspecting example.rb.' end it 'records Team#errors' do team.inspect_file(source) expect(team.errors).to eq([error_message]) expect($stderr.string).to include(error_message) expect($stdout.string).to include(exception_message) end end context 'when a correction raises an error' do include_context 'mock console output' before do allow(RuboCop::Cop::OrderedGemCorrector).to receive(:correct).and_return(buggy_correction) create_file(file_path, <<~RUBY) gem 'rubocop' gem 'rspec' RUBY end let(:file_path) { 'Gemfile' } let(:buggy_correction) { ->(_corrector) { raise cause } } let(:options) { { autocorrect: true } } let(:cause) { StandardError.new('cause') } let(:error_message) do 'An error occurred while Bundler/OrderedGems cop was inspecting ' \ 'Gemfile.' end it 'records Team#errors' do team.inspect_file(source) expect($stderr.string).to include(error_message) end end context 'when done twice', :restore_registry do let(:persisting_cop_class) do stub_cop_class('Test::Persisting') do def self.support_multiple_source? true end end end let(:cop_classes) { RuboCop::Cop::Registry.new([persisting_cop_class, RuboCop::Cop::Base]) } it 'allows cops to get ready' do before = team.cops.dup team.inspect_file(source) team.inspect_file(source) expect(team.cops).to contain_exactly(be(before.first), be_a(RuboCop::Cop::Base)) expect(team.cops.last).not_to be(before.last) end end end describe '#cops' do subject(:cops) { team.cops } it 'returns cop instances' do expect(cops).not_to be_empty expect(cops).to be_all(RuboCop::Cop::Base) end context 'when only some cop classes are passed to .new' do let(:cop_classes) do RuboCop::Cop::Registry.new([RuboCop::Cop::Lint::Void, RuboCop::Cop::Layout::LineLength]) end it 'returns only instances of the classes' do expect(cops.size).to eq(2) cops.sort_by!(&:name) expect(cops[0].name).to eq('Layout/LineLength') expect(cops[1].name).to eq('Lint/Void') end end end describe '#forces' do subject(:forces) { team.forces } let(:cop_classes) { RuboCop::Cop::Registry.global } it 'returns force instances' do expect(forces).not_to be_empty expect(forces).to all(be_a(RuboCop::Cop::Force)) end context 'when a cop joined a force' do let(:cop_classes) { RuboCop::Cop::Registry.new([RuboCop::Cop::Lint::UselessAssignment]) } it 'returns the force' do expect(forces.size).to eq(1) expect(forces.first).to be_a(RuboCop::Cop::VariableForce) end end context 'when multiple cops joined a same force' do let(:cop_classes) do RuboCop::Cop::Registry.new( [ RuboCop::Cop::Lint::UselessAssignment, RuboCop::Cop::Lint::ShadowingOuterLocalVariable ] ) end it 'returns only one force instance' do expect(forces.size).to eq(1) end end context 'when no cops joined force' do let(:cop_classes) { RuboCop::Cop::Registry.new([RuboCop::Cop::Style::For]) } it 'returns nothing' do expect(forces).to be_empty end end end describe '#external_dependency_checksum' do let(:cop_classes) { RuboCop::Cop::Registry.new } it 'does not error with no cops' do expect(team.external_dependency_checksum).to be_a(String) end context 'when a cop joins' do let(:cop_classes) { RuboCop::Cop::Registry.new([RuboCop::Cop::Lint::UselessAssignment]) } it 'returns string' do expect(team.external_dependency_checksum).to be_a(String) end end context 'when multiple cops join' do let(:cop_classes) do RuboCop::Cop::Registry.new( [ RuboCop::Cop::Lint::UselessAssignment, RuboCop::Cop::Lint::ShadowingOuterLocalVariable ] ) end it 'returns string' do expect(team.external_dependency_checksum).to be_a(String) end end context 'when cop with different checksum joins', :restore_registry do before do stub_cop_class('Test::CopWithExternalDeps') do def external_dependency_checksum 'something other than nil' end end end let(:new_cop_classes) do RuboCop::Cop::Registry.new( [ Test::CopWithExternalDeps, RuboCop::Cop::Lint::UselessAssignment, RuboCop::Cop::Lint::ShadowingOuterLocalVariable ] ) end it 'has a different checksum for the whole team' do original_checksum = team.external_dependency_checksum new_team = described_class.mobilize(new_cop_classes, config, options) new_checksum = new_team.external_dependency_checksum expect(original_checksum).not_to eq(new_checksum) end end end describe '.new' do it 'calls mobilize when passed classes' do expect(described_class).to receive(:mobilize).with(cop_classes, config, options) expect do described_class.new(cop_classes, config, options) end.to output(/Use `Team.mobilize` instead/).to_stderr end it 'accepts cops directly classes' do cop = RuboCop::Cop::Metrics::AbcSize.new team = described_class.new([cop], config, options) expect(team.cops.first).to equal(cop) end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/visibility_help_spec.rb
spec/rubocop/cop/visibility_help_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::VisibilityHelp do describe '#node_visibility' do subject do instance.__send__(:node_visibility, node) end let(:instance) do klass.new end let(:klass) do mod = described_class Class.new do include mod end end let(:node) do processed_source.ast.each_node(:def).first end let(:processed_source) do parse_source(source) end context 'without visibility block' do let(:source) do <<~RUBY class A def x; end end RUBY end it { is_expected.to eq(:public) } end context 'with visibility block public' do let(:source) do <<~RUBY class A public def x; end end RUBY end it { is_expected.to eq(:public) } end context 'with visibility block private' do let(:source) do <<~RUBY class A private def x; end end RUBY end it { is_expected.to eq(:private) } end context 'with visibility block private after public' do let(:source) do <<~RUBY class A public private def x; end end RUBY end it { is_expected.to eq(:private) } end context 'with inline public' do let(:source) do <<~RUBY class A public def x; end end RUBY end it { is_expected.to eq(:public) } end context 'with inline private' do let(:source) do <<~RUBY class A private def x; end end RUBY end it { is_expected.to eq(:private) } end context 'with inline private with symbol' do let(:source) do <<~RUBY class A def x; end private :x end RUBY end it { is_expected.to eq(:private) } end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/message_annotator_spec.rb
spec/rubocop/cop/message_annotator_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::MessageAnnotator do let(:options) { {} } let(:config) { RuboCop::Config.new({}) } let(:cop_name) { 'Cop/Cop' } let(:annotator) { described_class.new(config, cop_name, config[cop_name], options) } describe '#annotate' do subject(:annotate) { annotator.annotate('message') } context 'with default options' do it 'returns the message' do expect(annotate).to eq('message') end end context 'when the output format is JSON' do let(:options) { { format: 'json' } } it 'returns the message unannotated' do expect(annotate).to eq('message') end end context 'with options on' do let(:options) do { extra_details: true, display_cop_names: true, display_style_guide: true } end let(:config) do RuboCop::Config.new( 'Cop/Cop' => { 'Details' => 'my cop details', 'StyleGuide' => 'http://example.org/styleguide' } ) end it 'returns an annotated message' do expect(annotate).to eq('Cop/Cop: message my cop details (http://example.org/styleguide)') end end end describe 'with style guide url' do subject(:annotate) { annotator.annotate('') } let(:cop_name) { 'Cop/Cop' } let(:options) { { display_style_guide: true } } context 'when StyleGuide is not set in the config' do let(:config) { RuboCop::Config.new({}) } it 'does not add style guide url' do expect(annotate).to eq('') end end context 'when StyleGuide is set in the config' do let(:config) do RuboCop::Config.new('Cop/Cop' => { 'StyleGuide' => 'http://example.org/styleguide' }) end it 'adds style guide url' do expect(annotate).to include('http://example.org/styleguide') end end context 'when a base URL is specified' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'StyleGuideBaseURL' => 'http://example.org/styleguide' } ) end it 'does not specify a URL if a cop does not have one' do config['Cop/Cop'] = { 'StyleGuide' => nil } expect(annotate).to eq('') end it 'combines correctly with a target-based setting' do config['Cop/Cop'] = { 'StyleGuide' => '#target_based_url' } expect(annotate).to include('http://example.org/styleguide#target_based_url') end context 'when a department other than AllCops is specified' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'StyleGuideBaseURL' => 'http://example.org/styleguide' }, 'Foo' => { 'StyleGuideBaseURL' => 'http://foo.example.org' } ) end let(:cop_name) { 'Foo/Cop' } let(:urls) { annotator.urls } it 'returns style guide url when it is specified' do config['Foo/Cop'] = { 'StyleGuide' => '#target_style_guide' } expect(urls).to eq(%w[http://foo.example.org#target_style_guide]) end end context 'when a nested department is specified' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'StyleGuideBaseURL' => 'http://example.org/styleguide' }, 'Foo/Bar' => { 'StyleGuideBaseURL' => 'http://foo.example.org' } ) end let(:cop_name) { 'Foo/Bar/Cop' } let(:urls) { annotator.urls } it 'returns style guide url when it is specified' do config['Foo/Bar/Cop'] = { 'StyleGuide' => '#target_style_guide' } expect(urls).to eq(%w[http://foo.example.org#target_style_guide]) end end it 'can use a path-based setting' do config['Cop/Cop'] = { 'StyleGuide' => 'cop/path/rule#target_based_url' } expect(annotate).to include('http://example.org/cop/path/rule#target_based_url') end it 'can accept relative paths if base has a full path' do config['AllCops'] = { 'StyleGuideBaseURL' => 'https://github.com/rubocop/ruby-style-guide/' } config['Cop/Cop'] = { 'StyleGuide' => '../rails-style-guide#target_based_url' } expect(annotate).to include('https://github.com/rubocop/rails-style-guide#target_based_url') end it 'allows absolute URLs in the cop config' do config['Cop/Cop'] = { 'StyleGuide' => 'http://other.org#absolute_url' } expect(annotate).to include('http://other.org#absolute_url') end end end describe '#urls' do let(:urls) { annotator.urls } let(:config) do RuboCop::Config.new('AllCops' => { 'StyleGuideBaseURL' => 'http://example.org/styleguide' }) end it 'returns an empty array without StyleGuide URL' do expect(urls).to be_empty end it 'returns style guide url when it is specified' do config['Cop/Cop'] = { 'StyleGuide' => '#target_based_url' } expect(urls).to eq(%w[http://example.org/styleguide#target_based_url]) end it 'returns multiple reference urls' do config['Cop/Cop'] = { 'References' => ['https://example.com/some_style_guide', 'https://example.com/some_other_guide', ''] } expect(urls).to eq(['https://example.com/some_style_guide', 'https://example.com/some_other_guide']) end it 'handles References as a string' do # Config validation should prevent this, but we handle it here anyway. config['Cop/Cop'] = { 'References' => 'https://example.com/some_style_guide' } expect(urls).to eq(['https://example.com/some_style_guide']) end it 'merges "References" with "Reference" when both are specified and "Reference" is an array' do config['Cop/Cop'] = { 'References' => ['https://example.com/some_style_guide', 'https://example.com/some_other_guide'], 'Reference' => ['https://example.com/some_style_guide'] } expect(urls).to eq(%w[https://example.com/some_style_guide https://example.com/some_other_guide https://example.com/some_style_guide]) end it 'merges "References" with "Reference" when both are specified and "Reference" is a simple string' do config['Cop/Cop'] = { 'References' => ['https://example.com/some_style_guide', 'https://example.com/some_other_guide'], 'Reference' => 'https://example.com/some_style_guide' } expect(urls).to eq(%w[https://example.com/some_style_guide https://example.com/some_other_guide https://example.com/some_style_guide]) end it 'returns reference url when it is specified via legacy "Reference" key' do config['Cop/Cop'] = { 'Reference' => 'https://example.com/some_style_guide' } expect(urls).to eq(%w[https://example.com/some_style_guide]) end it 'returns an empty array if the legacy "Reference" key is blank' do config['Cop/Cop'] = { 'Reference' => '' } expect(urls).to be_empty end it 'returns multiple reference urls when specified via legacy "Reference" key' do config['Cop/Cop'] = { 'Reference' => ['https://example.com/some_style_guide', 'https://example.com/some_other_guide', ''] } expect(urls).to eq(['https://example.com/some_style_guide', 'https://example.com/some_other_guide']) end it 'returns style guide and reference url when they are specified' do config['Cop/Cop'] = { 'StyleGuide' => '#target_based_url', 'References' => ['https://example.com/plural_reference'], 'Reference' => 'https://example.com/some_style_guide' } expect(urls).to eq(%w[http://example.org/styleguide#target_based_url https://example.com/plural_reference https://example.com/some_style_guide]) end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/range_help_spec.rb
spec/rubocop/cop/range_help_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::RangeHelp do before { stub_const('TestRangeHelp', klass) } let(:instance) do klass.new(processed_source: processed_source) end let(:klass) do Class.new do include RuboCop::Cop::RangeHelp def initialize(processed_source:) @processed_source = processed_source end end end let(:processed_source) do parse_source(source) end describe 'source indicated by #range_with_surrounding_comma' do subject do r = instance.send(:range_with_surrounding_comma, input_range, side) processed_source.buffer.source[r.begin_pos...r.end_pos] end let(:source) { 'raise " ,Error, "' } let(:input_range) { Parser::Source::Range.new(processed_source.buffer, 9, 14) } context 'when side is :both' do let(:side) { :both } it { is_expected.to eq(',Error,') } end context 'when side is :left' do let(:side) { :left } it { is_expected.to eq(',Error') } end context 'when side is :right' do let(:side) { :right } it { is_expected.to eq('Error,') } end end describe 'source indicated by #range_with_surrounding_space' do let(:source) { 'f { a(2) }' } let(:input_range) { Parser::Source::Range.new(processed_source.buffer, 5, 9) } shared_examples 'works with various `side`s' do context 'when side is :both' do let(:side) { :both } it { is_expected.to eq(' a(2) ') } end context 'when side is :left' do let(:side) { :left } it { is_expected.to eq(' a(2)') } end context 'when side is :right' do let(:side) { :right } it { is_expected.to eq('a(2) ') } end end context 'when passing range as a kwarg' do subject do r = instance.send(:range_with_surrounding_space, range: input_range, side: side) processed_source.buffer.source[r.begin_pos...r.end_pos] end it_behaves_like 'works with various `side`s' end context 'when passing range as a positional argument' do subject do r = instance.send(:range_with_surrounding_space, input_range, side: side) processed_source.buffer.source[r.begin_pos...r.end_pos] end it_behaves_like 'works with various `side`s' end end describe 'source indicated by #range_by_whole_lines' do subject do r = output_range processed_source.buffer.source[r.begin_pos...r.end_pos] end let(:source) { <<~RUBY } puts 'example' puts 'another example' something_else RUBY # `input_source` defined in contexts let(:begin_pos) { source.index(input_source) } let(:end_pos) { begin_pos + input_source.length } let(:input_range) { Parser::Source::Range.new(processed_source.buffer, begin_pos, end_pos) } let(:output_range) do instance.send( :range_by_whole_lines, input_range, include_final_newline: include_final_newline ) end shared_examples 'final newline behavior' do context 'without include_final_newline' do let(:include_final_newline) { false } it { is_expected.to eq(expected) } end context 'with include_final_newline' do let(:include_final_newline) { true } it { is_expected.to eq("#{expected}\n") } end end context 'when part of a single line is selected' do let(:input_source) { "'example'" } let(:expected) { "puts 'example'" } it_behaves_like 'final newline behavior' end context 'with a whole line except newline selected' do let(:input_source) { "puts 'example'" } let(:expected) { "puts 'example'" } it_behaves_like 'final newline behavior' end context 'with a whole line plus beginning of next line' do let(:input_source) { "puts 'example'\n" } let(:expected) { "puts 'example'\nputs 'another example'" } it_behaves_like 'final newline behavior' end context 'with end of one line' do let(:begin_pos) { 14 } let(:end_pos) { 14 } let(:expected) { "puts 'example'" } it_behaves_like 'final newline behavior' end context 'with beginning of one line' do let(:begin_pos) { 15 } let(:end_pos) { 15 } let(:expected) { "puts 'another example'" } it_behaves_like 'final newline behavior' end context 'with parts of two lines' do let(:input_source) { "'example'\nputs 'another" } let(:expected) { "puts 'example'\nputs 'another example'" } it_behaves_like 'final newline behavior' end context 'with parts of four lines' do let(:input_source) { "'example'\nputs 'another example'\n\nso" } let(:expected) { source.chomp } it_behaves_like 'final newline behavior' end context "when source doesn't end with a newline" do let(:source) { "example\nwith\nno\nnewline_at_end" } let(:input_source) { 'line_at_e' } context 'without include_final_newline' do let(:include_final_newline) { false } it { is_expected.to eq('newline_at_end') } end context 'with include_final_newline' do let(:include_final_newline) { true } it { is_expected.to eq('newline_at_end') } it { expect(output_range.end_pos).to eq(source.size) } end end end describe '#range_with_comments_and_lines' do subject(:result) do instance.send(:range_with_comments_and_lines, node) end def indent(string, amount) string.gsub(/^(?!$)/, ' ' * amount) end let(:node) do processed_source.ast.each_node(:def).to_a[1] end let(:source) do <<~RUBY class A # foo 1 def foo # foo 2 end # bar 1 def bar # bar 2 end # baz 1 def baz # baz 2 end end RUBY end it 'returns a range that includes related comments and whole lines' do expect(result.source).to eq(indent(<<~RUBY, 2)) # bar 1 def bar # bar 2 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/util_spec.rb
spec/rubocop/cop/util_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Util do before { stub_const('TestUtil', Class.new { include RuboCop::Cop::Util }) } describe '#line_range' do let(:source) do <<~RUBY foo = 1 bar = 2 class Test def some_method do_something end end baz = 8 RUBY end let(:processed_source) { parse_source(source) } let(:ast) { processed_source.ast } let(:node) { ast.each_node.find(&:class_type?) } it 'returns line range of the expression' do line_range = described_class.line_range(node) expect(line_range).to eq(3..7) end end describe '#to_supported_styles' do subject { described_class.to_supported_styles(enforced_style) } context 'when EnforcedStyle' do let(:enforced_style) { 'EnforcedStyle' } it { is_expected.to eq('SupportedStyles') } end context 'when EnforcedStyleInsidePipes' do let(:enforced_style) { 'EnforcedStyleInsidePipes' } it { is_expected.to eq('SupportedStylesInsidePipes') } end end describe '#same_line?' do let(:source) do <<~RUBY @foo + @bar @baz RUBY end let(:processed_source) { parse_source(source) } let(:ast) { processed_source.ast } let(:nodes) { ast.each_descendant(:ivar).to_a } let(:ivar_foo_node) { nodes[0] } let(:ivar_bar_node) { nodes[1] } let(:ivar_baz_node) { nodes[2] } it 'returns true when two nodes are on the same line' do expect(described_class).to be_same_line(ivar_foo_node, ivar_bar_node) end it 'returns false when two nodes are not on the same line' do expect(described_class).not_to be_same_line(ivar_foo_node, ivar_baz_node) end it 'can use ranges' do expect(described_class).to be_same_line(ivar_foo_node.source_range, ivar_bar_node) end it 'returns false if an argument is not a node or range' do expect(described_class).not_to be_same_line(ivar_foo_node, 5) expect(described_class).not_to be_same_line(5, ivar_bar_node) end end describe '#parse_regexp' do it 'returns parsed expression structure on valid regexp' do expect(described_class.parse_regexp('a+')).to be_a(Regexp::Expression::Root) end it 'returns `nil` on invalid regexp' do expect(described_class.parse_regexp('+')).to be_nil end end describe '#to_string_literal' do it 'returns literal for normal string' do expect(TestUtil.new.send(:to_string_literal, 'foo')).to eq("'foo'") end it 'returns literal for string which requires escaping' do expect(TestUtil.new.send(:to_string_literal, 'foo\'')).to eq('"foo\'"') end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/cop_spec.rb
spec/rubocop/cop/cop_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Cop, :config do include FileHelper let(:source) { 'code = {some: :ruby}' } let(:location) { source_range(0...1) } before { cop.send(:begin_investigation, processed_source) } it 'initially has 0 offenses' do expect(cop.offenses).to be_empty end it 'qualified_cop_name is deprecated' do expect { described_class.qualified_cop_name('Layout/LineLength', '--only') } .to output(/`Cop.qualified_cop_name` is deprecated/).to_stderr end describe '.documentation_url' do context 'without passing a config' do subject(:url) { cop_class.documentation_url } describe 'for a builtin cop class' do let(:cop_class) { RuboCop::Cop::Layout::BlockEndNewline } it { is_expected.to eq 'https://docs.rubocop.org/rubocop/cops_layout.html#layoutblockendnewline' } # rubocop:disable Layout/LineLength end describe 'for a custom cop class without DocumentationBaseURL', :restore_registry do let(:cop_class) { stub_cop_class('Some::Cop') { def foo; end } } it { is_expected.to be_nil } end end context 'when passing a config' do subject(:url) { cop_class.documentation_url(config) } describe 'for a builtin cop class' do let(:cop_class) { RuboCop::Cop::Layout::BlockEndNewline } it { is_expected.to eq 'https://docs.rubocop.org/rubocop/cops_layout.html#layoutblockendnewline' } # rubocop:disable Layout/LineLength end describe 'for a custom cop class without DocumentationBaseURL', :restore_registry do let(:cop_class) { stub_cop_class('Some::Cop') { def foo; end } } it { is_expected.to be_nil } end describe 'for a custom cop class with DocumentationBaseURL', :restore_registry do let(:cop_class) { stub_cop_class('Rails::Exit') { def foo; end } } let(:config) do RuboCop::Config.new( 'Rails' => { 'DocumentationBaseURL' => 'https://docs.rubocop.org/rubocop-rails' } ) end it { is_expected.to eq 'https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsexit' } end describe 'for a custom cop class with DocumentationExtension', :restore_registry do let(:cop_class) { stub_cop_class('Sorbet::FalseSigil') { def foo; end } } let(:config) do RuboCop::Config.new( 'Sorbet' => { 'DocumentationBaseURL' => 'https://github.com/Shopify/rubocop-sorbet/blob/main/manual', 'DocumentationExtension' => '.md' } ) end it { is_expected.to eq 'https://github.com/Shopify/rubocop-sorbet/blob/main/manual/cops_sorbet.md#sorbetfalsesigil' } end end end describe 'requires_gem', :restore_registry do context 'on a cop with no gem requirements' do let(:cop_class) do stub_cop_class('CopSpec::CopWithNoGemReqs') do # no calls to `require_gem` end end describe '.gem_requirements' do it 'returns an empty hash' do expect(cop_class.gem_requirements).to eq({}) end end end context 'on a cop with a versionless gem requirement' do let(:cop_class) do stub_cop_class('CopSpec::CopWithVersionlessGemReq') do requires_gem 'gem' end end it 'returns a unconstrained requirement' do expected = { 'gem' => Gem::Requirement.new('>= 0') } expect(cop_class.gem_requirements).to eq(expected) end end describe 'on a cop with gem version requirements' do let(:cop_class) do stub_cop_class('CopSpec::CopWithGemReqs') do requires_gem 'gem1', '>= 1.2.3' requires_gem 'gem2', '>= 4.5.6' end end it 'can be retrieved with .gem_requirements' do expected = { 'gem1' => Gem::Requirement.new('>= 1.2.3'), 'gem2' => Gem::Requirement.new('>= 4.5.6') } expect(cop_class.gem_requirements).to eq(expected) end end it 'is heritable' do superclass = stub_cop_class('CopSpec::SuperclassCopWithGemReqs') do requires_gem 'gem1', '>= 1.2.3' end subclass = stub_cop_class('CopSpec::SubclassCopWithGemReqs', inherit: superclass) do requires_gem 'gem2', '>= 4.5.6' end expected = { 'gem1' => Gem::Requirement.new('>= 1.2.3'), 'gem2' => Gem::Requirement.new('>= 4.5.6') } expect(subclass.gem_requirements).to eq(expected) # Ensure the superclass wasn't modified: expect(superclass.gem_requirements).to eq(expected.slice('gem1')) end end describe '#target_gem_version', :isolated_environment do let(:cop_class) { RuboCop::Cop::Style::HashSyntax } before do # Call the original to actually look at the provided Gemfile.lock allow(config).to receive(:gem_versions_in_target).and_call_original end it 'returns nil when no lockfile exists' do expect(cop.target_gem_version('foo')).to be_nil end context 'when the lockfile exists' do before do create_file('Gemfile.lock', <<~LOCKFILE) GEM specs: rack (3.1.1) PLATFORMS ruby DEPENDENCIES rack (~> 3.0) LOCKFILE end it 'returns nil when the gem is not found' do expect(cop.target_gem_version('foo')).to be_nil end it 'returns the gem version for a matching gem' do expect(cop.target_gem_version('rack')).to eq(Gem::Version.new('3.1.1')) end end end it 'keeps track of offenses' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.size).to eq(1) end it 'reports registered offenses' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses).not_to be_empty end it 'sets default severity' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.first.severity).to eq(:convention) end it 'sets custom severity if present' do cop.config[cop.name] = { 'Severity' => 'warning' } cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.first.severity).to eq(:warning) end it 'warns if custom severity is invalid' do cop.config[cop.name] = { 'Severity' => 'superbad' } expect { cop.add_offense(nil, location: location, message: 'message') } .to output(/Warning: Invalid severity 'superbad'./).to_stderr end context 'when disabled by a comment' do subject(:offense_status) do cop.add_offense(nil, location: location, message: 'message') cop.offenses.first.status end before do allow(processed_source.comment_config).to receive(:cop_enabled_at_line?).and_return(false) end context 'ignore_disable_comments is false' do let(:cop_options) { { ignore_disable_comments: false } } it 'sets offense as disabled' do expect(offense_status).to eq :disabled end end context 'ignore_disable_comments is true' do let(:cop_options) { { ignore_disable_comments: true } } it 'does not set offense as disabled' do expect(offense_status).not_to eq :disabled end end end describe 'for a cop with a name' do let(:cop_class) { RuboCop::Cop::Style::For } it 'registers an offense with its name' do offenses = cop.add_offense(location, message: 'message') expect(offenses.first.cop_name).to eq('Style/For') end end describe 'setting of Offense#corrected attribute' do context 'when cop does not support autocorrection' do before { allow(cop).to receive(:support_autocorrect?).and_return(false) } it 'is not specified (set to nil)' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.first).not_to be_corrected end context 'when autocorrect is requested' do before { allow(cop).to receive(:autocorrect_requested?).and_return(true) } it 'is not specified (set to nil)' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.first).not_to be_corrected end context 'when disable_uncorrectable is enabled' do before { allow(cop).to receive(:disable_uncorrectable?).and_return(true) } let(:node) do instance_double(RuboCop::AST::Node, location: instance_double(Parser::Source::Map, expression: location, line: 1)) end it 'is set to true' do cop.add_offense(node, location: location, message: 'message') expect(cop.offenses.first).to be_corrected expect(cop.offenses.first.status).to be(:corrected_with_todo) end end end end context 'when cop supports autocorrection', :restore_registry do let(:cop_class) do cop_class = nil expect do # rubocop:disable RSpec/ExpectInLet cop_class = stub_cop_class('RuboCop::Cop::Test::StubCop', inherit: described_class) do def autocorrect(node); end end end.to output(/Inheriting from `RuboCop::Cop::Cop` is deprecated/).to_stderr cop_class end context 'when offense was corrected' do before do allow(cop).to receive_messages(autocorrect?: true, autocorrect: lambda do |corrector| corrector.insert_before(location, 'hi!') end) end it 'is set to true' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.first).to be_corrected end end context 'when autocorrection is not needed' do before { allow(cop).to receive(:autocorrect?).and_return(false) } it 'is set to false' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.first).not_to be_corrected end end context 'when offense was not corrected because of an error' do before do allow(cop).to receive_messages(autocorrect?: true, autocorrect: false) end it 'is set to false' do cop.add_offense(nil, location: location, message: 'message') expect(cop.offenses.first).not_to be_corrected end end end end context 'with no submodule' do it('has right name') { expect(cop_class.cop_name).to eq('Cop/Cop') } it('has right department') { expect(cop_class.department).to eq(:Cop) } end context 'with style cops' do let(:cop_class) { RuboCop::Cop::Style::For } it('has right name') { expect(cop_class.cop_name).to eq('Style/For') } it('has right department') { expect(cop_class.department).to eq(:Style) } end context 'with lint cops' do let(:cop_class) { RuboCop::Cop::Lint::Loop } it('has right name') { expect(cop_class.cop_name).to eq('Lint/Loop') } it('has right department') { expect(cop_class.department).to eq(:Lint) } end describe 'Registry' do describe '#departments' do subject(:departments) { described_class.registry.departments } it('has departments') { expect(departments.length).not_to eq(0) } it { is_expected.to include(:Lint) } it { is_expected.to include(:Style) } it 'contains every value only once' do expect(departments.length).to eq(departments.uniq.length) end end describe '#with_department' do let(:departments) { described_class.registry.departments } it 'has at least one cop per department' do departments.each do |c| expect(described_class.registry.with_department(c).length).to be > 0 end end it 'has each cop in exactly one type' do sum = 0 departments.each { |c| sum += described_class.registry.with_department(c).length } expect(sum).to be described_class.registry.length end it 'returns 0 for an invalid type' do expect(described_class.registry.with_department('x').length).to be 0 end end end describe '#autocorrect?' do subject { cop.autocorrect? } let(:support_autocorrect) { true } let(:disable_uncorrectable) { false } before do allow(cop.class).to receive(:support_autocorrect?) { support_autocorrect } allow(cop).to receive(:disable_uncorrectable?) { disable_uncorrectable } end context 'when the option is not given' do let(:cop_options) { {} } it { is_expected.to be(false) } end context 'when the option is given' do let(:cop_options) { { autocorrect: true } } it { is_expected.to be(true) } context 'when cop does not support autocorrection' do let(:support_autocorrect) { false } it { is_expected.to be(false) } context 'when disable_uncorrectable is enabled' do let(:disable_uncorrectable) { true } it { is_expected.to be(true) } end end context 'when the cop is set to not autocorrect' do let(:cop_options) { { 'AutoCorrect' => false } } it { is_expected.to be(false) } end end end describe '#relevant_file?' do subject { cop.relevant_file?(file) } let(:cop_config) { { 'Include' => ['foo.rb'] } } context 'when the file matches the Include configuration' do let(:file) { 'foo.rb' } it { is_expected.to be(true) } end context 'when the file doesn\'t match the Include configuration' do let(:file) { 'bar.rb' } it { is_expected.to be(false) } end context 'when the file is an anonymous source' do let(:file) { '(string)' } it { is_expected.to be(true) } end describe 'for a cop with gem version requirements', :restore_registry do subject { cop.relevant_file?(file) } let(:file) { 'foo.rb' } let(:cop_class) do stub_cop_class('CopSpec::CopWithGemReqs') do requires_gem 'gem1', '>= 1.2.3' end end before do allow(config).to receive(:gem_versions_in_target).and_return(gem_versions_in_target) end context 'the target doesn\'t satisfy any of the gem requirements' do let(:gem_versions_in_target) { {} } it { is_expected.to be(false) } end context 'the target has a required gem, but in a version that\'s too old' do let(:gem_versions_in_target) { { 'gem1' => Gem::Version.new('1.2.2') } } it { is_expected.to be(false) } end context 'the target has a required gem, in a supported version' do let(:gem_versions_in_target) { { 'gem1' => Gem::Version.new('1.2.3') } } it { is_expected.to be(true) } end context 'for a cop with multiple gem requirements' do let(:cop_class) do stub_cop_class('CopSpec::CopWithGemReqs') do requires_gem 'gem1', '>= 1.2.3' requires_gem 'gem2', '>= 4.5.6' end end context 'the target satisfies one but not all of the gem requirements' do let(:gem_versions_in_target) do { 'gem1' => Gem::Version.new('1.2.3'), 'gem2' => Gem::Version.new('4.5.5') } end it { is_expected.to be(false) } end context 'the target has all the required gems with sufficient versions' do let(:gem_versions_in_target) do { 'gem1' => Gem::Version.new('1.2.3'), 'gem2' => Gem::Version.new('4.5.6') } end it { is_expected.to be(true) } end end end end describe '#safe_autocorrect?' do subject { cop.safe_autocorrect? } context 'when cop is declared unsafe' do let(:cop_config) { { 'Safe' => false } } it { is_expected.to be(false) } end context 'when autocorrection of the cop is declared unsafe' do let(:cop_config) { { 'SafeAutoCorrect' => false } } it { is_expected.to be(false) } end context 'when safety is undeclared' do let(:cop_config) { {} } it { is_expected.to be(true) } end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/force_spec.rb
spec/rubocop/cop/force_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Force do subject(:force) { described_class.new(cops) } let(:cops) { [instance_double(RuboCop::Cop::Base), instance_double(RuboCop::Cop::Base)] } describe '.force_name' do it 'returns the class name without namespace' do expect(RuboCop::Cop::VariableForce.force_name).to eq('VariableForce') end end describe '#run_hook' do it 'invokes a hook in all cops' do expect(cops).to all receive(:message).with(:foo) force.run_hook(:message, :foo) end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/corrector_spec.rb
spec/rubocop/cop/corrector_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Corrector do describe '#rewrite' do let(:source) do <<~RUBY.strip true and false RUBY end let(:processed_source) { parse_source(source) } let(:node) { processed_source.ast } let(:operator) { node.loc.operator } def do_rewrite(corrections = nil, &block) corrector = described_class.new(processed_source.buffer) Array(corrections || block).each { |c| c.call(corrector) } corrector.rewrite end matcher :rewrite_to do |expected| supports_block_expectations attr_accessor :result match { |corrections| (self.result = do_rewrite corrections) == expected } failure_message { "expected to rewrite to #{expected.inspect}, but got #{result.inspect}" } failure_message_when_negated { "expected not to rewrite to #{expected.inspect}, but did" } end it 'allows removal of a range' do expect { |corr| corr.remove(operator) }.to rewrite_to 'true false' end it 'allows insertion before a source range' do expect do |corrector| corrector.insert_before(operator, ';nil ') end.to rewrite_to 'true ;nil and false' end it 'allows insertion after a source range' do expect do |corrector| corrector.insert_after(operator, ' nil;') end.to rewrite_to 'true and nil; false' end it 'allows insertion before and after a source range' do expect { |corrector| corrector.wrap(operator, '(', ')') }.to rewrite_to 'true (and) false' end it 'allows replacement of a range' do expect { |c| c.replace(operator, 'or') }.to rewrite_to 'true or false' end it 'allows removal of characters preceding range' do expect { |corrector| corrector.remove_preceding(operator, 2) }.to rewrite_to 'truand false' end it 'allows removal of characters from range beginning' do expect { |corrector| corrector.remove_leading(operator, 2) }.to rewrite_to 'true d false' end it 'allows removal of characters from range ending' do expect { |corrector| corrector.remove_trailing(operator, 2) }.to rewrite_to 'true a false' end it 'allows swapping sources of two nodes' do expect { |corrector| corrector.swap(node.lhs, node.rhs) }.to rewrite_to 'false and true' end it 'accepts a node instead of a range' do expect { |corrector| corrector.replace(node.rhs, 'maybe') }.to rewrite_to 'true and maybe' end it 'raises a useful error if not given a node or a range' do expect do do_rewrite { |corr| corr.replace(1..3, 'oops') } end.to raise_error(TypeError, 'Expected a Parser::Source::Range, ' \ 'Comment or RuboCop::AST::Node, got Range') end context 'when range is from incorrect source' do let(:other_source) { parse_source(source) } let(:op_other) { Parser::Source::Range.new(other_source.buffer, 0, 2) } let(:op_string) { Parser::Source::Range.new(processed_source.raw_source, 0, 2) } { remove: nil, insert_before: ['1'], insert_after: ['1'], replace: ['1'], remove_preceding: [2], remove_leading: [2], remove_trailing: [2] }.each_pair do |method, params| it "raises exception from #{method}" do expect do do_rewrite { |corr| corr.public_send(method, op_string, *params) } end.to raise_error(RuntimeError, 'Corrector expected range source buffer to be ' \ 'a Parser::Source::Buffer, but got String') expect do do_rewrite { |corr| corr.public_send(method, op_other, *params) } end.to raise_error(RuntimeError, /^Correction target buffer \d+ name:"\(string\)" is not current/) 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/alignment_corrector_spec.rb
spec/rubocop/cop/alignment_corrector_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::AlignmentCorrector, :config do let(:cop_class) { RuboCop::Cop::Test::AlignmentDirective } describe '#correct' do context 'simple indentation' do context 'with a positive column delta' do it 'indents' do expect_offense(<<~RUBY) # >> 2 42 ^^ Indent this node. RUBY expect_correction(<<~RUBY) # 42 RUBY end end context 'with a negative column delta' do it 'outdents' do expect_offense(<<~RUBY) # << 3 42 ^^ Indent this node. RUBY expect_correction(<<~RUBY) # 42 RUBY end end end shared_examples 'heredoc indenter' do |start_heredoc, column_delta| let(:indentation) { ' ' * column_delta } let(:end_heredoc) { /\w+/.match(start_heredoc)[0] } it 'does not change indentation of here doc bodies and end markers' do expect_offense(<<~RUBY) # >> #{column_delta} begin ^^^^^ Indent this node. #{start_heredoc} a b #{end_heredoc} end RUBY expect_correction(<<~RUBY) # #{indentation}begin #{indentation} #{start_heredoc} a b #{end_heredoc} #{indentation}end RUBY end end context 'with large column deltas' do context 'with plain heredoc (<<)' do it_behaves_like 'heredoc indenter', '<<DOC', 20 end context 'with heredoc in backticks (<<``)' do it_behaves_like 'heredoc indenter', '<<`DOC`', 20 end end context 'with single-line here docs' do it 'does not indent body and end marker' do indentation = ' ' expect_offense(<<~RUBY) # >> 2 begin ^^^^^ Indent this node. <<DOC single line DOC end RUBY expect_correction(<<~RUBY) # #{indentation}begin #{indentation} <<DOC single line DOC #{indentation}end RUBY end end context 'within string literals' do it 'does not insert whitespace' do expect_offense(<<~RUBY) # >> 2 begin ^^^^^ Indent this node. dstr = 'a b c' xstr = `a b c` end RUBY expect_correction(<<~RUBY) # begin dstr = 'a b c' xstr = `a b c` end RUBY end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/offense_spec.rb
spec/rubocop/cop/offense_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Offense do subject(:offense) do described_class.new(:convention, location, 'message', 'CopName', :corrected) end let(:location) do source_buffer = Parser::Source::Buffer.new('test', 1) source_buffer.source = "a\n" Parser::Source::Range.new(source_buffer, 0, 1) end it 'has a few required attributes' do expect(offense.severity).to eq(:convention) expect(offense.line).to eq(1) expect(offense.message).to eq('message') expect(offense.cop_name).to eq('CopName') expect(offense).to be_correctable expect(offense).to be_corrected expect(offense.highlighted_area.source).to eq('a') end it 'overrides #to_s' do expect(offense.to_s).to eq('C: 1: 1: message') end it 'does not blow up if a message contains %' do offense = described_class.new(:convention, location, 'message % test', 'CopName') expect(offense.to_s).to eq('C: 1: 1: message % test') end it 'redefines == to compare offenses based on their contents' do o1 = described_class.new(:convention, location, 'message', 'CopName') o2 = described_class.new(:convention, location, 'message', 'CopName') expect(o1 == o2).to be(true) end it 'is frozen' do expect(offense).to be_frozen end %i[severity location message cop_name].each do |a| describe "##{a}" do it 'is frozen' do expect(offense.public_send(a)).to be_frozen end end end context 'when unknown severity is passed' do it 'raises error' do expect do described_class.new(:foobar, location, 'message', 'CopName') end.to raise_error(ArgumentError) end end describe '#severity_level' do subject(:severity_level) do described_class.new(severity, location, 'message', 'CopName').severity.level end context 'when severity is :info' do let(:severity) { :info } it 'is 1' do expect(severity_level).to eq(1) end end context 'when severity is :refactor' do let(:severity) { :refactor } it 'is 2' do expect(severity_level).to eq(2) end end context 'when severity is :fatal' do let(:severity) { :fatal } it 'is 6' do expect(severity_level).to eq(6) end end end describe '#<=>' do def offense(hash = {}) attrs = { sev: :convention, line: 5, col: 5, mes: 'message', cop: 'CopName' }.merge(hash) described_class.new( attrs[:sev], location(attrs[:line], attrs[:col], %w[aaaaaa bbbbbb cccccc dddddd eeeeee ffffff]), attrs[:mes], attrs[:cop] ) end def location(line, column, source) source_buffer = Parser::Source::Buffer.new('test', 1) source_buffer.source = source.join("\n") begin_pos = source[0...(line - 1)].reduce(0) { |a, e| a + e.length + 1 } + column Parser::Source::Range.new(source_buffer, begin_pos, begin_pos + 1) end # We want a nice table layout, so we allow space inside empty hashes. # rubocop:disable Layout/SpaceInsideHashLiteralBraces, Layout/ExtraSpacing [ [{ }, { }, 0], [{ line: 6 }, { line: 5 }, 1], [{ line: 5, col: 6 }, { line: 5, col: 5 }, 1], [{ line: 6, col: 4 }, { line: 5, col: 5 }, 1], [{ cop: 'B' }, { cop: 'A' }, 1], [{ line: 6, cop: 'A' }, { line: 5, cop: 'B' }, 1], [{ col: 6, cop: 'A' }, { col: 5, cop: 'B' }, 1] ].each do |one, other, expectation| # rubocop:enable Layout/SpaceInsideHashLiteralBraces, Layout/ExtraSpacing context "when receiver has #{one} and other has #{other}" do it "returns #{expectation}" do an_offense = offense(one) other_offense = offense(other) expect(an_offense <=> other_offense).to eq(expectation) end end end end context 'offenses that span multiple lines' do subject(:offense) do described_class.new(:convention, location, 'message', 'CopName', :corrected) end let(:location) do source_buffer = Parser::Source::Buffer.new('test', 1) source_buffer.source = <<~RUBY def foo something something_else end RUBY Parser::Source::Range.new(source_buffer, 0, source_buffer.source.length) end it 'highlights the first line' do expect(offense.location.source).to eq(location.source_buffer.source) expect(offense.highlighted_area.source).to eq('def foo') end end context 'offenses that span part of a line' do subject(:offense) do described_class.new(:convention, location, 'message', 'CopName', :corrected) end let(:location) do source_buffer = Parser::Source::Buffer.new('test', 1) source_buffer.source = <<~RUBY def Foo something something_else end RUBY Parser::Source::Range.new(source_buffer, 4, 7) end it 'highlights the first line' do expect(offense.highlighted_area.source).to eq('Foo') end end context 'when the location is pseudo' do let(:location) { described_class::NO_LOCATION } it 'returns a location with valid size and length' do expect(offense.location.size).to eq 0 expect(offense.location.length).to eq 0 end it 'returns a line' do expect(offense.line).to eq 1 end it 'returns a column' do expect(offense.column).to eq 0 end it 'returns a source line' do expect(offense.source_line).to eq '' end it 'returns a column length' do expect(offense.column_length).to eq 0 end it 'returns the first line' do expect(offense.first_line).to eq 1 end it 'returns the last line' do expect(offense.last_line).to eq 1 end it 'returns the last column' do expect(offense.last_column).to eq 0 end it 'returns a column range' do expect(offense.column_range).to eq 0...0 end it 'returns a real column' do expect(offense.real_column).to eq 1 end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/registry_spec.rb
spec/rubocop/cop/registry_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Registry do subject(:registry) { described_class.new(cops, options) } let(:cops) do [ RuboCop::Cop::Lint::BooleanSymbol, RuboCop::Cop::Lint::DuplicateMethods, RuboCop::Cop::Layout::FirstArrayElementIndentation, RuboCop::Cop::Metrics::MethodLength, RuboCop::Cop::RSpec::Foo, RuboCop::Cop::Test::FirstArrayElementIndentation ] end let(:options) { {} } before do stub_const('RuboCop::Cop::Test::FirstArrayElementIndentation', Class.new(RuboCop::Cop::Base)) stub_const('RuboCop::Cop::RSpec::Foo', Class.new(RuboCop::Cop::Base)) end # `RuboCop::Cop::Base` mutates its `registry` when inherited from. # This can introduce nondeterministic failures in other parts of the # specs if this mutation occurs before code that depends on this global cop # store. The workaround is to replace the global cop store with a temporary # store during these tests around { |test| described_class.with_temporary_global { test.run } } it 'can be cloned' do klass = RuboCop::Cop::Metrics::AbcSize copy = registry.dup copy.enlist(klass) expect(copy.cops).to include(klass) expect(registry.cops).not_to include(klass) end context 'when dismissing a cop class' do let(:cop_class) { RuboCop::Cop::Metrics::AbcSize } before { registry.enlist(cop_class) } it 'allows it if done rapidly' do registry.dismiss(cop_class) expect(registry.cops).not_to include(cop_class) end it 'disallows it if done too late' do expect(registry.cops).to include(cop_class) expect { registry.dismiss(cop_class) }.to raise_error(RuntimeError) end it 'allows re-listing' do registry.dismiss(cop_class) expect(registry.cops).not_to include(cop_class) registry.enlist(cop_class) expect(registry.cops).to include(cop_class) end end it 'exposes cop departments' do expect(registry.departments).to eql(%i[Lint Layout Metrics RSpec Test]) end it 'can filter down to one type' do expect(registry.with_department(:Lint)).to eq(described_class.new(cops.first(2))) end it 'can filter down to all but one type' do expect(registry.without_department(:Lint)).to eq(described_class.new(cops.drop(2))) end describe '#contains_cop_matching?' do it 'can find cops matching a given name' do result = registry.contains_cop_matching?(['Test/FirstArrayElementIndentation']) expect(result).to be(true) end it 'returns false for cops not included in the store' do expect(registry).not_to be_contains_cop_matching(['Style/NotReal']) end end describe '#qualified_cop_name' do let(:origin) { '/app/.rubocop.yml' } it 'gives back already properly qualified names' do result = registry.qualified_cop_name('Layout/FirstArrayElementIndentation', origin) expect(result).to eql('Layout/FirstArrayElementIndentation') end it 'qualifies names without a namespace' do warning = "/app/.rubocop.yml: Warning: no department given for MethodLength.\n" qualified = nil expect do qualified = registry.qualified_cop_name('MethodLength', origin) end.to output(warning).to_stderr expect(qualified).to eql('Metrics/MethodLength') end it 'qualifies names with the correct namespace' do warning = "/app/.rubocop.yml: Warning: no department given for Foo.\n" qualified = nil expect do qualified = registry.qualified_cop_name('Foo', origin) end.to output(warning).to_stderr expect(qualified).to eql('RSpec/Foo') end it 'emits a warning when namespace is incorrect' do warning = '/app/.rubocop.yml: Style/MethodLength has the wrong ' \ "namespace - replace it with Metrics/MethodLength\n" qualified = nil expect do qualified = registry.qualified_cop_name('Style/MethodLength', origin) end.to output(warning).to_stderr expect(qualified).to eql('Metrics/MethodLength') end context 'when cops share the same class name' do let(:cops) do [ RuboCop::Cop::Test::SameNameInMultipleNamespace, RuboCop::Cop::Test::Foo::SameNameInMultipleNamespace, RuboCop::Cop::Test::Bar::SameNameInMultipleNamespace ] end it 'raises an error when a cop name is ambiguous' do cop_name = 'SameNameInMultipleNamespace' expect { registry.qualified_cop_name(cop_name, origin) } .to raise_error(RuboCop::Cop::AmbiguousCopName) .with_message( 'Ambiguous cop name `SameNameInMultipleNamespace` used in ' \ '/app/.rubocop.yml needs department qualifier. Did you mean ' \ 'Test/SameNameInMultipleNamespace or ' \ 'Test/Foo/SameNameInMultipleNamespace or ' \ 'Test/Bar/SameNameInMultipleNamespace?' ) .and output('/app/.rubocop.yml: Warning: no department given for ' \ "SameNameInMultipleNamespace.\n").to_stderr end it 'qualifies names when the cop is unambiguous' do qualified = registry.qualified_cop_name('Test/SameNameInMultipleNamespace', origin) expect(qualified).to eql('Test/SameNameInMultipleNamespace') end end it 'returns the provided name if no namespace is found' do expect(registry.qualified_cop_name('NotReal', origin)).to eql('NotReal') end end it 'exposes a mapping of cop names to cop classes' do expect(registry.to_h).to eql( 'Lint/BooleanSymbol' => [RuboCop::Cop::Lint::BooleanSymbol], 'Lint/DuplicateMethods' => [RuboCop::Cop::Lint::DuplicateMethods], 'Layout/FirstArrayElementIndentation' => [ RuboCop::Cop::Layout::FirstArrayElementIndentation ], 'Metrics/MethodLength' => [RuboCop::Cop::Metrics::MethodLength], 'Test/FirstArrayElementIndentation' => [ RuboCop::Cop::Test::FirstArrayElementIndentation ], 'RSpec/Foo' => [RuboCop::Cop::RSpec::Foo] ) end describe '#cops' do it 'exposes a list of cops' do expect(registry.cops).to eql(cops) end context 'with cops having the same inner-most module' do let(:cops) { [RuboCop::Cop::Foo::Bar, RuboCop::Cop::Baz::Foo::Bar] } before do stub_const('RuboCop::Cop::Foo::Bar', Class.new(RuboCop::Cop::Base)) stub_const('RuboCop::Cop::Baz::Foo::Bar', Class.new(RuboCop::Cop::Base)) end it 'exposes both cops' do expect(registry.cops).to contain_exactly( RuboCop::Cop::Foo::Bar, RuboCop::Cop::Baz::Foo::Bar ) end end end it 'exposes the number of stored cops' do expect(registry.length).to be(6) end describe '#enabled' do subject(:enabled_cops) { registry.enabled(config) } let(:config) do RuboCop::Config.new( 'Test/FirstArrayElementIndentation' => { 'Enabled' => false }, 'RSpec/Foo' => { 'Safe' => false } ) end it 'selects cops which are enabled in the config' do expect(registry.enabled(config)).to eql(cops.first(5)) end it 'overrides config if :only includes the cop' do options[:only] = ['Test/FirstArrayElementIndentation'] expect(enabled_cops).to eql(cops) end it 'selects only safe cops if :safe passed' do options[:safe] = true expect(enabled_cops).not_to include(RuboCop::Cop::RSpec::Foo) end context 'when new cops are introduced' do let(:config) { RuboCop::Config.new('Lint/BooleanSymbol' => { 'Enabled' => 'pending' }) } it 'does not include them' do expect(enabled_cops).not_to include(RuboCop::Cop::Lint::BooleanSymbol) end it 'overrides config if :only includes the cop' do options[:only] = ['Lint/BooleanSymbol'] expect(enabled_cops).to eql(cops) end context 'when specifying `--disable-pending-cops` command-line option' do let(:options) { { disable_pending_cops: true } } it 'does not include them' do expect(enabled_cops).not_to include(RuboCop::Cop::Lint::BooleanSymbol) end context 'when specifying `NewCops: enable` option in .rubocop.yml' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'NewCops' => 'enable' }, 'Lint/BooleanSymbol' => { 'Enabled' => 'pending' } ) end it 'does not include them because command-line option takes ' \ 'precedence over .rubocop.yml' do expect(enabled_cops).not_to include(RuboCop::Cop::Lint::BooleanSymbol) end end end context 'when specifying `--enable-pending-cops` command-line option' do let(:options) { { enable_pending_cops: true } } it 'includes them' do expect(enabled_cops).to include(RuboCop::Cop::Lint::BooleanSymbol) end context 'when specifying `NewCops: disable` option in .rubocop.yml' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'NewCops' => 'disable' }, 'Lint/BooleanSymbol' => { 'Enabled' => 'pending' } ) end it 'includes them because command-line option takes precedence over .rubocop.yml' do expect(enabled_cops).to include(RuboCop::Cop::Lint::BooleanSymbol) end end end context 'when specifying `NewCops: pending` option in .rubocop.yml' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'NewCops' => 'pending' }, 'Lint/BooleanSymbol' => { 'Enabled' => 'pending' } ) end it 'does not include them' do expect(enabled_cops).not_to include(RuboCop::Cop::Lint::BooleanSymbol) end end context 'when specifying `NewCops: disable` option in .rubocop.yml' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'NewCops' => 'disable' }, 'Lint/BooleanSymbol' => { 'Enabled' => 'pending' } ) end it 'does not include them' do expect(enabled_cops).not_to include(RuboCop::Cop::Lint::BooleanSymbol) end end context 'when specifying `NewCops: enable` option in .rubocop.yml' do let(:config) do RuboCop::Config.new( 'AllCops' => { 'NewCops' => 'enable' }, 'Lint/BooleanSymbol' => { 'Enabled' => 'pending' } ) end it 'includes them' do expect(enabled_cops).to include(RuboCop::Cop::Lint::BooleanSymbol) end end end end it 'exposes a list of cop names' do expect(registry.names).to eql( [ 'Lint/BooleanSymbol', 'Lint/DuplicateMethods', 'Layout/FirstArrayElementIndentation', 'Metrics/MethodLength', 'RSpec/Foo', 'Test/FirstArrayElementIndentation' ] ) end describe '#department?' do it 'returns true for department name' do expect(registry).to be_department('Lint') end it 'returns false for other names' do expect(registry).not_to be_department('Foo') end end describe 'names_for_department' do it 'returns array of cops for specified department' do expect(registry.names_for_department('Lint')) .to eq %w[Lint/BooleanSymbol Lint/DuplicateMethods] end 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_spec.rb
spec/rubocop/cop/generator_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Generator do subject(:generator) { described_class.new(cop_identifier, output: stdout) } let(:stdout) { StringIO.new } let(:cop_identifier) { 'Style/FakeCop' } before do allow(File).to receive(:write) stub_const('HOME_DIR', Dir.pwd) end describe '#write_source' do include_context 'cli spec behavior' it 'generates a helpful source file with the name filled in' do generated_source = <<~RUBY # frozen_string_literal: true module RuboCop module Cop module Style # TODO: Write cop description and example of bad / good code. For every # `SupportedStyle` and unique configuration, there needs to be examples. # Examples must have valid Ruby syntax. Do not use upticks. # # @safety # Delete this section if the cop is not unsafe (`Safe: false` or # `SafeAutoCorrect: false`), or use it to explain how the cop is # unsafe. # # @example EnforcedStyle: bar (default) # # Description of the `bar` style. # # # bad # bad_bar_method # # # bad # bad_bar_method(args) # # # good # good_bar_method # # # good # good_bar_method(args) # # @example EnforcedStyle: foo # # Description of the `foo` style. # # # bad # bad_foo_method # # # bad # bad_foo_method(args) # # # good # good_foo_method # # # good # good_foo_method(args) # class FakeCop < Base # TODO: Implement the cop in here. # # In many cases, you can use a node matcher for matching node pattern. # See https://github.com/rubocop/rubocop-ast/blob/master/lib/rubocop/ast/node_pattern.rb # # For example MSG = 'Use `#good_method` instead of `#bad_method`.' # TODO: Don't call `on_send` unless the method name is in this list # If you don't need `on_send` in the cop you created, remove it. RESTRICT_ON_SEND = %i[bad_method].freeze # @!method bad_method?(node) def_node_matcher :bad_method?, <<~PATTERN (send nil? :bad_method ...) PATTERN # Called on every `send` node (method call) while walking the AST. # TODO: remove this method if inspecting `send` nodes is unneeded for your cop. # By default, this is aliased to `on_csend` as well to handle method calls # with safe navigation, remove the alias if this is unnecessary. # If kept, ensure your tests cover safe navigation as well! def on_send(node) return unless bad_method?(node) add_offense(node) end alias on_csend on_send end end end end RUBY expect(File).to receive(:write).with('lib/rubocop/cop/style/fake_cop.rb', generated_source) generator.write_source expect(stdout.string).to eq("[create] lib/rubocop/cop/style/fake_cop.rb\n") end it 'refuses to overwrite existing files' do new_cop = described_class.new('Layout/IndentationStyle') allow(new_cop).to receive(:exit!) expect { new_cop.write_source } .to output( 'rake new_cop: lib/rubocop/cop/layout/indentation_style.rb ' \ "already exists!\n" ).to_stderr end end describe '#write_spec' do include_context 'cli spec behavior' it 'generates a helpful starting spec file with the class filled in' do generated_source = <<~SPEC # frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::FakeCop, :config do let(:config) { RuboCop::Config.new } # TODO: Write test code # # For example it 'registers an offense when using `#bad_method`' do expect_offense(<<~RUBY) bad_method ^^^^^^^^^^ Use `#good_method` instead of `#bad_method`. RUBY end it 'does not register an offense when using `#good_method`' do expect_no_offenses(<<~RUBY) good_method RUBY end end SPEC expect(File) .to receive(:write) .with('spec/rubocop/cop/style/fake_cop_spec.rb', generated_source) generator.write_spec end it 'refuses to overwrite existing files' do new_cop = described_class.new('Layout/IndentationStyle') allow(new_cop).to receive(:exit!) expect { new_cop.write_spec } .to output( 'rake new_cop: spec/rubocop/cop/layout/indentation_style_spec.rb ' \ "already exists!\n" ).to_stderr end end describe '#todo' do it 'provides a checklist for implementing the cop' do expect(generator.todo).to eql(<<~TODO) Do 4 steps: 1. Modify the description of Style/FakeCop in config/default.yml 2. Implement your new cop in the generated file! 3. Commit your new cop with a message such as e.g. "Add new `Style/FakeCop` cop" 4. Run `bundle exec rake changelog:new` to generate a changelog entry for your new cop. TODO end end describe '.new' do it 'does not accept an unqualified cop' do expect { described_class.new('FakeCop') } .to raise_error(ArgumentError) .with_message('Specify a cop name with Department/Name style') end end describe '#inject_config' do let(:path) { @path } # rubocop:disable RSpec/InstanceVariable around do |example| Tempfile.create('rubocop-config.yml') do |file| @path = file.path example.run end end before do # It is hacked to use `IO.write` to avoid mocking `File.write` for testing. IO.write(path, <<~YAML) # rubocop:disable Security/IoMethods Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML end context 'when it is the middle in alphabetical order' do it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/FakeCop: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '<<next>>' Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'when it is the first in alphabetical order' do let(:cop_identifier) { 'Style/Aaa' } it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Aaa: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '<<next>>' Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'when it is the last in alphabetical order' do let(:cop_identifier) { 'Style/Zzz' } it 'inserts the cop' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true Style/Zzz: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '<<next>>' YAML generator.inject_config(config_file_path: path) expect(stdout.string) .to eq('[modify] A configuration for the cop is added into ' \ "#{path}.\n") end end context 'with version provided' do it 'uses the provided version' do expect(File).to receive(:write).with(path, <<~YAML) Style/Alias: Enabled: true Style/FakeCop: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '<<next>>' Style/Lambda: Enabled: true Style/SpecialGlobalVars: Enabled: true YAML generator.inject_config(config_file_path: path) end end end describe '#snake_case' do it 'converts "Lint" to snake_case' do expect(generator.__send__(:snake_case, 'Lint')).to eq('lint') end it 'converts "FooBar" to snake_case' do expect(generator.__send__(:snake_case, 'FooBar')).to eq('foo_bar') end it 'converts "FooBar/Baz" to snake_case' do expect(generator.__send__(:snake_case, 'FooBar/Baz')).to eq('foo_bar/baz') end it 'converts "RSpec" to snake_case' do expect(generator.__send__(:snake_case, 'RSpec')).to eq('rspec') end it 'converts "RSpec/Foo" to snake_case' do expect(generator.__send__(:snake_case, 'RSpec/Foo')).to eq('rspec/foo') end it 'converts "RSpecFoo/Bar" to snake_case' do expect(generator.__send__(:snake_case, 'RSpecFoo/Bar')).to eq('rspec_foo/bar') end end context 'nested departments' do let(:cop_identifier) { 'Plugin/Style/FakeCop' } include_context 'cli spec behavior' it 'generates source and spec files correctly namespaced within departments' do expect(File).to receive(:write).with('lib/rubocop/cop/plugin/style/fake_cop.rb', an_instance_of(String)) generator.write_source expect(stdout.string).to eq("[create] lib/rubocop/cop/plugin/style/fake_cop.rb\n") expect(File).to receive(:write).with('spec/rubocop/cop/plugin/style/fake_cop_spec.rb', an_instance_of(String)) generator.write_spec expect(stdout.string) .to include("[create] spec/rubocop/cop/plugin/style/fake_cop_spec.rb\n") end end describe 'compliance with rubocop', :isolated_environment do include FileHelper around do |example| new_global = RuboCop::Cop::Registry.new([RuboCop::Cop::InternalAffairs::NodeDestructuring]) RuboCop::Cop::Registry.with_temporary_global(new_global) { example.run } end let(:config) { RuboCop::ConfigStore.new } let(:options) { { formatters: [] } } let(:runner) { RuboCop::Runner.new(options, config) } before do # Ignore any config validation errors allow_any_instance_of(RuboCop::ConfigValidator).to receive(:validate) # rubocop:disable RSpec/AnyInstance end it 'generates a cop file that has no offense' do generator.write_source expect(runner.run([])).to be true end it 'generates a spec file that has no offense' do generator.write_spec expect(runner.run([])).to be true end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/severity_spec.rb
spec/rubocop/cop/severity_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Severity do let(:info) { described_class.new(:info) } let(:refactor) { described_class.new(:refactor) } let(:convention) { described_class.new(:convention) } let(:warning) { described_class.new(:warning) } let(:error) { described_class.new(:error) } let(:fatal) { described_class.new(:fatal) } it 'has a few required attributes' do expect(convention.name).to eq(:convention) end it 'overrides #to_s' do expect(convention.to_s).to eq('convention') end it 'redefines == to compare severities' do expect(convention).to eq(:convention) expect(convention).to eq(described_class.new(:convention)) expect(convention).not_to eq(:warning) end it 'is frozen' do expect(convention).to be_frozen end describe '#code' do describe 'info' do it { expect(info.code).to eq('I') } end describe 'refactor' do it { expect(refactor.code).to eq('R') } end describe 'convention' do it { expect(convention.code).to eq('C') } end describe 'warning' do it { expect(warning.code).to eq('W') } end describe 'error' do it { expect(error.code).to eq('E') } end describe 'fatal' do it { expect(fatal.code).to eq('F') } end end describe '#level' do describe 'info' do it { expect(info.level).to eq(1) } end describe 'refactor' do it { expect(refactor.level).to eq(2) } end describe 'convention' do it { expect(convention.level).to eq(3) } end describe 'warning' do it { expect(warning.level).to eq(4) } end describe 'error' do it { expect(error.level).to eq(5) } end describe 'fatal' do it { expect(fatal.level).to eq(6) } end end describe 'constructs from code' do describe 'I' do it { expect(described_class.new('I')).to eq(info) } end describe 'R' do it { expect(described_class.new('R')).to eq(refactor) } end describe 'C' do it { expect(described_class.new('C')).to eq(convention) } end describe 'W' do it { expect(described_class.new('W')).to eq(warning) } end describe 'E' do it { expect(described_class.new('E')).to eq(error) } end describe 'F' do it { expect(described_class.new('F')).to eq(fatal) } end end describe 'Comparable' do describe 'info' do it { expect(info).to be < refactor } end describe 'refactor' do it { expect(refactor).to be < convention } end describe 'convention' do it { expect(convention).to be < warning } end describe 'warning' do it { expect(warning).to be < error } end describe 'error' do it { expect(error).to be < fatal } end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/annotation_comment_spec.rb
spec/rubocop/cop/annotation_comment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::AnnotationComment do subject(:annotation) { described_class.new(comment, keywords) } let(:keywords) { ['TODO', 'FOR LATER', 'FIXME'] } let(:comment) { instance_double(Parser::Source::Comment, text: "# #{text}") } describe '#annotation?' do subject { annotation.annotation? } context 'when given a keyword followed by a colon' do let(:text) { 'TODO: note' } it { is_expected.to be(true) } end context 'when given a keyword followed by a space' do let(:text) { 'TODO note' } it { is_expected.to be(true) } end context 'when the keyword is not capitalized properly' do let(:text) { 'todo: note' } it { is_expected.to be(true) } end context 'when the keyword is multiple words' do let(:text) { 'FOR LATER: note' } it { is_expected.to be(true) } end context 'when annotated with a non keyword' do let(:text) { 'SOMETHING: note' } it { is_expected.to be_nil } end context 'when given as the first word of a sentence' do let(:text) { 'Todo in the future' } it { is_expected.to be(false) } end context 'when it includes a keyword' do let(:text) { 'TODO2' } it { is_expected.to be_nil } end end describe '#correct?' do subject { annotation.correct?(colon: colon) } shared_examples 'correct' do |text| let(:text) { text } it { is_expected.to be(true) } end shared_examples 'incorrect' do |text| let(:text) { text } it { is_expected.to be(false) } end let(:colon) { true } context 'when a colon is required' do it_behaves_like 'correct', 'TODO: text' it_behaves_like 'correct', 'FIXME: text' it_behaves_like 'correct', 'FOR LATER: text' it_behaves_like 'incorrect', 'TODO: ' it_behaves_like 'incorrect', 'TODO ' it_behaves_like 'incorrect', 'TODO' it_behaves_like 'incorrect', 'TODOtext' it_behaves_like 'incorrect', 'TODO:text' it_behaves_like 'incorrect', 'TODO2: text' it_behaves_like 'incorrect', 'TODO text' it_behaves_like 'incorrect', 'todo text' it_behaves_like 'incorrect', 'UPDATE: text' it_behaves_like 'incorrect', 'UPDATE text' it_behaves_like 'incorrect', 'FOR LATER text' end context 'when no colon is required' do let(:colon) { false } it_behaves_like 'correct', 'TODO text' it_behaves_like 'correct', 'FIXME text' it_behaves_like 'correct', 'FOR LATER text' it_behaves_like 'incorrect', 'TODO: ' it_behaves_like 'incorrect', 'TODO ' it_behaves_like 'incorrect', 'TODO' it_behaves_like 'incorrect', 'TODOtext' it_behaves_like 'incorrect', 'TODO:text' it_behaves_like 'incorrect', 'TODO2 text' it_behaves_like 'incorrect', 'TODO: text' it_behaves_like 'incorrect', 'todo text' it_behaves_like 'incorrect', 'UPDATE: text' it_behaves_like 'incorrect', 'UPDATE text' it_behaves_like 'incorrect', 'FOR LATER: text' end context 'when there is duplication in the keywords' do context 'when the longer keyword is given first' do let(:keywords) { ['TODO LATER', 'TODO'] } it_behaves_like 'correct', 'TODO: text' it_behaves_like 'correct', 'TODO LATER: text' it_behaves_like 'incorrect', 'TODO text' it_behaves_like 'incorrect', 'TODO LATER text' end context 'when the shorter keyword is given first' do let(:keywords) { ['TODO', 'TODO LATER'] } it_behaves_like 'correct', 'TODO: text' it_behaves_like 'correct', 'TODO LATER: text' it_behaves_like 'incorrect', 'TODO text' it_behaves_like 'incorrect', 'TODO LATER text' 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/constant_definition_in_block_spec.rb
spec/rubocop/cop/lint/constant_definition_in_block_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ConstantDefinitionInBlock, :config do it 'does not register an offense for a top-level constant' do expect_no_offenses(<<~RUBY) FOO = 1 RUBY end it 'does not register an offense for a top-level constant followed by another statement' do expect_no_offenses(<<~RUBY) FOO = 1 bar RUBY end it 'registers an offense for a constant defined within a block' do expect_offense(<<~RUBY) describe do FOO = 1 ^^^^^^^ Do not define constants this way within a block. end RUBY end it 'registers an offense for a constant defined within a block followed by another statement' do expect_offense(<<~RUBY) describe do FOO = 1 ^^^^^^^ Do not define constants this way within a block. bar end RUBY end it 'does not register an offense for a top-level class' do expect_no_offenses(<<~RUBY) class Foo; end RUBY end it 'does not register an offense for a top-level class followed by another statement' do expect_no_offenses(<<~RUBY) class Foo; end bar RUBY end it 'registers an offense for a class defined within a block' do expect_offense(<<~RUBY) describe do class Foo; end ^^^^^^^^^^^^^^ Do not define constants this way within a block. end RUBY end it 'registers an offense for a class defined within a block followed by another statement' do expect_offense(<<~RUBY) describe do class Foo; end ^^^^^^^^^^^^^^ Do not define constants this way within a block. bar end RUBY end it 'registers an offense for a class defined within a numblock' do expect_offense(<<~RUBY) describe do class Foo; end ^^^^^^^^^^^^^^ Do not define constants this way within a block. _1 end RUBY end it 'does not register an offense for a top-level module' do expect_no_offenses(<<~RUBY) module Foo; end RUBY end it 'does not register an offense for a top-level module followed by another statement' do expect_no_offenses(<<~RUBY) module Foo; end bar RUBY end it 'registers an offense for a module defined within a block' do expect_offense(<<~RUBY) describe do module Foo; end ^^^^^^^^^^^^^^^ Do not define constants this way within a block. end RUBY end it 'registers an offense for a module defined within a block followed by another statement' do expect_offense(<<~RUBY) describe do module Foo; end ^^^^^^^^^^^^^^^ Do not define constants this way within a block. bar end RUBY end it 'registers an offense for a module defined within a numblock' do expect_offense(<<~RUBY) describe do module Foo; end ^^^^^^^^^^^^^^^ Do not define constants this way within a block. _1 end RUBY end it 'registers an offense for a module defined within an itblock', :ruby34 do expect_offense(<<~RUBY) describe do module Foo; end ^^^^^^^^^^^^^^^ Do not define constants this way within a block. it end RUBY end it 'does not register an offense for a constant with an explicit self scope' do expect_no_offenses(<<~RUBY) describe do self::FOO = 1 end RUBY end it 'does not register an offense for a constant with an explicit self scope followed by another statement' do expect_no_offenses(<<~RUBY) describe do self::FOO = 1 bar end RUBY end it 'does not register an offense for a constant with an explicit top-level scope' do expect_no_offenses(<<~RUBY) describe do ::FOO = 1 end RUBY end it 'does not register an offense for a constant with an explicit top-level scope followed by another statement' do expect_no_offenses(<<~RUBY) describe do ::FOO = 1 bar end RUBY end context 'when `AllowedMethods: [enums]`' do let(:cop_config) { { 'AllowedMethods' => ['enums'] } } it 'does not register an offense for a casign used within a block of `enums` method' do expect_no_offenses(<<~RUBY) class TestEnum < T::Enum enums do Foo = new("foo") end end RUBY end it 'does not register an offense for a class defined within a block of `enums` method' do expect_no_offenses(<<~RUBY) enums do class Foo end end RUBY end it 'does not register an offense for a module defined within a block of `enums` method' do expect_no_offenses(<<~RUBY) enums do module Foo end end RUBY end it 'does not register an offense for a module defined within a numblock of `enums` method' do expect_no_offenses(<<~RUBY) enums do module Foo end _1 end RUBY end it 'does not register an offense for a module defined within an itblock of `enums` method', :ruby34 do expect_no_offenses(<<~RUBY) enums do module Foo end it end RUBY end end context 'when `AllowedMethods: []`' do let(:cop_config) { { 'AllowedMethods' => [] } } it 'registers an offense for a casign used within a block of `enums` method' do expect_offense(<<~RUBY) class TestEnum < T::Enum enums do Foo = new("foo") ^^^^^^^^^^^^^^^^ Do not define constants this way within a block. end end RUBY end it 'registers an offense for a class defined within a block of `enums` method' do expect_offense(<<~RUBY) enums do class Foo ^^^^^^^^^ Do not define constants this way within a block. end end RUBY end it 'registers an offense for a module defined within a block of `enums` method' do expect_offense(<<~RUBY) enums do module Foo ^^^^^^^^^^ Do not define constants this way within a block. 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/lambda_without_literal_block_spec.rb
spec/rubocop/cop/lint/lambda_without_literal_block_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::LambdaWithoutLiteralBlock, :config do it 'registers and corrects an offense when using lambda with `&proc {}` block argument' do expect_offense(<<~RUBY) lambda(&proc { do_something }) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lambda without a literal block is deprecated; use the proc without lambda instead. RUBY expect_correction(<<~RUBY) proc { do_something } RUBY end it 'registers and corrects an offense when using lambda with `&Proc.new {}` block argument' do expect_offense(<<~RUBY) lambda(&Proc.new { do_something }) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lambda without a literal block is deprecated; use the proc without lambda instead. RUBY expect_correction(<<~RUBY) Proc.new { do_something } RUBY end it 'registers and corrects an offense when using lambda with a proc variable block argument' do expect_offense(<<~RUBY) pr = Proc.new { do_something } lambda(&pr) ^^^^^^^^^^^ lambda without a literal block is deprecated; use the proc without lambda instead. RUBY expect_correction(<<~RUBY) pr = Proc.new { do_something } pr RUBY end it 'does not register an offense when using lambda with a literal block' do expect_no_offenses(<<~RUBY) lambda { do_something } RUBY end it 'does not register an offense when using `lambda.call`' do expect_no_offenses(<<~RUBY) lambda.call RUBY end it 'does not register an offense when using lambda with a symbol proc' do expect_no_offenses(<<~RUBY) lambda(&:do_something) RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/else_layout_spec.rb
spec/rubocop/cop/lint/else_layout_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ElseLayout, :config do it 'registers an offense and corrects for expr on same line as else' do expect_offense(<<~RUBY) if something test else ala ^^^ Odd `else` layout detected. Did you mean to use `elsif`? something test end RUBY expect_correction(<<~RUBY) if something test else ala something test end RUBY end it 'registers an offense and corrects for the entire else body being on the same line without `then` single-line' do expect_offense(<<~RUBY) if something test else something_else ^^^^^^^^^^^^^^ Odd `else` layout detected. Did you mean to use `elsif`? end RUBY expect_correction(<<~RUBY) if something test else something_else end RUBY end it 'registers an offense for a part of `else` body being on the same line with `then` single-line' do expect_offense(<<~RUBY) if something then test else something_else ^^^^^^^^^^^^^^ Odd `else` layout detected. Did you mean to use `elsif`? other end RUBY expect_correction(<<~RUBY) if something then test else something_else other end RUBY end it 'does not register an offense for the single line `else` body being on the same line with `then` single-line' do expect_no_offenses(<<~RUBY) if something then test else something_else end RUBY end it 'accepts proper else' do expect_no_offenses(<<~RUBY) if something test else something test end RUBY end it 'registers an offense and corrects for elsifs' do expect_offense(<<~RUBY) if something test elsif something bala else ala ^^^ Odd `else` layout detected. Did you mean to use `elsif`? something test end RUBY expect_correction(<<~RUBY) if something test elsif something bala else ala something test end RUBY end it 'registers and corrects an offense when using multiple `elsif`s' do expect_offense(<<~RUBY) if condition_foo foo elsif condition_bar bar elsif condition_baz baz else qux ^^^ Odd `else` layout detected. Did you mean to use `elsif`? quux corge end RUBY expect_correction(<<~RUBY) if condition_foo foo elsif condition_bar bar elsif condition_baz baz else qux quux corge end RUBY end it 'accepts ternary ops' do expect_no_offenses('x ? a : b') end it 'accepts modifier forms' do expect_no_offenses('x if something') end it 'accepts empty braces' do expect_no_offenses(<<~RUBY) if something () else () end RUBY end it 'does not register an offense for an elsif with no body' do expect_no_offenses(<<~RUBY) if something foo elsif something_else end RUBY end it 'does not register an offense if the entire if is on a single line' do expect_no_offenses(<<~RUBY) if a then b else c end RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/empty_interpolation_spec.rb
spec/rubocop/cop/lint/empty_interpolation_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyInterpolation, :config do it 'registers an offense and corrects #{} in interpolation' do expect_offense(<<~'RUBY') "this is the #{}" ^^^ Empty interpolation detected. RUBY expect_correction(<<~RUBY) "this is the " RUBY end it 'registers an offense and corrects #{ } in interpolation' do expect_offense(<<~'RUBY') "this is the #{ }" ^^^^ Empty interpolation detected. RUBY expect_correction(<<~RUBY) "this is the " RUBY end it 'registers an offense and corrects #{\'\'} in interpolation' do expect_offense(<<~'RUBY') "this is the #{''}" ^^^^^ Empty interpolation detected. RUBY expect_correction(<<~RUBY) "this is the " RUBY end it 'registers an offense and corrects #{""} in interpolation' do expect_offense(<<~'RUBY') "this is the #{""}" ^^^^^ Empty interpolation detected. RUBY expect_correction(<<~RUBY) "this is the " RUBY end it 'registers an offense and corrects #{nil} in interpolation' do expect_offense(<<~'RUBY') "this is the #{nil}" ^^^^^^ Empty interpolation detected. RUBY expect_correction(<<~RUBY) "this is the " RUBY end it 'finds interpolations in string-like contexts' do expect_offense(<<~'RUBY') /regexp #{}/ ^^^ Empty interpolation detected. `backticks #{}` ^^^ Empty interpolation detected. :"symbol #{}" ^^^ Empty interpolation detected. RUBY end it 'accepts non-empty interpolation' do expect_no_offenses('"this is #{top} silly"') end it 'does not register an offense when using an integer inside interpolation' do expect_no_offenses(<<~'RUBY') "this is the #{1}" RUBY end it 'does not register an offense when using a boolean literal inside interpolation' do expect_no_offenses(<<~'RUBY') "this is the #{true}" RUBY end it 'does not register an offense for an empty string interpolation inside a `%W` literal' do expect_no_offenses(<<~'RUBY') %W[#{''} one two] RUBY end it 'does not register an offense for an empty string interpolation inside a `%I` literal' do expect_no_offenses(<<~'RUBY') %I[#{''} one two] RUBY end it 'registers an offense for an empty string interpolation inside an array' do expect_offense(<<~'RUBY') ["#{''}", one, two] ^^^^^ Empty interpolation detected. RUBY expect_correction(<<~RUBY) ["", one, two] 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_numeric_operation_spec.rb
spec/rubocop/cop/lint/useless_numeric_operation_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessNumericOperation, :config do it 'registers an offense when 0 is added to a variable' do expect_offense(<<~RUBY) x + 0 ^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x RUBY end it 'registers an offense when 0 is subtracted from a variable' do expect_offense(<<~RUBY) x - 0 ^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x RUBY end it 'registers an offense when a variable is multiplied by 1' do expect_offense(<<~RUBY) x * 1 ^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x RUBY end it 'registers an offense when a variable is divided by 1' do expect_offense(<<~RUBY) x / 1 ^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x RUBY end it 'registers an offense when a variable is raised to the power of 1' do expect_offense(<<~RUBY) x ** 1 ^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x RUBY end it 'registers an offense when a variable is set to itself plus zero via abbreviated assignment' do expect_offense(<<~RUBY) x += 0 ^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x = x RUBY end it 'registers an offense when a variable is set to itself minus zero via abbreviated assignment' do expect_offense(<<~RUBY) x -= 0 ^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x = x RUBY end it 'registers an offense when a variable is set to itself times one via abbreviated assignment' do expect_offense(<<~RUBY) x *= 1 ^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x = x RUBY end it 'registers an offense when a variable is set to itself divided by one via abbreviated assignment' do expect_offense(<<~RUBY) x /= 1 ^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x = x RUBY end it 'registers an offense when a variable is set to itself raised to the power of one via abbreviated assignment' do expect_offense(<<~RUBY) x **= 1 ^^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x = x RUBY end it 'registers an offense when calling `.+(0)`' do expect_offense(<<~RUBY) x.+(0) ^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x RUBY end it 'registers an offense when calling `&.+(0)`' do expect_offense(<<~RUBY) x&.+(0) ^^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x RUBY end it 'registers an offense when calling `.+(0)` in a chain' do expect_offense(<<~RUBY) x.+(0).bar ^^^^^^ Do not apply inconsequential numeric operations to variables. RUBY expect_correction(<<~RUBY) x.bar 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_defined_spec.rb
spec/rubocop/cop/lint/useless_defined_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessDefined, :config do it 'registers an offense when using `defined?` with a string argument' do expect_offense(<<~RUBY) defined?("FooBar") ^^^^^^^^^^^^^^^^^^ Calling `defined?` with a string argument will always return a truthy value. RUBY end it 'registers an offense when using `defined?` with interpolation' do expect_offense(<<~'RUBY') defined?("Foo#{bar}") ^^^^^^^^^^^^^^^^^^^^^ Calling `defined?` with a string argument will always return a truthy value. RUBY end it 'registers an offense when using `defined?` with a symbol' do expect_offense(<<~RUBY) defined?(:FooBar) ^^^^^^^^^^^^^^^^^ Calling `defined?` with a symbol argument will always return a truthy value. RUBY end it 'registers an offense when using `defined?` an interpolated symbol' do expect_offense(<<~'RUBY') defined?(:"Foo#{bar}") ^^^^^^^^^^^^^^^^^^^^^^ Calling `defined?` with a symbol argument will always return a truthy value. RUBY end it 'does not register an offense when using `defined?` with a constant' do expect_no_offenses(<<~RUBY) defined?(FooBar) RUBY end it 'does not register an offense when using `defined?` with a method' do expect_no_offenses(<<~RUBY) defined?(foo_bar) RUBY end it 'does not register an offense when calling a method on a symbol' do expect_no_offenses(<<~RUBY) defined?(:foo.to_proc) RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/redundant_regexp_quantifiers_spec.rb
spec/rubocop/cop/lint/redundant_regexp_quantifiers_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantRegexpQuantifiers, :config do # silence Ruby's own warnings for the tested redundant quantifiers around { |example| RuboCop::Util.silence_warnings(&example) } context 'with non-redundant quantifiers' do it 'does not register an offense' do expect_no_offenses('foo = /(?:ab+)+/') expect_no_offenses('foo = /(?:a|b+)+/') expect_no_offenses('foo = /(?:a+|b)+/') expect_no_offenses('foo = /(?:a+|b)+/') expect_no_offenses('foo = /(?:\d\D+)+/') # Quantifiers that apply to capture groups or their contents are not redundant. # Merging them with other quantifiers could affect the (final) captured value. expect_no_offenses('foo = /(a+)+/') expect_no_offenses('foo = /(?:(a+))+/') expect_no_offenses('foo = /(?:(a)+)+/') end end context 'with nested possessive quantifiers' do it 'does not register an offense' do expect_no_offenses('foo = /(?:a++)+/') expect_no_offenses('foo = /(?:a+)++/') end end context 'with nested reluctant quantifiers' do it 'does not register an offense' do expect_no_offenses('foo = /(?:a+?)+/') expect_no_offenses('foo = /(?:a+)+?/') end end context 'with nested interval quantifiers' do it 'does not register an offense' do expect_no_offenses('foo = /(?:a{3,4})+/') expect_no_offenses('foo = /(?:a+){3,4}/') end end context 'with duplicate "+" quantifiers' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?:a+)+/ ^^^ Replace redundant quantifiers `+` and `+` with a single `+`. RUBY expect_correction(<<~RUBY) foo = /(?:a+)/ RUBY end end context 'with duplicate "*" quantifiers' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?:a*)*/ ^^^ Replace redundant quantifiers `*` and `*` with a single `*`. RUBY expect_correction(<<~RUBY) foo = /(?:a*)/ RUBY end end context 'with duplicate "?" quantifiers' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?:a?)?/ ^^^ Replace redundant quantifiers `?` and `?` with a single `?`. RUBY expect_correction(<<~RUBY) foo = /(?:a?)/ RUBY end end context 'with any other redundant combination of greedy quantifiers' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?:a+)?/ ^^^ Replace redundant quantifiers `+` and `?` with a single `*`. RUBY expect_correction(<<~RUBY) foo = /(?:a*)/ RUBY end end context 'with nested interval quantifiers that can be normalized' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?:a{1,}){,1}/ ^^^^^^^^^ Replace redundant quantifiers `{1,}` and `{,1}` with a single `*`. RUBY expect_correction(<<~RUBY) foo = /(?:a*)/ RUBY end end context 'with redundant quantifiers applied to character sets' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?:[abc]+)+/ ^^^ Replace redundant quantifiers `+` and `+` with a single `+`. RUBY expect_correction(<<~RUBY) foo = /(?:[abc]+)/ RUBY end end context 'with redundant quantifiers in x-mode' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?: a ? ) + /x ^^^^^ Replace redundant quantifiers `?` and `+` with a single `*`. RUBY expect_correction(<<~RUBY) foo = /(?: a * ) /x RUBY end end context 'with non-redundant quantifiers and interpolation in x-mode' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') foo = /(?:a*#{interpolation})?/x RUBY end end context 'with deeply nested redundant quantifiers' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /(?:(?:(?:(?:a)?))+)/ ^^^^ Replace redundant quantifiers `?` and `+` with a single `*`. RUBY expect_correction(<<~RUBY) foo = /(?:(?:(?:(?:a)*)))/ RUBY end end context 'with multiple redundant quantifiers' do it 'registers offenses and corrects with leading optional quantifier' do expect_offense(<<~RUBY) foo = /(?:(?:a?)+)+/ ^^^ Replace redundant quantifiers `+` and `+` with a single `+`. ^^^^^ Replace redundant quantifiers `?` and `+` with a single `*`. RUBY expect_correction(<<~RUBY) foo = /(?:(?:a*))/ RUBY end it 'registers offenses and corrects with interspersed optional quantifier' do expect_offense(<<~RUBY) foo = /(?:(?:a+)?)+/ ^^^ Replace redundant quantifiers `?` and `+` with a single `*`. ^^^^^ Replace redundant quantifiers `+` and `+` with a single `+`. RUBY expect_correction(<<~RUBY) foo = /(?:(?:a*))/ RUBY end it 'registers offenses and corrects with trailing optional quantifier' do expect_offense(<<~RUBY) foo = /(?:(?:a+)+)?/ ^^^ Replace redundant quantifiers `+` and `?` with a single `*`. ^^^^^ Replace redundant quantifiers `+` and `?` with a single `*`. RUBY expect_correction(<<~RUBY) foo = /(?:(?:a*))/ RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/safe_navigation_with_empty_spec.rb
spec/rubocop/cop/lint/safe_navigation_with_empty_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SafeNavigationWithEmpty, :config do context 'in a conditional' do it 'registers an offense and corrects on `&.empty?`' do expect_offense(<<~RUBY) return unless foo&.empty? ^^^^^^^^^^^ Avoid calling `empty?` with the safe navigation operator in conditionals. RUBY expect_correction(<<~RUBY) return unless foo && foo.empty? RUBY end it 'does not register an offense on `.empty?`' do expect_no_offenses(<<~RUBY) return if foo.empty? RUBY end end context 'outside a conditional' do it 'registers no offense' do expect_no_offenses(<<~RUBY) bar = foo&.empty? 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/unreachable_loop_spec.rb
spec/rubocop/cop/lint/unreachable_loop_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnreachableLoop, :config do context 'without preceding continue statements' do it 'registers an offense when using `break`' do expect_offense(<<~RUBY) while x > 0 ^^^^^^^^^^^ This loop will have at most one iteration. x += 1 break end RUBY end it 'registers an offense when using `if-else` with all break branches' do expect_offense(<<~RUBY) while x > 0 ^^^^^^^^^^^ This loop will have at most one iteration. if condition break else raise MyError end end RUBY end it 'does not register an offense when using `if` without `else`' do expect_no_offenses(<<~RUBY) while x > 0 if condition break elsif other_condition raise MyError end end RUBY end it 'does not register an offense when using `if-elsif-else` and not all branches are breaking' do expect_no_offenses(<<~RUBY) while x > 0 if condition break elsif other_condition do_something else raise MyError end end RUBY end it 'registers an offense when using `case-when-else` with all break branches' do expect_offense(<<~RUBY) while x > 0 ^^^^^^^^^^^ This loop will have at most one iteration. case x when 1 break else raise MyError end end RUBY end it 'does not register an offense when using `case` without `else`' do expect_no_offenses(<<~RUBY) while x > 0 case x when 1 break end end RUBY end it 'does not register an offense when using `case-when-else` and not all branches are breaking' do expect_no_offenses(<<~RUBY) while x > 0 case x when 1 break when 2 do_something else raise MyError end end RUBY end it 'registers an offense when using `case-in-else` with all break branches' do expect_offense(<<~RUBY) while x > 0 ^^^^^^^^^^^ This loop will have at most one iteration. case x in 1 break else raise MyError end end RUBY end it 'does not register an offense when using `case` match without `else`' do expect_no_offenses(<<~RUBY) while x > 0 case x in 1 break end end RUBY end it 'does not register an offense when using `case-in-else` and not all branches are breaking' do expect_no_offenses(<<~RUBY) while x > 0 case x in 1 break in 2 do_something else raise MyError end end RUBY end end context 'with preceding continue statements' do it 'does not register an offense when using `break`' do expect_no_offenses(<<~RUBY) while x > 0 next if x.odd? x += 1 break end RUBY end it 'does not register an offense when using `if-else` with all break branches' do expect_no_offenses(<<~RUBY) while x > 0 next if x.odd? if condition break else raise MyError end end RUBY end it 'does not register an offense when using `case-when-else` with all break branches' do expect_no_offenses(<<~RUBY) while x > 0 redo if x.odd? case x when 1 break else raise MyError end end RUBY end it 'does not register an offense when using `case-in-else` with all break branches' do expect_no_offenses(<<~RUBY) while x > 0 redo if x.odd? case x in 1 break else raise MyError end end RUBY end end context 'with an enumerator method' do context 'as the last item in a method chain' do it 'registers an offense' do expect_offense(<<~RUBY) string.split('-').map { raise StandardError } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. RUBY end end context 'not chained' do it 'registers an offense' do expect_offense(<<~RUBY) string.map { raise StandardError } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. RUBY end end context 'in the middle of a method chain' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) exactly(2).times.with(x) { raise StandardError } RUBY end end end context 'with AllowedPatterns' do let(:cop_config) { { 'AllowedPatterns' => [/exactly\(\d+\)\.times/] } } context 'with an ignored method call' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) exactly(2).times { raise StandardError } RUBY end end context 'with a non ignored method call' do it 'registers an offense' do expect_offense(<<~RUBY) 2.times { raise StandardError } ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. RUBY end context 'Ruby 2.7', :ruby27 do it 'registers an offense' do expect_offense(<<~RUBY) 2.times { raise _1 } ^^^^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. RUBY end end context 'Ruby 3.4', :ruby34 do it 'registers an offense' do expect_offense(<<~RUBY) 2.times { raise it } ^^^^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. RUBY end end end end it 'handles inner loops' do expect_offense(<<~RUBY) until x > 0 ^^^^^^^^^^^ This loop will have at most one iteration. items.each do |item| next if item.odd? break end if x > 0 break some_value else raise MyError end loop do ^^^^^^^ This loop will have at most one iteration. case y when 1 return something when 2 break else throw :exit end end end RUBY end it 'does not register an offense when branch includes continue statement preceding break statement' do expect_no_offenses(<<~RUBY) while x > 0 if y next if something break else break end end RUBY end it 'does not register an offense when using `return do_something(value) || next` in a loop' do expect_no_offenses(<<~RUBY) [nil, nil, 42].each do |value| return do_something(value) || next end RUBY end it 'does not register an offense when using `return do_something(value) || redo` in a loop' do expect_no_offenses(<<~RUBY) [nil, nil, 42].each do |value| return do_something(value) || redo end RUBY end it 'registers an offense when using `return do_something(value) || break` in a loop' do expect_offense(<<~RUBY) [nil, nil, 42].each do |value| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. return do_something(value) || break end RUBY end context 'Ruby 2.7', :ruby27 do it 'registers an offense when using `return do_something(value) || break` in a loop' do expect_offense(<<~RUBY) [1, 2, 3].each do ^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. return _1.odd? || break end RUBY end end context 'Ruby 3.4', :ruby34 do it 'registers an offense when using `return do_something(value) || break` in a loop' do expect_offense(<<~RUBY) [1, 2, 3].each do ^^^^^^^^^^^^^^^^^ This loop will have at most one iteration. return it.odd? || break 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/script_permission_spec.rb
spec/rubocop/cop/lint/script_permission_spec.rb
# frozen_string_literal: true # rubocop:disable Style/NumericLiteralPrefix RSpec.describe RuboCop::Cop::Lint::ScriptPermission, :config do subject(:cop) { described_class.new(config, options) } let(:options) { nil } let(:file) { Tempfile.new('') } let(:filename) { file.path.split('/').last } let(:source) { '#!/usr/bin/ruby' } after do file.close file.unlink end context 'with file permission 0644' do before do File.write(file.path, source) FileUtils.chmod(0644, file.path) end if RuboCop::Platform.windows? context 'Windows' do it 'allows any file permissions' do expect_no_offenses(<<~RUBY, file) #!/usr/bin/ruby RUBY end end else it 'registers an offense for script permission' do expect_offense(<<~RUBY, file) #!/usr/bin/ruby ^^^^^^^^^^^^^^^ Script file #{filename} doesn't have execute permission. RUBY expect_no_corrections expect(file.stat).to be_executable end context 'if autocorrection is off' do # very dirty hack def _investigate(cop, processed_source) cop.instance_variable_get(:@options)[:autocorrect] = false super end it 'leaves the file intact' do expect_offense(<<~RUBY, file) #!/usr/bin/ruby ^^^^^^^^^^^^^^^ Script file #{filename} doesn't have execute permission. RUBY expect_no_corrections expect(file.stat).not_to be_executable end end end end context 'with file permission 0755' do before { FileUtils.chmod(0755, file.path) } it 'accepts with shebang line' do File.write(file.path, source) expect_no_offenses(file.read, file) end it 'accepts without shebang line' do File.write(file.path, 'puts "hello"') expect_no_offenses(file.read, file) end it 'accepts with blank' do File.write(file.path, '') expect_no_offenses(file.read, file) end end context 'with stdin' do let(:options) { { stdin: '' } } it 'skips investigation' do expect_no_offenses(source) end end end # rubocop:enable Style/NumericLiteralPrefix
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/flip_flop_spec.rb
spec/rubocop/cop/lint/flip_flop_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::FlipFlop, :config do it 'registers an offense for inclusive flip-flops' do expect_offense(<<~RUBY) DATA.each_line do |line| print line if (line =~ /begin/)..(line =~ /end/) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid the use of flip-flop operators. end RUBY end it 'registers an offense for exclusive flip-flops' do expect_offense(<<~RUBY) DATA.each_line do |line| print line if (line =~ /begin/)...(line =~ /end/) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid the use of flip-flop operators. 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/incompatible_io_select_with_fiber_scheduler_spec.rb
spec/rubocop/cop/lint/incompatible_io_select_with_fiber_scheduler_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::IncompatibleIoSelectWithFiberScheduler, :config do it 'registers and corrects an offense when using `IO.select` with single read argument' do expect_offense(<<~RUBY) IO.select([io], [], []) ^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_readable` instead of `IO.select([io], [], [])`. RUBY expect_correction(<<~RUBY) io.wait_readable RUBY end it 'registers and corrects an offense when using `IO.select` with single read argument and specify the first argument only' do expect_offense(<<~RUBY) IO.select([io]) ^^^^^^^^^^^^^^^ Use `io.wait_readable` instead of `IO.select([io])`. RUBY expect_correction(<<~RUBY) io.wait_readable RUBY end it 'registers and corrects an offense when using `IO.select` with single read and timeout arguments' do expect_offense(<<~RUBY) IO.select([io], [], [], timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_readable(timeout)` instead of `IO.select([io], [], [], timeout)`. RUBY expect_correction(<<~RUBY) io.wait_readable(timeout) RUBY end it 'registers and corrects an offense when using `::IO.select` with single read argument' do expect_offense(<<~RUBY) ::IO.select([io], [], []) ^^^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_readable` instead of `::IO.select([io], [], [])`. RUBY expect_correction(<<~RUBY) io.wait_readable RUBY end it 'registers and corrects an offense when using `::IO.select` with single read and timeout arguments' do expect_offense(<<~RUBY) ::IO.select([io], [], [], timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_readable(timeout)` instead of `::IO.select([io], [], [], timeout)`. RUBY expect_correction(<<~RUBY) io.wait_readable(timeout) RUBY end it 'registers and corrects an offense when using `IO.select` with single read, `nil`, and timeout arguments' do expect_offense(<<~RUBY) IO.select([io], nil, nil, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_readable(timeout)` instead of `IO.select([io], nil, nil, timeout)`. RUBY expect_correction(<<~RUBY) io.wait_readable(timeout) RUBY end it 'registers and corrects an offense when using `IO.select` with single write, `nil`, and timeout arguments' do expect_offense(<<~RUBY) IO.select(nil, [io], nil, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_writable(timeout)` instead of `IO.select(nil, [io], nil, timeout)`. RUBY expect_correction(<<~RUBY) io.wait_writable(timeout) RUBY end it 'registers and corrects an offense when using `IO.select` with single write argument' do expect_offense(<<~RUBY) IO.select([], [io], []) ^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_writable` instead of `IO.select([], [io], [])`. RUBY expect_correction(<<~RUBY) io.wait_writable RUBY end it 'registers and corrects an offense when using `IO.select` with single write and timeout arguments' do expect_offense(<<~RUBY) IO.select([], [io], [], timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `io.wait_writable(timeout)` instead of `IO.select([], [io], [], timeout)`. RUBY expect_correction(<<~RUBY) io.wait_writable(timeout) RUBY end it 'registers and corrects an offense when using `IO.select` with single read as `self` and timeout arguments' do expect_offense(<<~RUBY) IO.select([self], nil, nil, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `self.wait_readable(timeout)` instead of `IO.select([self], nil, nil, timeout)`. RUBY expect_correction(<<~RUBY) self.wait_readable(timeout) RUBY end it 'registers and corrects an offense when using `IO.select` with single write as `self` and timeout arguments' do expect_offense(<<~RUBY) IO.select(nil, [self], nil, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `self.wait_writable(timeout)` instead of `IO.select(nil, [self], nil, timeout)`. RUBY expect_correction(<<~RUBY) self.wait_writable(timeout) RUBY end it 'registers an offense when using `IO.select` with read argument and using return value but does not autocorrect' do expect_offense(<<~RUBY) rs, _ = IO.select([rp], []) ^^^^^^^^^^^^^^^^^^^ Use `rp.wait_readable` instead of `IO.select([rp], [])`. RUBY expect_no_corrections end it 'registers an offense when using `IO.select` with write argument and using return value but does not autocorrect' do expect_offense(<<~RUBY) _, ws = IO.select([], [wp]) ^^^^^^^^^^^^^^^^^^^ Use `wp.wait_writable` instead of `IO.select([], [wp])`. RUBY expect_no_corrections end it 'does not register an offense when using `IO.select` with multiple read arguments' do expect_no_offenses(<<~RUBY) IO.select([foo, bar], [], []) RUBY end it 'registers and corrects an offense when using `IO.select` with multiple read argument and specify the first argument only' do expect_no_offenses(<<~RUBY) IO.select([foo, bar]) RUBY end it 'does not register an offense when using `IO.select` with multiple write arguments' do expect_no_offenses(<<~RUBY) IO.select([], [foo, bar], []) RUBY end it 'does not register an offense when using `IO.select` with read and write arguments' do expect_no_offenses(<<~RUBY) IO.select([rp], [wp], []) RUBY end it 'does not register an offense when using `IO.select` with read and excepts arguments' do expect_no_offenses(<<~RUBY) IO.select([rp], [], [excepts]) RUBY end it 'does not register an offense when using `Enumerable#select`' do expect_no_offenses(<<~RUBY) collection.select { |item| item.do_something? } RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/void_spec.rb
spec/rubocop/cop/lint/void_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::Void, :config do described_class::BINARY_OPERATORS.each do |op| it "registers an offense for void op #{op} if not on last line" do expect_offense(<<~RUBY, op: op) a %{op} b ^{op} Operator `#{op}` used in void context. a %{op} b ^{op} Operator `#{op}` used in void context. a %{op} b RUBY expect_correction(<<~RUBY) a b a b a #{op} b RUBY end it "accepts void op #{op} if on last line" do expect_no_offenses(<<~RUBY) something a #{op} b RUBY end it "accepts void op #{op} by itself without a begin block" do expect_no_offenses("a #{op} b") end it "accepts void op #{op} method call without arguments unless it is on the last line" do expect_no_offenses(<<~RUBY) a.#{op} something RUBY end it "accepts void op #{op} safe navigation method call without arguments unless it is on the last line" do expect_no_offenses(<<~RUBY) a&.#{op} something RUBY end it "registers an offense for parenthesized void op #{op} if not on last line" do expect_offense(<<~RUBY, op: op) (a %{op} b) ^{op} Operator `#{op}` used in void context. ((a %{op} b)) ^{op} Operator `#{op}` used in void context. (((a %{op} b))) RUBY # NOTE: Redundant parentheses in `(var)` are left to `Style/RedundantParentheses` to fix. expect_correction(<<~RUBY) (a b) ((a b)) (((a #{op} b))) RUBY end it "accepts parenthesized void op #{op} if on last line" do expect_no_offenses(<<~RUBY) something (a #{op} b) RUBY end it "accepts parenthesized void op #{op} by itself without a begin block" do expect_no_offenses("(a #{op} b)") end it 'handles methods called by dot' do expect_offense(<<~RUBY, op: op) a.%{op}(b) ^{op} Operator `#{op}` used in void context. nil RUBY expect_correction(<<~RUBY) a (b) nil RUBY end it 'handles methods called by dot with safe navigation' do expect_offense(<<~RUBY, op: op) a&.%{op}(b) ^{op} Operator `#{op}` used in void context. nil RUBY expect_correction(<<~RUBY) a (b) nil RUBY end end sign_unary_operators = %i[+ -] other_unary_operators = %i[~ !] unary_operators = sign_unary_operators + other_unary_operators sign_unary_operators.each do |op| it "registers an offense for void sign op #{op} if not on last line" do expect_offense(<<~RUBY, op: op) %{op}b ^{op} Operator `#{op}@` used in void context. %{op}b ^{op} Operator `#{op}@` used in void context. %{op}b RUBY expect_correction(<<~RUBY) b b #{op}b RUBY end end other_unary_operators.each do |op| it "registers an offense for void unary op #{op} if not on last line" do expect_offense(<<~RUBY, op: op) %{op}b ^{op} Operator `#{op}` used in void context. %{op}b ^{op} Operator `#{op}` used in void context. %{op}b RUBY expect_correction(<<~RUBY) b b #{op}b RUBY end it "registers an offense for void unary op #{op} with dot" do expect_offense(<<~RUBY, op: op) b.%{op} ^{op} Operator `#{op}` used in void context. b.%{op} RUBY expect_correction(<<~RUBY) b b.#{op} RUBY end it "registers an offense for void unary op #{op} with dot with safe navigation" do expect_offense(<<~RUBY, op: op) b&.%{op} ^{op} Operator `#{op}` used in void context. b&.%{op} RUBY expect_correction(<<~RUBY) b b&.#{op} RUBY end end unary_operators.each do |op| it "accepts void unary op #{op} if on last line" do expect_no_offenses(<<~RUBY) something #{op}b RUBY end it "accepts void unary op #{op} by itself without a begin block" do expect_no_offenses("#{op}b") end end %w[var @var @@var $var].each do |var| it "registers an offense for void var #{var} if not on last line" do expect_offense(<<~RUBY, var: var) %{var} = 5 %{var} ^{var} Variable `#{var}` used in void context. top RUBY expect_correction(<<~RUBY) #{var} = 5 top RUBY end it "registers an offense for void var #{var} with guard clause if not on last line" do expect_offense(<<~RUBY, var: var) %{var} = 5 %{var} unless condition ^{var} Variable `#{var}` used in void context. top RUBY # `var unless condition` might indicate missing `return` in `return var unless condition`, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end it "registers an offense for void var #{var} inside unless block if not on last line" do expect_offense(<<~RUBY, var: var) %{var} = 5 unless condition %{var} ^{var} Variable `#{var}` used in void context. end top RUBY # `unless condition; var end` might indicate missing `return` or assignment, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end it "registers an offense for void var #{var} in ternary if not on last line" do expect_offense(<<~RUBY, var: var) %{var} = 5 condition ? %{var} : nil ^{var} Variable `#{var}` used in void context. top RUBY # `condition ? var : nil` might indicate missing `return` or assignment, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end end it 'registers an offense for void constant `CONST` if not on last line' do expect_offense(<<~RUBY) CONST = 5 CONST ^^^^^ Constant `CONST` used in void context. top RUBY expect_correction(<<~RUBY) CONST = 5 top RUBY end it 'registers an offense for void constant `CONST` with guard condition if not on last line' do expect_offense(<<~RUBY) CONST = 5 CONST unless condition ^^^^^ Constant `CONST` used in void context. top RUBY # `CONST unless condition` might indicate missing `return` in `return CONST unless condition`, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end it 'registers an offense for void constant `CONST` within conditional if not on last line' do expect_offense(<<~RUBY) CONST = 5 unless condition CONST ^^^^^ Constant `CONST` used in void context. end top RUBY # `unless condition; CONST end` might indicate missing `return` or assignment, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end it 'registers an offense for void constant `CONST` within ternary if not on last line' do expect_offense(<<~RUBY) CONST = 5 condition ? CONST : nil ^^^^^ Constant `CONST` used in void context. top RUBY # `condition ? CONST : ...` might indicate missing `return` or assignment, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end %w(1 2.0 :test /test/ [1] {}).each do |lit| it "registers an offense for void lit #{lit} if not on last line" do expect_offense(<<~RUBY, lit: lit) %{lit} ^{lit} Literal `#{lit}` used in void context. top RUBY expect_correction(<<~RUBY) top RUBY end it "registers an offense for void lit #{lit} with guard condition if not on last line" do expect_offense(<<~RUBY, lit: lit) %{lit} unless condition ^{lit} Literal `#{lit}` used in void context. top RUBY # `42 unless condition` might indicate missing `return` in `return 42 unless condition`, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end it "registers an offense for void lit #{lit} within conditional if not on last line" do expect_offense(<<~RUBY, lit: lit) unless condition %{lit} ^{lit} Literal `#{lit}` used in void context. end top RUBY # `unless condition; 42 end` might indicate missing `return` or assignment, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end it "registers an offense for void lit #{lit} within ternary if not on last line" do expect_offense(<<~RUBY, lit: lit) condition ? %{lit} : nil ^{lit} Literal `#{lit}` used in void context. top RUBY # `condition ? 42 : ...` might indicate missing `return` or assignment, # so for convenience, the code will not be autocorrected by deletion. expect_no_corrections end end it 'registers an offense for void `self` if not on last line' do expect_offense(<<~RUBY) self; top ^^^^ `self` used in void context. RUBY expect_correction(<<~RUBY) ; top RUBY end it 'registers an offense for void `defined?` if not on last line' do expect_offense(<<~RUBY) defined?(x) ^^^^^^^^^^^ `defined?(x)` used in void context. top RUBY expect_correction(<<~RUBY) top RUBY end it 'registers an offense for void `-> { bar }` if not on last line' do expect_offense(<<~RUBY) def foo -> { bar } ^^^^^^^^^^ `-> { bar }` used in void context. top end RUBY expect_correction(<<~RUBY) def foo top end RUBY end it 'does not register an offense for void `-> { bar }` if on last line' do expect_no_offenses(<<~RUBY) def foo top -> { bar } end RUBY end it 'does not register an offense for void `-> { bar }.call` if not on last line' do expect_no_offenses(<<~RUBY) def foo -> { bar }.call top end RUBY end it 'registers an offense for void `lambda { bar }` if not on last line' do expect_offense(<<~RUBY) def foo lambda { bar } ^^^^^^^^^^^^^^ `lambda { bar }` used in void context. top end RUBY expect_correction(<<~RUBY) def foo top end RUBY end it 'does not register an offense for void `lambda { bar }` if on last line' do expect_no_offenses(<<~RUBY) def foo top lambda { bar } end RUBY end it 'does not register an offense for void `lambda { bar }.call` if not on last line' do expect_no_offenses(<<~RUBY) def foo lambda { bar }.call top end RUBY end it 'registers an offense for void `proc { bar }` if not on last line' do expect_offense(<<~RUBY) def foo proc { bar } ^^^^^^^^^^^^ `proc { bar }` used in void context. top end RUBY expect_correction(<<~RUBY) def foo top end RUBY end it 'does not register an offense for void `proc { bar }` if on last line' do expect_no_offenses(<<~RUBY) def foo top proc { bar } end RUBY end it 'does not register an offense for void `proc { bar }.call` if not on last line' do expect_no_offenses(<<~RUBY) def foo proc { bar }.call top end RUBY end it 'registers an offense for void `Proc.new { bar }` if not on last line' do expect_offense(<<~RUBY) def foo Proc.new { bar } ^^^^^^^^^^^^^^^^ `Proc.new { bar }` used in void context. top end RUBY expect_correction(<<~RUBY) def foo top end RUBY end it 'does not register an offense for void `Proc.new { bar }` if on last line' do expect_no_offenses(<<~RUBY) def foo top Proc.new { bar } end RUBY end it 'does not register an offense for void `Proc.new { bar }.call` if not on last line' do expect_no_offenses(<<~RUBY) def foo Proc.new { bar }.call top end RUBY end context 'when checking for methods with no side effects' do let(:config) do RuboCop::Config.new('Lint/Void' => { 'CheckForMethodsWithNoSideEffects' => true }) end it 'registers an offense for nonmutating method that takes a block' do expect_offense(<<~RUBY) [1,2,3].collect do |n| ^^^^^^^^^^^^^^^^^^^^^^ Method `#collect` used in void context. Did you mean `#each`? n.to_s end "done" RUBY expect_correction(<<~RUBY) [1,2,3].each do |n| n.to_s end "done" RUBY end context 'Ruby 2.7', :ruby27 do it 'registers an offense for nonmutating method that takes a numbered parameter block' do expect_offense(<<~RUBY) [1,2,3].map do ^^^^^^^^^^^^^^ Method `#map` used in void context. Did you mean `#each`? _1.to_s end "done" RUBY expect_correction(<<~RUBY) [1,2,3].each do _1.to_s end "done" RUBY end end context 'Ruby 3.4', :ruby34 do it 'registers an offense for nonmutating method that takes an `it` parameter block' do expect_offense(<<~RUBY) [1,2,3].map do ^^^^^^^^^^^^^^ Method `#map` used in void context. Did you mean `#each`? it.to_s end "done" RUBY expect_correction(<<~RUBY) [1,2,3].each do it.to_s end "done" RUBY end end it 'registers an offense if not on last line' do expect_offense(<<~RUBY) x.sort ^^^^^^ Method `#sort` used in void context. Did you mean `#sort!`? top(x) RUBY expect_correction(<<~RUBY) x.sort! top(x) RUBY end it 'registers an offense for chained methods' do expect_offense(<<~RUBY) x.sort.flatten ^^^^^^^^^^^^^^ Method `#flatten` used in void context. Did you mean `#flatten!`? top(x) RUBY expect_correction(<<~RUBY) x.sort.flatten! top(x) RUBY end it 'does not register an offense assigning variable' do expect_no_offenses(<<~RUBY) foo = bar baz RUBY end it 'does not register an offense when using a method definition' do expect_no_offenses(<<~RUBY) def merge end 42 RUBY end end context 'when not checking for methods with no side effects' do let(:config) do RuboCop::Config.new('Lint/Void' => { 'CheckForMethodsWithNoSideEffects' => false }) end it 'does not register an offense for void nonmutating methods' do expect_no_offenses(<<~RUBY) x.sort top(x) RUBY end end it 'does not register an offense for an array literal that includes non-literal elements in a method definition' do expect_no_offenses(<<~RUBY) def something [foo, bar] baz end RUBY end it 'does not register an offense for a nested array literal that includes non-literal elements in a method definition' do expect_no_offenses(<<~RUBY) def something [1, 2, [foo, bar]] baz end RUBY end it 'registers an offense for an array literal composed entirely of literals in a method definition' do expect_offense(<<~RUBY) def something [1, 2] ^^^^^^ Literal `[1, 2]` used in void context. baz end RUBY end it 'registers an offense for a nested array literal composed entirely of literals in a method definition' do expect_offense(<<~RUBY) def something [1, 2, [3]] ^^^^^^^^^^^ Literal `[1, 2, [3]]` used in void context. baz end RUBY end it 'registers an offense for a frozen literal in a method definition' do expect_offense(<<~RUBY) def something 'foo'.freeze ^^^^^^^^^^^^ Literal `'foo'.freeze` used in void context. baz end RUBY end it 'registers an offense for a literal frozen via safe navigation in a method definition' do expect_offense(<<~RUBY) def something 'foo'&.freeze ^^^^^^^^^^^^^ Literal `'foo'&.freeze` used in void context. baz end RUBY end it 'does not register an offense for frozen non-literal in a method definition' do expect_no_offenses(<<~RUBY) def something foo.freeze baz end RUBY end it 'registers an offense for a nested array literal composed of frozen and unfrozen literals in a method definition' do expect_offense(<<~RUBY) def something [1, ['foo'.freeze]] ^^^^^^^^^^^^^^^^^^^ Literal `[1, ['foo'.freeze]]` used in void context. baz end RUBY end it 'does not register an offense for a nested array literal that includes frozen non-literal value elements in a method definition' do expect_no_offenses(<<~RUBY) def something [1, [foo.freeze]] baz end RUBY end it 'does not register an offense for a hash literal that includes non-literal value elements in a method definition' do expect_no_offenses(<<~RUBY) def something {k1: foo, k2: bar} baz end RUBY end it 'does not register an offense for a nested hash literal that includes non-literal value elements in a method definition' do expect_no_offenses(<<~RUBY) def something {k0: {k1: foo, k2: bar}} baz end RUBY end it 'does not register an offense for a hash literal that includes non-literal key elements in a method definition' do expect_no_offenses(<<~RUBY) def something {foo => 1, bar => 2} baz end RUBY end it 'does not register an offense for a nested hash literal that includes non-literal key elements in a method definition' do expect_no_offenses(<<~RUBY) def something {foo: 1, bar: {baz => 2}} baz end RUBY end it 'registers an offense for a hash literal composed entirely of literals in a method definition' do expect_offense(<<~RUBY) def something {k1: 1, k2: 2} ^^^^^^^^^^^^^^ Literal `{k1: 1, k2: 2}` used in void context. baz end RUBY expect_correction(<<~RUBY) def something baz end RUBY end it 'registers an offense for a nested hash literal composed entirely of literals in a method definition' do expect_offense(<<~RUBY) def something {x: {k1: 1, k2: 2}} ^^^^^^^^^^^^^^^^^^^ Literal `{x: {k1: 1, k2: 2}}` used in void context. baz end RUBY expect_correction(<<~RUBY) def something baz end RUBY end it 'does not register an offense for a hash literal that includes array literal key within non-literal elements in a method definition' do expect_no_offenses(<<~RUBY) def something {[foo, bar] => :foo} baz end RUBY end it 'registers an offense for a hash literal that includes array literal key within literal elements in a method definition' do expect_offense(<<~RUBY) def something {[1, 2] => :foo} ^^^^^^^^^^^^^^^^ Literal `{[1, 2] => :foo}` used in void context. baz end RUBY end it 'registers an offense for void literal in a method definition' do expect_offense(<<~RUBY) def something 42 ^^ Literal `42` used in void context. 42 end RUBY expect_correction(<<~RUBY) def something 42 end RUBY end it 'registers two offenses for void literals in an initialize method' do expect_offense(<<~RUBY) def initialize 42 ^^ Literal `42` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) def initialize end RUBY end it 'registers two offenses for void literals in a setter method' do expect_offense(<<~RUBY) def foo=(rhs) 42 ^^ Literal `42` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_no_corrections end it 'registers two offenses for void literals in a class setter method' do expect_offense(<<~RUBY) def self.foo=(rhs) 42 ^^ Literal `42` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_no_corrections end it 'registers two offenses for void literals in a `#each` method' do expect_offense(<<~RUBY) array.each do |_item| 42 ^^ Literal `42` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) array.each do |_item| end RUBY end it 'registers an offense for void constant in a `#each` method' do expect_offense(<<~RUBY) array.each do |_item| CONST ^^^^^ Constant `CONST` used in void context. end RUBY expect_correction(<<~RUBY) array.each do |_item| end RUBY end it 'handles `#each` block with single expression' do expect_offense(<<~RUBY) array.each do |_item| 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) array.each do |_item| end RUBY end it 'does not register `#each` block with conditional expression' do expect_no_offenses(<<~RUBY) enumerator_as_filter.each do |item| # The `filter` method is used to filter for matches with `42`. # In this case, it's not void. item == 42 end RUBY end it 'does not register `#each` block with conditional expressions that has multiple statements' do expect_no_offenses(<<~RUBY) enumerator_as_filter.each do |item| puts item # The `filter` method is used to filter for matches with `42`. # In this case, it's not void. item == 42 end RUBY end it 'does not register `#each` numblock with conditional expressions that has multiple statements' do expect_no_offenses(<<~RUBY) enumerator_as_filter.each do puts _1 # The `filter` method is used to filter for matches with `42`. # In this case, it's not void. _1 == 42 end RUBY end context 'Ruby 2.7', :ruby27 do it 'registers two offenses for void literals in `#tap` method' do expect_offense(<<~RUBY) foo.tap do _1 ^^ Variable `_1` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) foo.tap do end RUBY end end it 'registers two offenses for void literals in `#tap` method with a numbered block' do expect_offense(<<~RUBY) foo.tap do _1 ^^ Variable `_1` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) foo.tap do end RUBY end it 'accepts empty block' do expect_no_offenses(<<~RUBY) array.each { |_item| } RUBY end it 'registers two offenses for void literals in `#tap` method' do expect_offense(<<~RUBY) foo.tap do |x| 42 ^^ Literal `42` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) foo.tap do |x| end RUBY end it 'registers two offenses for void literals in a `for`' do expect_offense(<<~RUBY) for _item in array do 42 ^^ Literal `42` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) for _item in array do end RUBY end it 'registers two offenses for void literals in an `ensure`' do expect_offense(<<~RUBY) def foo ensure bar 42 ^^ Literal `42` used in void context. 42 ^^ Literal `42` used in void context. end RUBY expect_correction(<<~RUBY) def foo ensure bar end RUBY end it 'registers an offense when the body of `ensure` is a literal' do expect_offense(<<~RUBY) def foo bar ensure [1, 2, [3]] ^^^^^^^^^^^ Literal `[1, 2, [3]]` used in void context. end RUBY expect_correction(<<~RUBY) def foo bar ensure end RUBY end it 'handles explicit begin blocks' do expect_offense(<<~RUBY) begin 1 ^ Literal `1` used in void context. 2 end RUBY expect_correction(<<~RUBY) begin 2 end RUBY end it 'accepts short call syntax' do expect_no_offenses(<<~RUBY) lambda.(a) top RUBY end it 'accepts backtick commands' do expect_no_offenses(<<~RUBY) `touch x` nil RUBY end it 'accepts assigned if statements' do expect_no_offenses(<<~RUBY) x = if condition 42 end nil RUBY end it 'accepts assigned if statements in modifier form' do expect_no_offenses(<<~RUBY) x = (42 if condition) nil RUBY end it 'accepts assigned ternary statements' do expect_no_offenses(<<~RUBY) x = condition ? 42 : nil nil RUBY end it 'accepts percent-x commands' do expect_no_offenses(<<~RUBY) %x(touch x) nil RUBY end it 'accepts method with irange block' do expect_no_offenses(<<~RUBY) def foo 1..100.times.each { puts 1 } do_something end RUBY end it 'accepts method with erange block' do expect_no_offenses(<<~RUBY) def foo 1...100.times.each { puts 1 } do_something end RUBY end it 'registers an offense when using special __ENCODING__' do expect_offense(<<~RUBY) def foo __ENCODING__ ^^^^^^^^^^^^ Variable `__ENCODING__` used in void context. 42 end RUBY expect_correction(<<~RUBY) def foo 42 end RUBY end it 'does not register an offense for `if` without body' do expect_no_offenses(<<~RUBY) if some_condition end puts :ok RUBY end it 'does not register an offense for nested empty `begin`' do expect_no_offenses(<<~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/nested_method_definition_spec.rb
spec/rubocop/cop/lint/nested_method_definition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NestedMethodDefinition, :config do it 'registers an offense for a nested method definition' do expect_offense(<<~RUBY) def x; def y; end; end ^^^^^^^^^^ Method definitions must not be nested. Use `lambda` instead. RUBY end it 'registers an offense for a nested singleton method definition' do expect_offense(<<~RUBY) class Foo end foo = Foo.new def foo.bar def baz ^^^^^^^ Method definitions must not be nested. Use `lambda` instead. end end RUBY end it 'registers an offense for a nested method definition inside lambda' do expect_offense(<<~RUBY) def foo bar = -> { def baz; puts; end } ^^^^^^^^^^^^^^^^^^ Method definitions must not be nested. Use `lambda` instead. end RUBY end it 'registers an offense for a nested class method definition' do expect_offense(<<~RUBY) class Foo def self.x def self.y ^^^^^^^^^^ Method definitions must not be nested. Use `lambda` instead. end end end RUBY end it 'does not register an offense for a lambda definition inside method' do expect_no_offenses(<<~RUBY) def foo bar = -> { puts } bar.call end RUBY end it 'does not register offense for nested definition inside instance_eval' do expect_no_offenses(<<~RUBY) class Foo def x(obj) obj.instance_eval do def y end end end end RUBY end it 'does not register offense for nested definition inside instance_exec' do expect_no_offenses(<<~RUBY) class Foo def x(obj) obj.instance_exec do def y end end end end RUBY end it 'does not register offense for definition of method on local var' do expect_no_offenses(<<~RUBY) class Foo def x(obj) def obj.y end end end RUBY end it 'does not register offense for definition of method on instance var' do expect_no_offenses(<<~RUBY) class Foo def x def @obj.y end end end RUBY end it 'does not register offense for definition of method on class var' do expect_no_offenses(<<~RUBY) class Foo def x def @@obj.y end end end RUBY end it 'does not register offense for definition of method on global var' do expect_no_offenses(<<~RUBY) class Foo def x def $obj.y end end end RUBY end it 'does not register offense for definition of method on constant' do expect_no_offenses(<<~RUBY) class Foo def x def Const.y end end end RUBY end it 'does not register offense for definition of method on method call' do expect_no_offenses(<<~RUBY) class Foo def x def do_something.y end end end RUBY end it 'does not register offense for definition of method on safe navigation method call' do expect_no_offenses(<<~RUBY) class Foo def x def (do_something&.y).z end end end RUBY end it 'does not register offense for nested definition inside class_eval' do expect_no_offenses(<<~RUBY) class Foo def x(klass) klass.class_eval do def y end end end end RUBY end it 'does not register offense for nested definition inside class_exec' do expect_no_offenses(<<~RUBY) class Foo def x(klass) klass.class_exec do def y end end end end RUBY end it 'does not register offense for nested definition inside module_eval' do expect_no_offenses(<<~RUBY) class Foo def self.define(mod) mod.module_eval do def y end end end end RUBY end it 'does not register offense for nested definition inside module_exec' do expect_no_offenses(<<~RUBY) class Foo def self.define(mod) mod.module_exec do def y end end end end RUBY end it 'does not register offense for nested definition inside class shovel' do expect_no_offenses(<<~RUBY) class Foo def bar class << self def baz end end end end RUBY end it 'does not register offense for nested definition inside Class.new' do expect_no_offenses(<<~RUBY) class Foo def self.define Class.new(S) do def y end end end end class Foo def self.define Class.new do def y end end end end RUBY end it 'does not register offense for nested definition inside ::Class.new' do expect_no_offenses(<<~RUBY) class Foo def self.define ::Class.new(S) do def y end end end end class Foo def self.define ::Class.new do def y end end end end RUBY end it 'does not register offense for nested definition inside Module.new' do expect_no_offenses(<<~RUBY) class Foo def self.define Module.new do def y end end end end RUBY end it 'does not register offense for nested definition inside ::Module.new' do expect_no_offenses(<<~RUBY) class Foo def self.define ::Module.new do def y end end end end RUBY end it 'does not register offense for nested definition inside Struct.new' do expect_no_offenses(<<~RUBY) class Foo def self.define Struct.new(:name) do def y end end end end class Foo def self.define Struct.new do def y end end end end RUBY end it 'does not register offense for nested definition inside ::Struct.new' do expect_no_offenses(<<~RUBY) class Foo def self.define ::Struct.new(:name) do def y end end end end class Foo def self.define ::Struct.new do def y end end end end RUBY end it 'does not register offense for nested definition inside `Module.new` with block' do expect_no_offenses(<<~RUBY) class Foo def self.define Module.new do |m| def y end do_something(m) end end end RUBY end context 'when Ruby >= 2.7', :ruby27 do it 'does not register offense for nested definition inside `Module.new` with numblock' do expect_no_offenses(<<~RUBY) class Foo def self.define Module.new do def y end do_something(_1) end end end RUBY end it 'does not register offense for nested definition inside instance_eval with a numblock' do expect_no_offenses(<<~RUBY) class Foo def x(obj) obj.instance_eval do @bar = _1 def y end end end end RUBY end it 'does not register offense for nested definition inside instance_exec with a numblock' do expect_no_offenses(<<~RUBY) class Foo def x(obj) obj.instance_exec(3) do @bar = _1 def y end end end end RUBY end end context 'Ruby >= 3.4', :ruby34 do it 'does not register offense for nested definition inside `Module.new` with itblock' do expect_no_offenses(<<~RUBY) class Foo def self.define Module.new do def y end do_something(it) end end end RUBY end it 'does not register offense for nested definition inside instance_eval with itblock' do expect_no_offenses(<<~RUBY) class Foo def x(obj) obj.instance_eval do @bar = it def y end end end end RUBY end it 'does not register offense for nested definition inside instance_exec with itblock' do expect_no_offenses(<<~RUBY) class Foo def x(obj) obj.instance_exec(3) do @bar = it def y end end end end RUBY end end context 'when Ruby >= 3.2', :ruby32 do it 'does not register offense for nested definition inside `Data.define`' do expect_no_offenses(<<~RUBY) class Foo def self.define Data.define(:name) do def y end end end end class Foo def self.define Data.define do def y end end end end RUBY end it 'does not register offense for nested definition inside `::Data.define`' do expect_no_offenses(<<~RUBY) class Foo def self.define ::Data.define(:name) do def y end end end end class Foo def self.define ::Data.define do def y end end end end RUBY end end context 'when `AllowedMethods: [has_many]`' do let(:cop_config) do { 'AllowedMethods' => ['has_many'] } end it 'does not register offense for nested definition inside `has_many`' do expect_no_offenses(<<~RUBY) def do_something has_many :articles do def find_or_create_by_name(name) end end end RUBY end it 'registers an offense for nested definition inside `denied_method`' do expect_offense(<<~RUBY) def do_something denied_method :articles do def find_or_create_by_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Method definitions must not be nested. Use `lambda` instead. end end end RUBY end end context 'when `AllowedPatterns: [baz]`' do let(:cop_config) do { 'AllowedPatterns' => ['baz'] } end it 'does not register offense for nested definition inside `do_baz`' do expect_no_offenses(<<~RUBY) def foo(obj) obj.do_baz do def bar end end end RUBY end it 'registers an offense for nested definition inside `do_qux`' do expect_offense(<<~RUBY) def foo(obj) obj.do_qux do def bar ^^^^^^^ Method definitions must not be nested. Use `lambda` instead. end end end RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/duplicate_case_condition_spec.rb
spec/rubocop/cop/lint/duplicate_case_condition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateCaseCondition, :config do it 'registers an offense for repeated case conditionals' do expect_offense(<<~RUBY) case x when false first_method when true second_method when false ^^^^^ Duplicate `when` condition detected. third_method end RUBY end it 'registers an offense for subsequent repeated case conditionals' do expect_offense(<<~RUBY) case x when false first_method when false ^^^^^ Duplicate `when` condition detected. second_method end RUBY end it 'registers multiple offenses for multiple repeated case conditionals' do expect_offense(<<~RUBY) case x when false first_method when true second_method when false ^^^^^ Duplicate `when` condition detected. third_method when true ^^^^ Duplicate `when` condition detected. fourth_method end RUBY end it 'registers multiple offenses for repeated multi-value conditionals' do expect_offense(<<~RUBY) case x when a, b first_method when b, a ^ Duplicate `when` condition detected. ^ Duplicate `when` condition detected. second_method end RUBY end it 'registers an offense for repeated logical operator when expressions' do expect_offense(<<~RUBY) case x when a && b first_method when a && b ^^^^^^ Duplicate `when` condition detected. second_method end RUBY end it 'accepts trivial case expressions' do expect_no_offenses(<<~RUBY) case x when false first_method end RUBY end it 'accepts non-redundant case expressions' do expect_no_offenses(<<~RUBY) case x when false first_method when true second_method end RUBY end it 'accepts non-redundant case expressions with an else expression' do expect_no_offenses(<<~RUBY) case x when false method_name when true second_method else third_method end RUBY end it 'accepts similar but not equivalent && expressions' do expect_no_offenses(<<~RUBY) case x when something && another && other first_method when something && another second_method end RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/next_without_accumulator_spec.rb
spec/rubocop/cop/lint/next_without_accumulator_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NextWithoutAccumulator, :config do shared_examples 'reduce/inject' do |reduce_alias| context "given a #{reduce_alias} block" do it 'registers an offense for a bare next' do expect_offense(<<~RUBY) (1..4).#{reduce_alias}(0) do |acc, i| next if i.odd? ^^^^ Use `next` with an accumulator argument in a `reduce`. acc + i end RUBY end it 'registers an offense for a bare `next` in the block of safe navigation method called' do expect_offense(<<~RUBY) (1..4)&.#{reduce_alias}(0) do |acc, i| next if i.odd? ^^^^ Use `next` with an accumulator argument in a `reduce`. acc + i end RUBY end it 'accepts next with a value' do expect_no_offenses(<<~RUBY) (1..4).#{reduce_alias}(0) do |acc, i| next acc if i.odd? acc + i end RUBY end it 'accepts next within a nested block' do expect_no_offenses(<<~RUBY) [(1..3), (4..6)].#{reduce_alias}(0) do |acc, elems| elems.each_with_index do |elem, i| next if i == 1 acc << elem end acc end RUBY end context 'Ruby 2.7', :ruby27 do it 'registers an offense for a bare next' do expect_offense(<<~RUBY) (1..4).#{reduce_alias}(0) do next if _2.odd? ^^^^ Use `next` with an accumulator argument in a `reduce`. _1 + i end RUBY end it 'registers an offense for a bare `next` in the block of safe navigation method call' do expect_offense(<<~RUBY) (1..4)&.#{reduce_alias}(0) do next if _2.odd? ^^^^ Use `next` with an accumulator argument in a `reduce`. _1 + i end RUBY end end end end it_behaves_like 'reduce/inject', :reduce it_behaves_like 'reduce/inject', :inject context 'given an unrelated block' do it 'accepts a bare next' do expect_no_offenses(<<~RUBY) (1..4).foo(0) do |acc, i| next if i.odd? acc + i end RUBY end it 'accepts next with a value' do expect_no_offenses(<<~RUBY) (1..4).foo(0) do |acc, i| next acc if i.odd? acc + i 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_block_spec.rb
spec/rubocop/cop/lint/empty_block_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyBlock, :config do let(:cop_config) { { 'AllowComments' => true, 'AllowEmptyLambdas' => true } } it 'registers an offense for empty block within method call' do expect_offense(<<~RUBY) items.each { |item| } ^^^^^^^^^^^^^^^^^^^^^ Empty block detected. RUBY end it 'does not register an offense for empty block with inner comments' do expect_no_offenses(<<~RUBY) items.each do |item| # TODO: implement later end RUBY end it 'does not register an offense for empty block with inline comments' do expect_no_offenses(<<~RUBY) items.each { |item| } # TODO: implement later RUBY end it 'does not register an offense when block is not empty' do expect_no_offenses(<<~RUBY) items.each { |item| puts item } RUBY end it 'does not register an offense on an empty lambda' do expect_no_offenses(<<~RUBY) lambda do end RUBY end it 'does not register an offense on an empty stabby lambda' do expect_no_offenses(<<~RUBY) -> {} RUBY end it 'does not register an offense on an empty proc' do expect_no_offenses(<<~RUBY) proc do end RUBY end it 'does not register an offense on an empty Proc.new' do expect_no_offenses(<<~RUBY) Proc.new {} RUBY end it 'does not register an offense on an empty ::Proc.new' do expect_no_offenses(<<~RUBY) ::Proc.new {} RUBY end it 'registers an offense for an empty block given to a non-Kernel `proc` method' do expect_offense(<<~RUBY) Foo.proc {} ^^^^^^^^^^^ Empty block detected. RUBY end context 'when AllowComments is false' do let(:cop_config) { { 'AllowComments' => false } } it 'registers an offense for empty block with inner comments' do expect_offense(<<~RUBY) items.each do |item| ^^^^^^^^^^^^^^^^^^^^ Empty block detected. # TODO: implement later end RUBY end it 'registers an offense for empty block with inline comments' do expect_offense(<<~RUBY) items.each { |item| } # TODO: implement later ^^^^^^^^^^^^^^^^^^^^^ Empty block detected. RUBY end end context 'when AllowEmptyLambdas is false' do let(:cop_config) { { 'AllowEmptyLambdas' => false } } it 'registers an offense for an empty lambda' do expect_offense(<<~RUBY) lambda do ^^^^^^^^^ Empty block detected. end RUBY end it 'registers an offense for an empty stabby lambda' do expect_offense(<<~RUBY) -> {} ^^^^^ Empty block detected. RUBY end it 'registers an offense on an empty proc' do expect_offense(<<~RUBY) proc do ^^^^^^^ Empty block detected. end RUBY end it 'registers an offense on an empty Proc.new' do expect_offense(<<~RUBY) Proc.new {} ^^^^^^^^^^^ Empty block detected. RUBY end it 'registers an offense on an empty ::Proc.new' do expect_offense(<<~RUBY) ::Proc.new {} ^^^^^^^^^^^^^ Empty block detected. 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/refinement_import_methods_spec.rb
spec/rubocop/cop/lint/refinement_import_methods_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RefinementImportMethods, :config do context 'Ruby >= 3.1', :ruby31 do it 'registers an offense when using `include` in `refine` block' do expect_offense(<<~RUBY) refine Foo do include Bar ^^^^^^^ Use `import_methods` instead of `include` because it is deprecated in Ruby 3.1. end RUBY end it 'registers an offense when using `prepend` in `refine` block' do expect_offense(<<~RUBY) refine Foo do prepend Bar ^^^^^^^ Use `import_methods` instead of `prepend` because it is deprecated in Ruby 3.1. end RUBY end it 'does not register an offense when using `import_methods` in `refine` block' do expect_no_offenses(<<~RUBY) refine Foo do import_methods Bar end RUBY end it 'does not register an offense when using `include` with a receiver in `refine` block' do expect_no_offenses(<<~RUBY) refine Foo do Bar.include Baz end RUBY end it 'does not register an offense when using `include` on the top level' do expect_no_offenses(<<~RUBY) include Foo RUBY end end context 'Ruby <= 3.0', :ruby30, unsupported_on: :prism do it 'does not register an offense when using `include` in `refine` block' do expect_no_offenses(<<~RUBY) refine Foo do include Bar end RUBY end it 'does not register an offense when using `prepend` in `refine` block' do expect_no_offenses(<<~RUBY) refine Foo do prepend Bar end RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/struct_new_override_spec.rb
spec/rubocop/cop/lint/struct_new_override_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::StructNewOverride, :config do it 'registers an offense using `Struct.new(symbol)`' do expect_offense(<<~RUBY) Bad = Struct.new(:members) ^^^^^^^^ `:members` member overrides `Struct#members` and it may be unexpected. RUBY end it 'registers an offense using `::Struct.new(symbol)`' do expect_offense(<<~RUBY) Bad = ::Struct.new(:members) ^^^^^^^^ `:members` member overrides `Struct#members` and it may be unexpected. RUBY end it 'registers an offense using `Struct.new(string, ...symbols)`' do expect_offense(<<~RUBY) Struct.new('Bad', :members, :name) ^^^^^^^^ `:members` member overrides `Struct#members` and it may be unexpected. RUBY end it 'registers an offense using `Struct.new(...symbols)`' do expect_offense(<<~RUBY) Bad = Struct.new(:name, :members, :address) ^^^^^^^^ `:members` member overrides `Struct#members` and it may be unexpected. RUBY end it 'registers an offense using `Struct.new(symbol, string)`' do expect_offense(<<~RUBY) Bad = Struct.new(:name, "members") ^^^^^^^^^ `"members"` member overrides `Struct#members` and it may be unexpected. RUBY end it 'registers an offense using `Struct.new(...)` with a block' do expect_offense(<<~RUBY) Struct.new(:members) do ^^^^^^^^ `:members` member overrides `Struct#members` and it may be unexpected. def members? !members.empty? end end RUBY end it 'registers an offense using `Struct.new(...)` with multiple overrides' do expect_offense(<<~RUBY) Struct.new(:members, :clone, :zip) ^^^^ `:zip` member overrides `Struct#zip` and it may be unexpected. ^^^^^^ `:clone` member overrides `Struct#clone` and it may be unexpected. ^^^^^^^^ `:members` member overrides `Struct#members` and it may be unexpected. RUBY end it 'registers an offense using `Struct.new(...)` with an option argument' do expect_offense(<<~RUBY) Struct.new(:members, keyword_init: true) ^^^^^^^^ `:members` member overrides `Struct#members` and it may be unexpected. RUBY end it 'does not register an offense with no overrides' do expect_no_offenses(<<~RUBY) Good = Struct.new(:id, :name) RUBY end it 'does not register an offense with an override within a given block' do expect_no_offenses(<<~RUBY) Good = Struct.new(:id, :name) do def members super.tap { |ret| pp "members: " + ret.to_s } 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/suppressed_exception_spec.rb
spec/rubocop/cop/lint/suppressed_exception_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SuppressedException, :config do context 'with AllowComments set to false' do let(:cop_config) { { 'AllowComments' => false } } it 'registers an offense for empty rescue block' do expect_offense(<<~RUBY) begin something rescue ^^^^^^ Do not suppress exceptions. #do nothing end RUBY end it 'does not register an offense for rescue with body' do expect_no_offenses(<<~RUBY) begin something return rescue file.close end RUBY end context 'when empty rescue for `def`' do it 'registers an offense for empty rescue without comment' do expect_offense(<<~RUBY) def foo do_something rescue ^^^^^^ Do not suppress exceptions. end RUBY end it 'registers an offense for empty rescue with comment' do expect_offense(<<~RUBY) def foo do_something rescue ^^^^^^ Do not suppress exceptions. # do nothing end RUBY end context 'with AllowNil set to true' do let(:cop_config) { { 'AllowComments' => false, 'AllowNil' => true } } it 'does not register an offense for rescue block with nil' do expect_no_offenses(<<~RUBY) begin do_something rescue nil end RUBY end it 'does not register an offense for inline nil rescue' do expect_no_offenses(<<~RUBY) something rescue nil RUBY end end context 'with AllowNil set to false' do let(:cop_config) { { 'AllowComments' => false, 'AllowNil' => false } } it 'registers an offense for rescue block with nil' do expect_offense(<<~RUBY) begin do_something rescue ^^^^^^ Do not suppress exceptions. nil end RUBY end it 'registers an offense for inline nil rescue' do expect_offense(<<~RUBY) something rescue nil ^^^^^^^^^^ Do not suppress exceptions. RUBY end end end context 'when empty rescue for defs' do it 'registers an offense for empty rescue without comment' do expect_offense(<<~RUBY) def self.foo do_something rescue ^^^^^^ Do not suppress exceptions. end RUBY end it 'registers an offense for empty rescue with comment' do expect_offense(<<~RUBY) def self.foo do_something rescue ^^^^^^ Do not suppress exceptions. # do nothing end RUBY end end context 'Ruby 2.5 or higher', :ruby25 do context 'when empty rescue for `do` block' do it 'registers an offense for empty rescue without comment' do expect_offense(<<~RUBY) foo do do_something rescue ^^^^^^ Do not suppress exceptions. end RUBY end it 'registers an offense for empty rescue with comment' do expect_offense(<<~RUBY) foo do rescue ^^^^^^ Do not suppress exceptions. # do nothing end RUBY end end end end context 'with AllowComments set to true' do let(:cop_config) { { 'AllowComments' => true, 'AllowNil' => allow_nil } } let(:allow_nil) { true } it 'does not register an offense for empty rescue with comment' do expect_no_offenses(<<~RUBY) begin something return rescue # do nothing end RUBY end context 'when empty rescue for `def`' do it 'registers an offense for empty rescue without comment' do expect_offense(<<~RUBY) def foo do_something rescue ^^^^^^ Do not suppress exceptions. end RUBY end it 'does not register an offense for empty rescue with comment' do expect_no_offenses(<<~RUBY) def foo do_something rescue # do nothing end RUBY end end context 'when empty rescue for `defs`' do it 'registers an offense for empty rescue without comment' do expect_offense(<<~RUBY) def self.foo do_something rescue ^^^^^^ Do not suppress exceptions. end RUBY end it 'does not register an offense for empty rescue with comment' do expect_no_offenses(<<~RUBY) def self.foo do_something rescue # do nothing end RUBY end end context 'Ruby 2.5 or higher', :ruby25 do context 'when empty rescue for `do` block' do it 'registers an offense for empty rescue without comment' do expect_offense(<<~RUBY) foo do do_something rescue ^^^^^^ Do not suppress exceptions. end RUBY end it 'does not register an offense for empty rescue with comment' do expect_no_offenses(<<~RUBY) foo do rescue # do nothing end RUBY end end end context 'Ruby 2.7 or higher', :ruby27 do context 'when empty rescue for `do` block with a numbered parameter' do it 'registers an offense for empty rescue without comment' do expect_offense(<<~RUBY) foo do _1 rescue ^^^^^^ Do not suppress exceptions. end RUBY end it 'does not register an offense for empty rescue with comment' do expect_no_offenses(<<~RUBY) foo do _1 rescue # do nothing end RUBY end end end context 'with AllowNil set to true' do let(:allow_nil) { true } context 'when using endless method definition', :ruby30 do it 'does not register an offense for inline nil rescue' do expect_no_offenses(<<~RUBY) def some_method = other_method(42) rescue nil RUBY end end end context 'with AllowNil set to false' do let(:allow_nil) { false } context 'when using endless method definition', :ruby30 do it 'registers an offense for inline nil rescue' do expect_offense(<<~RUBY) def some_method = other_method(42) rescue nil ^^^^^^^^^^ Do not suppress exceptions. RUBY end end end it 'registers an offense for empty rescue on single line with a comment after it' do expect_offense(<<~RUBY) RSpec.describe Dummy do it 'dummy spec' do # This rescue is here to ensure the test does not fail because of the `raise` expect { begin subject; rescue ActiveRecord::Rollback; end }.not_to(change(Post, :count)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not suppress exceptions. # Done 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/safe_navigation_consistency_spec.rb
spec/rubocop/cop/lint/safe_navigation_consistency_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SafeNavigationConsistency, :config do let(:cop_config) { { 'AllowedMethods' => %w[present? blank? try presence] } } it 'allows && without receiver' do expect_no_offenses(<<~RUBY) foo && bar RUBY end it 'allows && without safe navigation' do expect_no_offenses(<<~RUBY) foo.bar && foo.baz RUBY end it 'allows || without safe navigation' do expect_no_offenses(<<~RUBY) foo.bar || foo.baz RUBY end it 'allows || with comparison method' do expect_no_offenses(<<~RUBY) foo == bar || foo == baz RUBY end it 'allows safe navigation when different variables are used' do expect_no_offenses(<<~RUBY) foo&.bar || foobar.baz RUBY end it 'does not register an offense using calling `nil?` after safe navigation with `||`' do expect_no_offenses(<<~RUBY) foo&.bar || foo.nil? RUBY end it 'does not register an offense using calling `nil?` before safe navigation with `&&`' do expect_no_offenses(<<~RUBY) foo.nil? && foo&.bar RUBY end it 'does not register an offense when calling to methods that nil responds to' do expect_no_offenses(<<~RUBY) return true if a.nil? || a&.whatever? RUBY end it 'does not register an offense using safe navigation on the left of &&' do expect_no_offenses(<<~RUBY) foo&.bar && foo.baz RUBY end it 'registers an offense and corrects using safe navigation on the right of &&' do expect_offense(<<~RUBY) foo.bar && foo&.baz ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo.bar && foo.baz RUBY end it 'does not register an offense using safe navigation for difference receiver on the right of &&' do expect_no_offenses(<<~RUBY) x.foo.bar && y.foo&.baz RUBY end it 'registers an offense and corrects using safe navigation on the both of &&' do expect_offense(<<~RUBY) foo&.bar && foo&.baz ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo&.bar && foo.baz RUBY end it 'registers an offense and corrects using safe navigation on the left of ||' do expect_offense(<<~RUBY) foo&.bar || foo.baz ^ Use `&.` for consistency with safe navigation. RUBY expect_correction(<<~RUBY) foo&.bar || foo&.baz RUBY end it 'registers an offense and corrects using safe navigation on the right of ||' do expect_offense(<<~RUBY) foo.bar || foo&.baz ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo.bar || foo.baz RUBY end it 'registers an offense and corrects when there is code before or after the condition' do expect_offense(<<~RUBY) foo = nil foo&.bar || foo.baz ^ Use `&.` for consistency with safe navigation. something RUBY expect_correction(<<~RUBY) foo = nil foo&.bar || foo&.baz something RUBY end it 'registers an offense and corrects non dot method calls for `&&` on LHS only' do expect_offense(<<~RUBY) foo > 5 && foo&.zero? ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo > 5 && foo.zero? RUBY end it 'registers an offense but does not correct non dot method calls for `||` on RHS only' do expect_offense(<<~RUBY) foo&.zero? || foo > 5 ^^^^^^^ Use `&.` for consistency with safe navigation. RUBY expect_no_corrections end it 'does not register an offense when using safe navigation on the LHS with `==` on the RHS of `&&`' do expect_no_offenses(<<~RUBY) foo&.bar && foo == 1 RUBY end it 'does not register an offense when using safe navigation on the LHS with `!=` on the RHS of `&&`' do expect_no_offenses(<<~RUBY) foo&.bar && foo != 1 RUBY end it 'does not register an offense when using safe navigation on the LHS with `===` on the RHS of `&&`' do expect_no_offenses(<<~RUBY) foo&.bar && foo === 1 RUBY end it 'does not register an offense when using safe navigation on the LHS with `==` on the RHS of `||`' do expect_no_offenses(<<~RUBY) foo&.bar || foo == 1 RUBY end it 'does not register an offense when using safe navigation on the LHS with `!=` on the RHS of `||`' do expect_no_offenses(<<~RUBY) foo&.bar || foo != 1 RUBY end it 'does not register an offense when using safe navigation on the LHS with `===` on the RHS of `||`' do expect_no_offenses(<<~RUBY) foo&.bar || foo === 1 RUBY end it 'does not register an offense when using safe navigation on the LHS with `+` on the RHS of `&&`' do expect_no_offenses(<<~RUBY) foo&.bar && foo + 1 RUBY end it 'registers an offense when using safe navigation on the LHS with `+` on the RHS of `||`' do expect_offense(<<~RUBY) foo&.bar || foo + 1 ^^^^^^^ Use `&.` for consistency with safe navigation. RUBY expect_no_corrections end it 'does not register an offense when using safe navigation on the LHS with `-` on the RHS of `&&`' do expect_no_offenses(<<~RUBY) foo&.bar && foo - 1 RUBY end it 'registers an offense when using safe navigation on the LHS with `-` on the RHS of `||`' do expect_offense(<<~RUBY) foo&.bar || foo - 1 ^^^^^^^ Use `&.` for consistency with safe navigation. RUBY expect_no_corrections end it 'does not register an offense when using safe navigation on the LHS with `<<` on the RHS of `&&`' do expect_no_offenses(<<~RUBY) foo&.bar && foo << 1 RUBY end it 'registers an offense when using safe navigation on the LHS with `<<` on the RHS of `||`' do expect_offense(<<~RUBY) foo&.bar || foo << 1 ^^^^^^^^ Use `&.` for consistency with safe navigation. RUBY expect_no_corrections end it 'does not register an offense assignment when using safe navigation on the left `&`' do expect_no_offenses(<<~RUBY) foo&.bar && foo.baz = 1 RUBY end it 'registers an offense and corrects assignment when using safe navigation on the right `&`' do expect_offense(<<~RUBY) foo.bar && foo&.baz = 1 ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo.bar && foo.baz = 1 RUBY end it 'registers an offense and corrects assignment when using safe navigation on the both `&`' do expect_offense(<<~RUBY) foo&.bar && foo&.baz = 1 ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo&.bar && foo.baz = 1 RUBY end it 'does not register an offense using safe navigation on the left `&&` and inside of separated conditions' do expect_no_offenses(<<~RUBY) foo&.bar && foobar.baz && foo.qux RUBY end it 'registers an offense and corrects using safe navigation on the right `&&` and inside of separated conditions' do expect_offense(<<~RUBY) foo.bar && foobar.baz && foo&.qux ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo.bar && foobar.baz && foo.qux RUBY end it 'registers an offense and corrects using safe navigation on the right `||` and inside of separated conditions' do expect_offense(<<~RUBY) foo.bar || foobar.baz || foo&.qux ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo.bar || foobar.baz || foo.qux RUBY end it 'does not register an offense using safe navigation in conditions on the right hand side' do expect_no_offenses(<<~RUBY) foobar.baz && foo&.bar && foo.qux RUBY end it 'registers and corrects multiple offenses' do expect_no_offenses(<<~RUBY) foobar.baz && foo&.bar && foo.qux && foo.foobar RUBY end it 'registers an offense and corrects using unsafe navigation with both && and ||' do expect_offense(<<~RUBY) foo&.bar && foo&.baz || foo&.qux ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo&.bar && foo.baz || foo&.qux RUBY end it 'does not register an offense using unsafe navigation with grouped conditions' do expect_no_offenses(<<~RUBY) foo&.bar && (foo.baz || foo.qux) RUBY end it 'registers an offense and corrects safe navigation that appears after dot method call' do expect_offense(<<~RUBY) foo.bar && foo.baz || foo&.qux ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo.bar && foo.baz || foo.qux RUBY end it 'does not register an offense safe navigation that appears before dot method call' do expect_no_offenses(<<~RUBY) foo&.bar || foo&.baz && foo.qux RUBY end it 'does not register an offense using unsafe navigation and the safe navigation appears in a group' do expect_no_offenses(<<~RUBY) (foo&.bar && foo.baz) || foo.qux RUBY end it 'registers a single offense and corrects when safe navigation is used multiple times' do expect_offense(<<~RUBY) foo&.bar && foo&.baz || foo.qux ^^ Use `.` instead of unnecessary `&.`. RUBY expect_correction(<<~RUBY) foo&.bar && foo.baz || foo.qux RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/redundant_cop_disable_directive_spec.rb
spec/rubocop/cop/lint/redundant_cop_disable_directive_spec.rb
# frozen_string_literal: true require 'rubocop/cop/legacy/corrector' RSpec.describe RuboCop::Cop::Lint::RedundantCopDisableDirective, :config do describe '.check' do let(:offenses) { [] } let(:cop) { cop_class.new(config, cop_options, offenses) } context 'when there are no disabled lines' do let(:source) { '' } it 'returns no offense' do expect_no_offenses(source) end end context 'when there are disabled lines' do context 'and there are no offenses' do context 'and a comment disables' do context 'a cop that is disabled in the config' do let(:other_cops) { { 'Metrics/MethodLength' => { 'Enabled' => false } } } let(:offenses) do [ RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: 7, column: 0), 'Method has too many lines.', 'Metrics/MethodLength') ] end it 'returns an offense when disabling same cop' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. RUBY end describe 'when that cop was previously enabled' do it 'returns no offense' do expect_no_offenses(<<~RUBY) # rubocop:enable Metrics/MethodLength foo # rubocop:disable Metrics/MethodLength RUBY end end describe 'if that cop has offenses' do it 'returns an offense' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. RUBY end end end context 'a department that is disabled in the config' do let(:config) do RuboCop::Config.new('Metrics' => { 'Enabled' => false }) end it 'returns an offense when same department is disabled' do expect_offense(<<~RUBY) # rubocop:disable Metrics ^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics` department. RUBY end it 'returns an offense when cop from this department is disabled' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. RUBY end end context 'one cop' do it 'returns an offense' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. RUBY expect_correction('') end end context 'an unknown cop' do it 'returns an offense' do expect_offense(<<~RUBY) # rubocop:disable UnknownCop ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `UnknownCop` (unknown cop). RUBY expect_correction('') end end context 'when using a directive comment after a non-directive comment' do it 'returns an offense' do expect_offense(<<~RUBY) # not very long comment # rubocop:disable Layout/LineLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Layout/LineLength`. RUBY expect_correction(<<~RUBY) # not very long comment RUBY end end context 'itself and another cop' do context 'disabled on the same range' do it 'returns no offense' do expect_no_offenses(<<~RUBY) # rubocop:disable Lint/RedundantCopDisableDirective, Metrics/ClassLength RUBY end end context 'disabled on different ranges' do it 'returns no offense' do expect_no_offenses(<<~RUBY) # rubocop:disable Lint/RedundantCopDisableDirective # rubocop:disable Metrics/ClassLength RUBY end end context 'and the other cop is disabled a second time' do let(:source) do ['# rubocop:disable Lint/RedundantCopDisableDirective', '# rubocop:disable Metrics/ClassLength', '# rubocop:disable Metrics/ClassLength'].join("\n") end it 'returns no offense' do expect_no_offenses(source) end end end context 'multiple cops' do it 'returns an offense' do expect_offense(<<~RUBY.gsub("<\n", '')) # Wrap lines & avoid issue with JRuby # rubocop:disable Metrics/MethodLength, Metrics/ClassLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ < Unnecessary disabling of `Metrics/ClassLength`, `Metrics/MethodLength`. RUBY end end context 'multiple cops, and one of them has offenses' do let(:offenses) do [ RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: 7, column: 0), 'Class has too many lines.', 'Metrics/ClassLength') ] end it 'returns an offense' do expect_offense(<<~RUBY.gsub("<\n", '')) # Wrap lines & avoid issue with JRuby # rubocop:disable Metrics/MethodLength, Metrics/ClassLength, Lint/Debugger, < Lint/AmbiguousOperator ^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. ^^^^^^^^^^^^^ Unnecessary disabling of `Lint/Debugger`. < ^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Lint/AmbiguousOperator`. RUBY expect_correction(<<~RUBY) # rubocop:disable Metrics/ClassLength RUBY end end context 'multiple cops, and the leftmost one has no offenses' do let(:offenses) do [ RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: 7, column: 0), 'Method has too many lines.', 'Metrics/MethodLength') ] end it 'returns an offense' do expect_offense(<<~RUBY) # rubocop:disable Metrics/ClassLength, Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. RUBY expect_correction(<<~RUBY) # rubocop:disable Metrics/MethodLength RUBY end end context 'multiple cops, with abbreviated names' do include_context 'mock console output' context 'one of them has offenses' do let(:offenses) do [ RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: 4, column: 0), 'Method has too many lines.', 'Metrics/MethodLength') ] end it 'returns an offense' do expect_offense(<<~RUBY) puts 1 # rubocop:disable MethodLength, ClassLength, Debugger ^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. ^^^^^^^^ Unnecessary disabling of `Lint/Debugger`. # # offense here RUBY expect($stderr.string).to eq(<<~OUTPUT) (string): Warning: no department given for MethodLength. (string): Warning: no department given for ClassLength. (string): Warning: no department given for Debugger. OUTPUT end end end context 'comment is not at the beginning of the file' do context 'and not all cops have offenses' do let(:offenses) do [ RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: 4, column: 0), 'Method has too many lines.', 'Metrics/MethodLength') ] end it 'returns an offense' do expect_offense(<<~RUBY) puts 1 # rubocop:disable Metrics/MethodLength, Metrics/ClassLength ^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. # # offense here RUBY end end end context 'misspelled cops' do it 'returns an offense' do message = 'Unnecessary disabling of `KlassLength` (unknown ' \ 'cop), `Metrics/MethodLenght` (did you mean ' \ '`Metrics/MethodLength`?).' expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLenght, KlassLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{message} RUBY end context 'when the department starts with a lowercase letter' do it 'registers an offense' do expect_offense(<<~RUBY) # rubocop:disable lint/SelfAssignment ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `lint/SelfAssignment` (did you mean `Lint/SelfAssignment`?). RUBY expect_correction('') end end context 'when the cop starts with a lowercase letter' do it 'registers an offense' do expect_offense(<<~RUBY) # rubocop:disable Lint/selfAssignment ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Lint/selfAssignment` (did you mean `Lint/SelfAssignment`?). RUBY expect_correction('') end end end context 'all cops' do it 'returns an offense' do expect_offense(<<~RUBY) # rubocop : disable all ^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of all cops. RUBY end end context 'itself and all cops' do context 'disabled on different ranges' do let(:source) do ['# rubocop:disable Lint/RedundantCopDisableDirective', '# rubocop:disable all'].join("\n") end it 'returns no offense' do expect_no_offenses(source) end end end end end context 'and there are two offenses' do let(:message) { 'Replace class var @@class_var with a class instance var.' } let(:cop_name) { 'Style/ClassVars' } let(:offenses) do offense_lines.map do |line| RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: line, column: 3), message, cop_name) end end context 'and a comment disables' do context 'one cop twice' do let(:offense_lines) { [3, 8] } it 'returns an offense' do expect_offense(<<~RUBY) class One # rubocop:disable Style/ClassVars @@class_var = 1 # offense here end class Two # rubocop:disable Style/ClassVars ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Style/ClassVars`. @@class_var = 2 # offense and here # rubocop:enable Style/ClassVars end RUBY end end context 'one cop and then all cops' do let(:offense_lines) { [4] } it 'returns an offense' do expect_offense(<<~RUBY) class One # rubocop:disable Style/ClassVars ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Style/ClassVars`. # rubocop:disable all @@class_var = 1 # offense here end RUBY end end end end context 'and there is an offense' do let(:offenses) do [ RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: 3, column: 0), 'Tab detected.', 'Layout/IndentationStyle') ] end context 'and a comment disables' do context 'that cop' do let(:source) { '# rubocop:disable Layout/IndentationStyle' } it 'returns no offense' do expect_no_offenses(source) end end context 'that cop but on other lines' do it 'returns an offense' do expect_offense(<<~RUBY) # 1 # 2 # 3, offense here # 4 # rubocop:disable Layout/IndentationStyle ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Layout/IndentationStyle`. # # rubocop:enable Layout/IndentationStyle RUBY end end context 'all cops' do let(:source) { '# rubocop : disable all' } it 'returns no offense' do expect_no_offenses(source) end end end end end context 'autocorrecting whitespace' do context 'when the comment is the first line of the file' do context 'followed by code' do it 'removes the comment' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. def my_method end # rubocop:enable Metrics/MethodLength RUBY expect_correction(<<~RUBY) def my_method end # rubocop:enable Metrics/MethodLength RUBY end end context 'followed by a newline' do it 'removes the comment and newline' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. def my_method end # rubocop:enable Metrics/MethodLength RUBY expect_correction(<<~RUBY) def my_method end # rubocop:enable Metrics/MethodLength RUBY end end context 'followed by another comment' do it 'removes the comment and newline' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. # @api private def my_method end # rubocop:enable Metrics/MethodLength RUBY expect_correction(<<~RUBY) # @api private def my_method end # rubocop:enable Metrics/MethodLength RUBY end end end context 'when there is only whitespace before the comment' do it 'leaves the whitespace' do expect_offense(<<~RUBY) # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. def my_method end # rubocop:enable Metrics/MethodLength RUBY expect_correction(<<~RUBY) def my_method end # rubocop:enable Metrics/MethodLength RUBY end end context 'when the comment is not the first line of the file' do it 'preserves whitespace before the comment' do expect_offense(<<~RUBY) attr_reader :foo # rubocop:disable Metrics/MethodLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/MethodLength`. def my_method end # rubocop:enable Metrics/MethodLength RUBY expect_correction(<<~RUBY) attr_reader :foo def my_method end # rubocop:enable Metrics/MethodLength RUBY end end context 'nested inside a namespace' do it 'preserves indentation' do expect_offense(<<~RUBY) module Foo module Bar # rubocop:disable Metrics/ClassLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. class Baz end # rubocop:enable Metrics/ClassLength end end RUBY expect_correction(<<~RUBY) module Foo module Bar class Baz end # rubocop:enable Metrics/ClassLength end end RUBY end end context 'inline comment' do it 'removes the comment and preceding whitespace' do expect_offense(<<~RUBY) module Foo module Bar class Baz # rubocop:disable Metrics/ClassLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. end end end RUBY expect_correction(<<~RUBY) module Foo module Bar class Baz end end end RUBY end end context 'when there is a blank line before inline comment' do it 'removes the comment and preceding whitespace' do expect_offense(<<~RUBY) def foo; end def bar # rubocop:disable Metrics/ClassLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. do_something do end end RUBY expect_correction(<<~RUBY) def foo; end def bar do_something do end end RUBY end end end context 'with a disabled department' do let(:offenses) do [ RuboCop::Cop::Offense.new(:convention, FakeLocation.new(line: 2, column: 0), 'Class has too many lines.', 'Metrics/ClassLength') ] end it 'removes entire comment' do expect_offense(<<~RUBY) # rubocop:disable Style ^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Style` department. def bar do_something end RUBY expect_correction(<<~RUBY) def bar do_something end RUBY end it 'removes redundant department' do expect_offense(<<~RUBY) # rubocop:disable Style, Metrics/ClassLength ^^^^^ Unnecessary disabling of `Style` department. def bar do_something end RUBY expect_correction(<<~RUBY) # rubocop:disable Metrics/ClassLength def bar do_something end RUBY end it 'removes cop duplicated by department' do expect_offense(<<~RUBY) # rubocop:disable Metrics, Metrics/ClassLength ^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. def bar do_something end RUBY expect_correction(<<~RUBY) # rubocop:disable Metrics def bar do_something end RUBY end it 'removes cop duplicated by department on previous line' do expect_offense(<<~RUBY) # rubocop:disable Metrics def bar do_something # rubocop:disable Metrics/ClassLength ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. end RUBY expect_correction(<<~RUBY) # rubocop:disable Metrics def bar do_something end RUBY end it 'removes cop duplicated by department and leaves free text as a comment' do expect_offense(<<~RUBY) # rubocop:disable Metrics def bar do_something # rubocop:disable Metrics/ClassLength - note ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`. end RUBY expect_correction(<<~RUBY) # rubocop:disable Metrics def bar do_something # - note end RUBY end it 'removes department duplicated by department' do expect_offense(<<~RUBY) # rubocop:disable Metrics class One # rubocop:disable Metrics ^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics` department. @@class_var = 1 # offense here end # rubocop:enable Metrics RUBY end it 'removes department duplicated by department on previous line' do expect_offense(<<~RUBY) # rubocop:disable Metrics class One @@class_var = 1 # rubocop:disable Metrics ^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics` department. end RUBY end it 'removes department duplicated by department and leaves free text as a comment' do expect_offense(<<~RUBY) # rubocop:disable Metrics def bar do_something # rubocop:disable Metrics - note ^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics` department. end RUBY expect_correction(<<~RUBY) # rubocop:disable Metrics def bar do_something # - note end RUBY end it 'does not remove correct department' do expect_no_offenses(<<~RUBY) # rubocop:disable Metrics def bar do_something 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/numbered_parameter_assignment_spec.rb
spec/rubocop/cop/lint/numbered_parameter_assignment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NumberedParameterAssignment, :config do # NOTE: Assigning to numbered parameter (from `_1` to `_9`) cause an error in Ruby 3.0. context 'when Ruby 2.7 or lower', :ruby27, unsupported_on: :prism do (1..9).to_a.each do |number| it "registers an offense when using `_#{number}` numbered parameter" do expect_offense(<<~RUBY) _#{number} = :value ^^^^^^^^^^^ `_#{number}` is reserved for numbered parameter; consider another name. RUBY end end end it 'registers an offense when using `_0` lvar' do expect_offense(<<~RUBY) _0 = :value ^^^^^^^^^^^ `_0` is similar to numbered parameter; consider another name. RUBY end it 'registers an offense when using `_10` lvar' do expect_offense(<<~RUBY) _10 = :value ^^^^^^^^^^^^ `_10` is similar to numbered parameter; consider another name. RUBY end it 'does not register an offense when using non numbered parameter' do expect_no_offenses(<<~RUBY) non_numbered_parameter_name = :value RUBY end it 'does not register an offense when index assignment' do expect_no_offenses(<<~RUBY) Hash.new { _1[_2] = :value } 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_type_spec.rb
spec/rubocop/cop/lint/rescue_type_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RescueType, :config do it 'accepts rescue modifier' do expect_no_offenses('foo rescue nil') end it 'accepts rescuing nothing' do expect_no_offenses(<<~RUBY) begin foo rescue bar end RUBY end it 'accepts rescuing a single exception' do expect_no_offenses(<<~RUBY) def foobar foo rescue NameError bar end RUBY end it 'accepts rescuing nothing within a method definition' do expect_no_offenses(<<~RUBY) def foobar foo rescue bar end RUBY end shared_examples 'offenses' do |rescues| context 'begin rescue' do context "rescuing from #{rescues}" do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY, rescues: rescues) begin foo rescue %{rescues} ^^^^^^^^{rescues} Rescuing from `#{rescues}` will raise a `TypeError` instead of catching the actual exception. bar end RUBY expect_correction(<<~RUBY) begin foo rescue bar end RUBY end end context "rescuing from #{rescues} before another exception" do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY, rescues: rescues) begin foo rescue %{rescues}, StandardError ^^^^^^^^{rescues}^^^^^^^^^^^^^^^ Rescuing from `#{rescues}` will raise a `TypeError` instead of catching the actual exception. bar end RUBY expect_correction(<<~RUBY) begin foo rescue StandardError bar end RUBY end end context "rescuing from #{rescues} after another exception" do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY, rescues: rescues) begin foo rescue StandardError, %{rescues} ^^^^^^^^^^^^^^^^^^^^^^^{rescues} Rescuing from `#{rescues}` will raise a `TypeError` instead of catching the actual exception. bar end RUBY expect_correction(<<~RUBY) begin foo rescue StandardError bar end RUBY end end end context 'begin rescue ensure' do context "rescuing from #{rescues}" do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY, rescues: rescues) begin foo rescue %{rescues} ^^^^^^^^{rescues} Rescuing from `#{rescues}` will raise a `TypeError` instead of catching the actual exception. bar ensure baz end RUBY expect_correction(<<~RUBY) begin foo rescue bar ensure baz end RUBY end end end context 'def rescue' do context "rescuing from #{rescues}" do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY, rescues: rescues) def foobar foo rescue %{rescues} ^^^^^^^^{rescues} Rescuing from `#{rescues}` will raise a `TypeError` instead of catching the actual exception. bar end RUBY expect_correction(<<~RUBY) def foobar foo rescue bar end RUBY end end end context 'def rescue ensure' do context "rescuing from #{rescues}" do it 'registers an offense and autocorrects' do expect_offense(<<~RUBY, rescues: rescues) def foobar foo rescue %{rescues} ^^^^^^^^{rescues} Rescuing from `#{rescues}` will raise a `TypeError` instead of catching the actual exception. bar ensure baz end RUBY expect_correction(<<~RUBY) def foobar foo rescue bar ensure baz end RUBY end end end end it_behaves_like 'offenses', 'nil' it_behaves_like 'offenses', "'string'" it_behaves_like 'offenses', '"#{string}"' it_behaves_like 'offenses', '0' it_behaves_like 'offenses', '0.0' it_behaves_like 'offenses', '[]' it_behaves_like 'offenses', '{}' it_behaves_like 'offenses', ':symbol' end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/top_level_return_with_argument_spec.rb
spec/rubocop/cop/lint/top_level_return_with_argument_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::TopLevelReturnWithArgument, :config do context 'Code segment with only top-level return statement' do it 'expects no offense from the return without arguments' do expect_no_offenses(<<~RUBY) return RUBY end it 'expects offense from the return with arguments' do expect_offense(<<~RUBY) return 1, 2, 3 ^^^^^^^^^^^^^^ Top level return with argument detected. RUBY expect_correction(<<~RUBY) return RUBY end it 'expects multiple offenses from the return with arguments statements' do expect_offense(<<~RUBY) return 1, 2, 3 ^^^^^^^^^^^^^^ Top level return with argument detected. return 1, 2, 3 ^^^^^^^^^^^^^^ Top level return with argument detected. return 1, 2, 3 ^^^^^^^^^^^^^^ Top level return with argument detected. RUBY expect_correction(<<~RUBY) return return return RUBY end end context 'Code segment with block level returns other than the top-level return' do it 'expects no offense from the return without arguments' do expect_no_offenses(<<~RUBY) foo [1, 2, 3, 4, 5].each { |n| return n } return bar RUBY end it 'expects offense from the return with arguments' do expect_offense(<<~RUBY) foo [1, 2, 3, 4, 5].each { |n| return n } return 1, 2, 3 ^^^^^^^^^^^^^^ Top level return with argument detected. bar RUBY expect_correction(<<~RUBY) foo [1, 2, 3, 4, 5].each { |n| return n } return bar RUBY end end context 'Code segment with method-level return statements' do it 'expects offense when method-level & top-level return co-exist' do expect_offense(<<~RUBY) def method return 'Hello World' end return 1, 2, 3 ^^^^^^^^^^^^^^ Top level return with argument detected. RUBY expect_correction(<<~RUBY) def method return 'Hello World' end return RUBY end end context 'Code segment with inline if along with top-level return' do it 'expects no offense from the return without arguments' do expect_no_offenses(<<~RUBY) foo return if 1 == 1 bar def method return "Hello World" if 1 == 1 end RUBY end it 'expects multiple offenses from the return with arguments' do expect_offense(<<~RUBY) foo return 1, 2, 3 if 1 == 1 ^^^^^^^^^^^^^^ Top level return with argument detected. bar return 2 ^^^^^^^^ Top level return with argument detected. return 3 ^^^^^^^^ Top level return with argument detected. def method return "Hello World" if 1 == 1 end RUBY expect_correction(<<~RUBY) foo return if 1 == 1 bar return return def method return "Hello World" if 1 == 1 end RUBY end end context 'Code segment containing semi-colon separated statements' do it 'expects an offense from the return with arguments and multi-line code' do expect_offense(<<~RUBY) foo if a == b; warn 'hey'; return 42; end ^^^^^^^^^ Top level return with argument detected. bar RUBY expect_correction(<<~RUBY) foo if a == b; warn 'hey'; return; end bar RUBY end it 'expects no offense from the return with arguments and multi-line code' do expect_no_offenses(<<~RUBY) foo if a == b; warn 'hey'; return; end 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/ambiguous_regexp_literal_spec.rb
spec/rubocop/cop/lint/ambiguous_regexp_literal_spec.rb
# frozen_string_literal: true # FIXME: https://github.com/ruby/prism/issues/2513 RSpec.describe RuboCop::Cop::Lint::AmbiguousRegexpLiteral, :config do shared_examples 'with a regexp literal in the first argument' do context 'without parentheses' do it 'registers an offense and corrects when single argument' do expect_offense(<<~RUBY) p /pattern/ ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) p(/pattern/) RUBY end it 'registers an offense and corrects when multiple arguments' do expect_offense(<<~RUBY) p /pattern/, foo ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) p(/pattern/, foo) RUBY end it 'registers an offense and corrects when sending method to regexp without argument' do expect_offense(<<~RUBY) p /pattern/.do_something ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) p(/pattern/.do_something) RUBY end it 'registers an offense and corrects when sending method to regexp with argument' do expect_offense(<<~RUBY) p /pattern/.do_something(42) ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) p(/pattern/.do_something(42)) RUBY end it 'registers an offense and corrects when sending method chain to regexp' do expect_offense(<<~RUBY) p /pattern/.do_something.do_something ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) p(/pattern/.do_something.do_something) RUBY end it 'registers an offense and corrects when using regexp without method call in a nested structure' do expect_offense(<<~RUBY) class MyTest test '#foo' do assert_match /expected/, actual ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. end end RUBY expect_correction(<<~RUBY) class MyTest test '#foo' do assert_match(/expected/, actual) end end RUBY end it 'registers an offense and corrects when sending method inside parens without receiver takes a regexp argument' do expect_offense(<<~RUBY) expect('RuboCop').to(match /Cop/) ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) expect('RuboCop').to(match(/Cop/)) RUBY end it 'registers an offense and corrects when sending method without receiver takes a regexp argument' do expect_offense(<<~RUBY) expect('RuboCop').to match /Robo/ ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) expect('RuboCop').to match(/Robo/) RUBY end it 'registers an offense and corrects when using block argument' do expect_offense(<<~RUBY) p /pattern/, foo do |arg| ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. end RUBY expect_correction(<<~RUBY) p(/pattern/, foo) do |arg| end RUBY end it 'registers an offense and corrects when nesting' do expect_offense(<<~RUBY) p /pattern/ do ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. p /pattern/ ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. end RUBY expect_correction(<<~RUBY) p(/pattern/) do p(/pattern/) end RUBY end it 'registers an offense and corrects when using nested method arguments without parentheses' do expect_offense(<<~RUBY) puts line.grep /pattern/ ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY expect_correction(<<~RUBY) puts line.grep(/pattern/) RUBY end end context 'with parentheses' do it 'accepts' do expect_no_offenses('p(/pattern/)') end end context 'with `match_with_lvasgn` node' do context 'with parentheses' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) assert(/some pattern/ =~ some_string) RUBY end end context 'with different parentheses' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) assert(/some pattern/) =~ some_string RUBY end end context 'without parentheses' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) assert /some pattern/ =~ some_string ^ Ambiguous regexp literal. Parenthesize the method arguments if it's surely a regexp literal, or add a whitespace to the right of the `/` if it should be a division. RUBY # Spacing will be fixed by `Lint/ParenthesesAsGroupedExpression`. expect_correction(<<~RUBY) assert (/some pattern/ =~ some_string) RUBY end end end end context 'Ruby <= 2.7', :ruby27, unsupported_on: :prism do it_behaves_like 'with a regexp literal in the first argument' end context 'Ruby >= 3.0', :ruby30 do it_behaves_like 'with a regexp literal in the first argument' 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_spec.rb
spec/rubocop/cop/lint/ambiguous_operator_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::AmbiguousOperator, :config do context 'with `+` unary operator in the first argument' do context 'without parentheses' do context 'without whitespaces on the right of the operator' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) do_something(+24) do_something +42 ^ Ambiguous positive number operator. Parenthesize the method arguments if it's surely a positive number operator, or add a whitespace to the right of the `+` if it should be an addition. RUBY expect_correction(<<~RUBY) do_something(+24) do_something(+42) RUBY end end context 'without whitespaces on the right of the operator when a method with no arguments is used in advance' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) do_something do_something +42 ^ Ambiguous positive number operator. Parenthesize the method arguments if it's surely a positive number operator, or add a whitespace to the right of the `+` if it should be an addition. RUBY expect_correction(<<~RUBY) do_something do_something(+42) RUBY end end context 'with a whitespace on the right of the operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) do_something + 42 RUBY end end end context 'with parentheses around the operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) do_something(+42) RUBY end end end context 'with `-` unary operator in the first argument' do context 'without parentheses' do context 'without whitespaces on the right of the operator' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) do_something(-24) do_something -42 ^ Ambiguous negative number operator. Parenthesize the method arguments if it's surely a negative number operator, or add a whitespace to the right of the `-` if it should be a subtraction. RUBY expect_correction(<<~RUBY) do_something(-24) do_something(-42) RUBY end end context 'with a whitespace on the right of the operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) do_something - 42 RUBY end end end context 'with parentheses around the operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) do_something(-42) RUBY end end end context 'with a splat operator in the first argument' do context 'without parentheses' do context 'without whitespaces on the right of the operator' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) array = [1, 2, 3] puts *array ^ Ambiguous splat operator. Parenthesize the method arguments if it's surely a splat operator, or add a whitespace to the right of the `*` if it should be a multiplication. RUBY expect_correction(<<~RUBY) array = [1, 2, 3] puts(*array) RUBY end end context 'with a whitespace on the right of the operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) array = [1, 2, 3] puts * array RUBY end end end context 'with parentheses around the splatted argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) array = [1, 2, 3] puts(*array) RUBY end end end context 'with a block ampersand in the first argument' do context 'without parentheses' do context 'without whitespaces on the right of the operator' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) process = proc { do_something } 2.times &process ^ Ambiguous block operator. Parenthesize the method arguments if it's surely a block operator, or add a whitespace to the right of the `&` if it should be a binary AND. RUBY expect_correction(<<~RUBY) process = proc { do_something } 2.times(&process) RUBY end end context 'with a whitespace on the right of the operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) process = proc { do_something } 2.times & process RUBY end end end context 'with parentheses around the block argument' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) process = proc { do_something } 2.times(&process) RUBY end end end context 'with a keyword splat operator in the first argument' do context 'without parentheses' do context 'without whitespaces on the right of the operator' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) do_something **kwargs ^^ Ambiguous keyword splat operator. Parenthesize the method arguments if it's surely a keyword splat operator, or add a whitespace to the right of the `**` if it should be an exponent. RUBY expect_correction(<<~RUBY) do_something(**kwargs) RUBY end end context 'with a whitespace on the right of the operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) do_something ** kwargs RUBY end end end context 'with parentheses around the keyword splat operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) do_something(**kwargs) RUBY end end end context 'when using safe navigation operator with a unary operator' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) do_something&.* -1 RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/duplicate_magic_comment_spec.rb
spec/rubocop/cop/lint/duplicate_magic_comment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateMagicComment, :config do it 'registers an offense when frozen magic comments are duplicated' do expect_offense(<<~RUBY) # frozen_string_literal: true # frozen_string_literal: true ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Duplicate magic comment detected. RUBY expect_correction(<<~RUBY) # frozen_string_literal: true RUBY end it 'registers an offense when frozen magic comments with different case are duplicated' do expect_offense(<<~RUBY) # frozen_string_literal: true # frozen_string_literal: TRUE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Duplicate magic comment detected. RUBY expect_correction(<<~RUBY) # frozen_string_literal: true RUBY end it 'registers an offense when same encoding magic comments are duplicated' do expect_offense(<<~RUBY) # encoding: ascii # encoding: ascii ^^^^^^^^^^^^^^^^^ Duplicate magic comment detected. RUBY expect_correction(<<~RUBY) # encoding: ascii RUBY end it 'registers an offense when different encoding magic comments are duplicated' do expect_offense(<<~RUBY) # encoding: ascii # encoding: utf-8 ^^^^^^^^^^^^^^^^^ Duplicate magic comment detected. RUBY expect_correction(<<~RUBY) # encoding: ascii RUBY end it 'registers an offense when encoding and frozen magic comments are duplicated' do expect_offense(<<~RUBY) # encoding: ascii # frozen_string_literal: true # encoding: ascii ^^^^^^^^^^^^^^^^^ Duplicate magic comment detected. # frozen_string_literal: true ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Duplicate magic comment detected. RUBY expect_correction(<<~RUBY) # encoding: ascii # frozen_string_literal: true RUBY end it 'does not register an offense when frozen magic comments are not duplicated' do expect_no_offenses(<<~RUBY) # frozen_string_literal: true RUBY end it 'does not register an offense when encoding magic comments are not duplicated' do expect_no_offenses(<<~RUBY) # encoding: ascii RUBY end it 'does not register an offense when encoding and frozen magic comments are not duplicated' do expect_no_offenses(<<~RUBY) # encoding: ascii # frozen_string_literal: true 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_match_pattern_spec.rb
spec/rubocop/cop/lint/duplicate_match_pattern_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateMatchPattern, :config, :ruby27 do it 'registers an offense for repeated `in` patterns' do expect_offense(<<~RUBY) case x in foo first_method in bar second_method in foo ^^^ Duplicate `in` pattern detected. third_method end RUBY end it 'registers an offense for subsequent repeated `in` patterns' do expect_offense(<<~RUBY) case x in foo first_method in foo ^^^ Duplicate `in` pattern detected. second_method end RUBY end it 'registers multiple offenses for multiple repeated `in` patterns' do expect_offense(<<~RUBY) case x in foo first_method in bar second_method in foo ^^^ Duplicate `in` pattern detected. third_method in bar ^^^ Duplicate `in` pattern detected. fourth_method end RUBY end it 'registers multiple offenses for repeated alternative patterns' do expect_offense(<<~RUBY) case x in 0 | 1 first_method in 1 | 0 ^^^^^ Duplicate `in` pattern detected. second_method end RUBY end it 'does not register for not equivalent alternative patterns' do expect_no_offenses(<<~RUBY) case x in 0 | 1 | 2 first_method in 3 | 4 second_method end RUBY end it 'registers an offense for repeated array patterns with elements in the same order' do expect_offense(<<~RUBY) case x in [foo, bar] first_method in [foo, bar] ^^^^^^^^^^ Duplicate `in` pattern detected. second_method end RUBY end it 'does not register an offense for repeated array patterns with elements in different order' do expect_no_offenses(<<~RUBY) case x in [foo, bar] first_method in [bar, foo] second_method end RUBY end it 'does not register similar but not equivalent && array patterns' do expect_no_offenses(<<~RUBY) case x in [foo, bar] first_method in [foo, bar, baz] second_method end RUBY end it 'registers an offense for repeated hash patterns with elements in the same order' do expect_offense(<<~RUBY) case x in foo: a, bar: b first_method in foo: a, bar: b ^^^^^^^^^^^^^^ Duplicate `in` pattern detected. second_method end RUBY end it 'registers an offense for repeated hash patterns with elements in different order' do expect_offense(<<~RUBY) case x in foo: a, bar: b first_method in bar: b, foo: a ^^^^^^^^^^^^^^ Duplicate `in` pattern detected. second_method end RUBY end it 'does not register similar but not equivalent && hash patterns' do expect_no_offenses(<<~RUBY) case x in foo: a, bar: b first_method in foo: a, bar: b, baz: c second_method end RUBY end it 'does not register trivial `in` patterns' do expect_no_offenses(<<~RUBY) case x in false first_method end RUBY end it 'does not register non-redundant `in` patterns' do expect_no_offenses(<<~RUBY) case x in foo first_method in bar second_method end RUBY end it 'does not register non-redundant `in` patterns with an else clause' do expect_no_offenses(<<~RUBY) case x in foo method_name in bar second_method else third_method end RUBY end it 'registers an offense for repeated `in` patterns and the same `if` guard is used' do expect_offense(<<~RUBY) case x in foo if condition first_method in foo if condition ^^^ Duplicate `in` pattern detected. third_method end RUBY end it 'registers an offense for repeated `in` patterns and the same `unless` guard is used' do expect_offense(<<~RUBY) case x in foo unless condition first_method in foo unless condition ^^^ Duplicate `in` pattern detected. third_method end RUBY end it 'does not register an offense for repeated `in` patterns but different `if` guard is used' do expect_no_offenses(<<~RUBY) case x in foo if condition1 first_method in foo if condition2 third_method end RUBY end it 'does not register an offense for repeated `in` patterns but different `unless` guard is used' do expect_no_offenses(<<~RUBY) case x in foo unless condition1 first_method in foo unless condition2 third_method end RUBY end it 'does not crash when using hash pattern with `if` guard' do expect_no_offenses(<<~RUBY) case x in { key: value } if condition 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/raise_exception_spec.rb
spec/rubocop/cop/lint/raise_exception_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RaiseException, :config do let(:cop_config) { { 'AllowedImplicitNamespaces' => ['Gem'] } } it 'registers an offense and corrects for `raise` with `::Exception`' do expect_offense(<<~RUBY) raise ::Exception ^^^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) raise ::StandardError RUBY end it 'registers an offense and corrects for `raise` with `::Exception.new`' do expect_offense(<<~RUBY) raise ::Exception.new 'Error with exception' ^^^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) raise ::StandardError.new 'Error with exception' RUBY end it 'registers an offense and corrects for `raise` with `::Exception` and message' do expect_offense(<<~RUBY) raise ::Exception, 'Error with exception' ^^^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) raise ::StandardError, 'Error with exception' RUBY end it 'registers an offense and corrects for `raise` with `Exception`' do expect_offense(<<~RUBY) raise Exception ^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) raise StandardError RUBY end it 'registers an offense and corrects for `raise` with `Exception` and message' do expect_offense(<<~RUBY) raise Exception, 'Error with exception' ^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) raise StandardError, 'Error with exception' RUBY end it 'registers an offense and corrects for `raise` with `Exception.new` and message' do expect_offense(<<~RUBY) raise Exception.new 'Error with exception' ^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) raise StandardError.new 'Error with exception' RUBY end it 'registers an offense and corrects for `raise` with `Exception.new(args*)`' do expect_offense(<<~RUBY) raise Exception.new('arg1', 'arg2') ^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) raise StandardError.new('arg1', 'arg2') RUBY end it 'registers an offense and corrects for `fail` with `Exception`' do expect_offense(<<~RUBY) fail Exception ^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) fail StandardError RUBY end it 'registers an offense and corrects for `fail` with `Exception` and message' do expect_offense(<<~RUBY) fail Exception, 'Error with exception' ^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) fail StandardError, 'Error with exception' RUBY end it 'registers an offense and corrects for `fail` with `Exception.new` and message' do expect_offense(<<~RUBY) fail Exception.new 'Error with exception' ^^^^^^^^^ Use `StandardError` over `Exception`. RUBY expect_correction(<<~RUBY) fail StandardError.new 'Error with exception' RUBY end it 'does not register an offense for `raise` without arguments' do expect_no_offenses('raise') end it 'does not register an offense for `fail` without arguments' do expect_no_offenses('fail') end it 'does not register an offense when raising Exception with explicit namespace' do expect_no_offenses(<<~RUBY) raise Foo::Exception RUBY end context 'when under namespace' do it 'does not register an offense when Exception without cbase specified' do expect_no_offenses(<<~RUBY) module Gem def self.foo raise Exception end end RUBY end it 'registers an offense and corrects when Exception with cbase specified' do expect_offense(<<~RUBY) module Gem def self.foo raise ::Exception ^^^^^^^^^^^ Use `StandardError` over `Exception`. end end RUBY expect_correction(<<~RUBY) module Gem def self.foo raise ::StandardError 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/empty_ensure_spec.rb
spec/rubocop/cop/lint/empty_ensure_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyEnsure, :config do it 'registers an offense and corrects empty ensure' do expect_offense(<<~RUBY) begin something ensure # hello ^^^^^^ Empty `ensure` block detected. # world end RUBY expect_correction(<<~RUBY) begin something # hello # world end RUBY end it 'does not register an offense for non-empty ensure' do expect_no_offenses(<<~RUBY) begin something return ensure file.close 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_with_index_spec.rb
spec/rubocop/cop/lint/redundant_with_index_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantWithIndex, :config do it 'registers an offense for `ary.each_with_index { |v| v }` and corrects to `ary.each`' do expect_offense(<<~RUBY) ary.each_with_index { |v| v } ^^^^^^^^^^^^^^^ Use `each` instead of `each_with_index`. RUBY expect_correction(<<~RUBY) ary.each { |v| v } RUBY end it 'registers an offense for `ary&.each_with_index { |v| v }` and corrects to `ary&.each`' do expect_offense(<<~RUBY) ary&.each_with_index { |v| v } ^^^^^^^^^^^^^^^ Use `each` instead of `each_with_index`. RUBY expect_correction(<<~RUBY) ary&.each { |v| v } RUBY end it 'registers an offense when using `ary.each.with_index { |v| v }` and corrects to `ary.each`' do expect_offense(<<~RUBY) ary.each.with_index { |v| v } ^^^^^^^^^^ Remove redundant `with_index`. RUBY expect_correction(<<~RUBY) ary.each { |v| v } RUBY end it 'registers an offense when using `ary.each.with_index(1) { |v| v }` ' \ 'and correct to `ary.each { |v| v }`' do expect_offense(<<~RUBY) ary.each.with_index(1) { |v| v } ^^^^^^^^^^^^^ Remove redundant `with_index`. RUBY expect_correction(<<~RUBY) ary.each { |v| v } RUBY end it 'registers an offense when using ' \ '`ary.each_with_object([]).with_index { |v| v }` ' \ 'and corrects to `ary.each_with_object([]) { |v| v }`' do expect_offense(<<~RUBY) ary.each_with_object([]).with_index { |v| v } ^^^^^^^^^^ Remove redundant `with_index`. RUBY expect_correction(<<~RUBY) ary.each_with_object([]) { |v| v } RUBY end it 'accepts an index is used as a block argument' do expect_no_offenses('ary.each_with_index { |v, i| v; i }') end context 'Ruby 2.7', :ruby27 do it 'registers an offense for `ary.each_with_index { _1 }` and corrects to `ary.each`' do expect_offense(<<~RUBY) ary.each_with_index { _1 } ^^^^^^^^^^^^^^^ Use `each` instead of `each_with_index`. RUBY expect_correction(<<~RUBY) ary.each { _1 } RUBY end it 'registers an offense for `ary&.each_with_index { _1 }` and corrects to `ary&.each`' do expect_offense(<<~RUBY) ary&.each_with_index { _1 } ^^^^^^^^^^^^^^^ Use `each` instead of `each_with_index`. RUBY expect_correction(<<~RUBY) ary&.each { _1 } RUBY end it 'registers an offense when using `ary.each.with_index { _1 }` and corrects to `ary.each`' do expect_offense(<<~RUBY) ary.each.with_index { _1 } ^^^^^^^^^^ Remove redundant `with_index`. RUBY expect_correction(<<~RUBY) ary.each { _1 } RUBY end it 'accepts an index is used as a numblock argument' do expect_no_offenses('ary.each_with_index { _1; _2 }') end it 'accepts with_index with receiver and a block' do expect_no_offenses('ary.with_index { |v| v }') end it 'accepts with_index without receiver with a block' do expect_no_offenses('with_index { |v| v }') end it 'accepts with_index without receiver with a numblock' do expect_no_offenses('with_index { _1 }') end end context 'Ruby 3.4', :ruby34 do it 'registers an offense for `ary.each_with_index { it }` and corrects to `ary.each`' do expect_offense(<<~RUBY) ary.each_with_index { it } ^^^^^^^^^^^^^^^ Use `each` instead of `each_with_index`. RUBY expect_correction(<<~RUBY) ary.each { it } RUBY end it 'registers an offense for `ary&.each_with_index { it }` and corrects to `ary&.each`' do expect_offense(<<~RUBY) ary&.each_with_index { it } ^^^^^^^^^^^^^^^ Use `each` instead of `each_with_index`. RUBY expect_correction(<<~RUBY) ary&.each { it } RUBY end it 'registers an offense when using `ary.each.with_index { it }` and corrects to `ary.each`' do expect_offense(<<~RUBY) ary.each.with_index { it } ^^^^^^^^^^ Remove redundant `with_index`. RUBY expect_correction(<<~RUBY) ary.each { it } RUBY end it 'accepts with_index without receiver with an itblock' do expect_no_offenses('with_index { it }') end 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_local_exit_from_iterator_spec.rb
spec/rubocop/cop/lint/non_local_exit_from_iterator_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NonLocalExitFromIterator, :config do context 'when block is followed by method chain' do context 'and has single argument' do it 'registers an offense' do expect_offense(<<~RUBY) items.each do |item| return if item.stock == 0 ^^^^^^ Non-local exit from iterator, [...] item.update!(foobar: true) end RUBY end it 'registers an offense for numblocks' do expect_offense(<<~RUBY) items.each do return if baz?(_1) ^^^^^^ Non-local exit from iterator, [...] _1.update!(foobar: true) end RUBY end it 'registers an offense for itblocks', :ruby34 do expect_offense(<<~RUBY) items.each do return if baz?(it) ^^^^^^ Non-local exit from iterator, [...] it.update!(foobar: true) end RUBY end end context 'and has multiple arguments' do it 'registers an offense' do expect_offense(<<~RUBY) items.each_with_index do |item, i| return if item.stock == 0 ^^^^^^ Non-local exit from iterator, [...] item.update!(foobar: true) end RUBY end end context 'and has no argument' do it 'allows' do expect_no_offenses(<<~RUBY) item.with_lock do return if item.stock == 0 item.update!(foobar: true) end RUBY end end end context 'when block is not followed by method chain' do it 'allows' do expect_no_offenses(<<~RUBY) transaction do return unless update_necessary? find_each do |item| return if item.stock == 0 # false-negative... item.update!(foobar: true) end end RUBY end end context 'when block is lambda' do it 'allows' do expect_no_offenses(<<~RUBY) items.each(lambda do |item| return if item.stock == 0 item.update!(foobar: true) end) items.each -> (item) { return if item.stock == 0 item.update!(foobar: true) } RUBY end end context 'when lambda is inside of block followed by method chain' do it 'allows' do expect_no_offenses(<<~RUBY) RSpec.configure do |config| # some configuration if Gem.loaded_specs["paper_trail"].version < Gem::Version.new("4.0.0") current_behavior = ActiveSupport::Deprecation.behavior ActiveSupport::Deprecation.behavior = lambda do |message, callstack| return if message =~ /foobar/ Array.wrap(current_behavior).each do |behavior| behavior.call(message, callstack) end end # more configuration end end RUBY end end context 'when block in middle of nest is followed by method chain' do it 'registers offenses' do expect_offense(<<~RUBY) transaction do return unless update_necessary? items.each do |item| return if item.nil? ^^^^^^ Non-local exit from iterator, [...] item.with_lock do return if item.stock == 0 ^^^^^^ Non-local exit from iterator, [...] item.very_complicated_update_operation! end end end RUBY end end it 'allows return with value' do expect_no_offenses(<<~RUBY) def find_first_sold_out_item(items) items.each do |item| return item if item.stock == 0 item.foobar! end end RUBY end it 'allows return in define_method' do expect_no_offenses(<<~RUBY) [:method_one, :method_two].each do |method_name| define_method(method_name) do return if predicate? end end RUBY end it 'allows return in define_singleton_method' do expect_no_offenses(<<~RUBY) str = 'foo' str.define_singleton_method :bar do |baz| return unless baz replace baz end RUBY end context 'when the return is within a nested method definition' do it 'allows return in an instance method definition' do expect_no_offenses(<<~RUBY) Foo.configure do |c| def bar return if baz? end end RUBY end it 'allows return in a class method definition' do expect_no_offenses(<<~RUBY) Foo.configure do |c| def self.bar return if baz? 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/redundant_string_coercion_spec.rb
spec/rubocop/cop/lint/redundant_string_coercion_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantStringCoercion, :config do it 'registers an offense and corrects `to_s` in interpolation' do expect_offense(<<~'RUBY') "this is the #{result.to_s}" ^^^^ Redundant use of `Object#to_s` in interpolation. /regexp #{result.to_s}/ ^^^^ Redundant use of `Object#to_s` in interpolation. :"symbol #{result.to_s}" ^^^^ Redundant use of `Object#to_s` in interpolation. `backticks #{result.to_s}` ^^^^ Redundant use of `Object#to_s` in interpolation. RUBY expect_correction(<<~'RUBY') "this is the #{result}" /regexp #{result}/ :"symbol #{result}" `backticks #{result}` RUBY end it 'registers an offense and corrects `to_s` in interpolation with safe navigation' do expect_offense(<<~'RUBY') "this is the #{result&.to_s}" ^^^^ Redundant use of `Object#to_s` in interpolation. /regexp #{result&.to_s}/ ^^^^ Redundant use of `Object#to_s` in interpolation. :"symbol #{result&.to_s}" ^^^^ Redundant use of `Object#to_s` in interpolation. `backticks #{result&.to_s}` ^^^^ Redundant use of `Object#to_s` in interpolation. RUBY expect_correction(<<~'RUBY') "this is the #{result}" /regexp #{result}/ :"symbol #{result}" `backticks #{result}` RUBY end it 'registers an offense and corrects `to_s` in an interpolation with several expressions' do expect_offense(<<~'RUBY') "this is the #{top; result.to_s}" ^^^^ Redundant use of `Object#to_s` in interpolation. RUBY expect_correction(<<~'RUBY') "this is the #{top; result}" RUBY end it 'accepts #to_s with arguments in an interpolation' do expect_no_offenses('"this is a #{result.to_s(8)}"') end it 'accepts interpolation without #to_s' do expect_no_offenses('"this is the #{result}"') end it 'registers an offense and corrects an implicit receiver' do expect_offense(<<~'RUBY') "#{to_s}" ^^^^ Use `self` instead of `Object#to_s` in interpolation. RUBY expect_correction(<<~'RUBY') "#{self}" RUBY end it 'does not explode on empty interpolation' do expect_no_offenses('"this is #{} silly"') end it 'registers an offense and corrects `to_s` in `print` arguments' do expect_offense(<<~RUBY) print first.to_s, second.to_s ^^^^ Redundant use of `Object#to_s` in `print`. ^^^^ Redundant use of `Object#to_s` in `print`. RUBY expect_correction(<<~RUBY) print first, second RUBY end it 'registers an offense and corrects `to_s` in `print` arguments without receiver' do expect_offense(<<~RUBY) print to_s, to_s ^^^^ Use `self` instead of `Object#to_s` in `print`. ^^^^ Use `self` instead of `Object#to_s` in `print`. RUBY expect_correction(<<~RUBY) print self, self RUBY end it 'registers an offense and corrects `to_s` in `puts` arguments' do expect_offense(<<~RUBY) puts first.to_s, second.to_s ^^^^ Redundant use of `Object#to_s` in `puts`. ^^^^ Redundant use of `Object#to_s` in `puts`. RUBY expect_correction(<<~RUBY) puts first, second RUBY end it 'registers an offense and corrects `to_s` with safe navigation in `puts` arguments' do expect_offense(<<~RUBY) puts first&.to_s, second&.to_s ^^^^ Redundant use of `Object#to_s` in `puts`. ^^^^ Redundant use of `Object#to_s` in `puts`. RUBY expect_correction(<<~RUBY) puts first, second RUBY end it 'registers an offense and corrects `to_s` in `warn` arguments' do expect_offense(<<~RUBY) warn first.to_s, second.to_s ^^^^ Redundant use of `Object#to_s` in `warn`. ^^^^ Redundant use of `Object#to_s` in `warn`. RUBY expect_correction(<<~RUBY) warn first, second RUBY end it 'registers an offense and corrects `to_s` in `puts` arguments without receiver' do expect_offense(<<~RUBY) puts to_s, to_s ^^^^ Use `self` instead of `Object#to_s` in `puts`. ^^^^ Use `self` instead of `Object#to_s` in `puts`. RUBY expect_correction(<<~RUBY) puts self, self RUBY end it 'does not register an offense when not using `to_s` in `print` arguments' do expect_no_offenses(<<~RUBY) print obj.do_something RUBY end it 'does not register an offense when not using `to_s` in `puts` arguments' do expect_no_offenses(<<~RUBY) puts obj.do_something RUBY end it 'does not register an offense when using `to_s` in `p` arguments' do expect_no_offenses(<<~RUBY) p first.to_s, second.to_s RUBY end it 'does not register an offense when using `to_s` in `print` arguments with receiver' do expect_no_offenses(<<~RUBY) obj.print first.to_s, second.to_s RUBY end it 'does not register an offense when using `to_s(argument)` in `puts` argument' do expect_no_offenses(<<~RUBY) puts obj.to_s(argument) 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/triple_quotes_spec.rb
spec/rubocop/cop/lint/triple_quotes_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::TripleQuotes, :config do context 'triple quotes' do context 'on one line' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) """a string""" ^^^^^^^^^^^^^^ Delimiting a string with multiple quotes has no effect, use a single quote instead. RUBY expect_correction(<<~RUBY) "a string" RUBY end end context 'on multiple lines' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) """ ^^^ Delimiting a string with multiple quotes has no effect, use a single quote instead. a string """ RUBY expect_correction(<<~RUBY) " a string " RUBY end end context 'when only quotes' do it 'registers an offense and corrects to a single empty quote' do expect_offense(<<~RUBY) """""" ^^^^^^ Delimiting a string with multiple quotes has no effect, use a single quote instead. RUBY expect_correction(<<~RUBY) "" RUBY end end context 'with only whitespace' do it 'does not register' do expect_no_offenses(<<~RUBY) " " " " " " RUBY end end end context 'quintuple quotes' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) """"" ^^^^^ Delimiting a string with multiple quotes has no effect, use a single quote instead. a string """"" RUBY expect_correction(<<~RUBY) " a string " RUBY end end context 'string interpolation' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') str = "#{abc}" RUBY end context 'with nested extra quotes' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') str = "#{'''abc'''}" ^^^^^^^^^ Delimiting a string with multiple quotes has no effect, use a single quote instead. RUBY expect_correction(<<~'RUBY') str = "#{'abc'}" RUBY end end end context 'heredocs' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') str = <<~STRING a string #{interpolation} STRING RUBY end end it 'does not register an offense for implicit concatenation' do expect_no_offenses(<<~RUBY) '' '' 'a''b''c' 'a''''b' RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/multiple_comparison_spec.rb
spec/rubocop/cop/lint/multiple_comparison_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::MultipleComparison, :config do shared_examples 'Check to use two comparison operator' do |operator1, operator2| it "registers an offense for x #{operator1} y #{operator2} z" do expect_offense(<<~RUBY, operator1: operator1, operator2: operator2) x %{operator1} y %{operator2} z ^^^{operator1}^^^^{operator2}^^ Use the `&&` operator to compare multiple values. RUBY expect_correction(<<~RUBY) x #{operator1} y && y #{operator2} z RUBY end end %w[< > <= >=].repeated_permutation(2) do |operator1, operator2| it_behaves_like 'Check to use two comparison operator', operator1, operator2 end it 'accepts to use one compare operator' do expect_no_offenses('x < 1') end it 'accepts to use `&` operator' do expect_no_offenses('x >= y & x < z') end it 'accepts to use `|` operator' do expect_no_offenses('x >= y | x < z') end it 'accepts to use `^` operator' do expect_no_offenses('x >= y ^ x < z') 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/unmodified_reduce_accumulator_spec.rb
spec/rubocop/cop/lint/unmodified_reduce_accumulator_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnmodifiedReduceAccumulator, :config do shared_examples 'reduce/inject' do |method| it "does not affect #{method} called with no block args" do expect_no_offenses(<<~RUBY) values.#{method} do do_something end RUBY end it "does not affect #{method} called without a block" do expect_no_offenses(<<~RUBY) values.#{method}(:+) RUBY end it "does not affect #{method} called with an empty block" do expect_no_offenses(<<~RUBY) values.#{method}(:+) { |result, value| } RUBY end context "given a #{method} block" do it 'does not register an offense when returning a literal' do expect_no_offenses(<<~RUBY) values.reduce(true) do |result, value| next false if something? true end RUBY end it 'registers an offense when returning the element' do aggregate_failures do expect_offense(<<~RUBY) (1..4).#{method}(0) do |acc, el| el ^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY expect_offense(<<~RUBY) values.#{method}({}) do |acc, el| acc[el] = true el ^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end end it 'registers an offense when returning the element in the block of safe navigation method call' do aggregate_failures do expect_offense(<<~RUBY) (1..4)&.#{method}(0) do |acc, el| el ^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY expect_offense(<<~RUBY) values&.#{method}({}) do |acc, el| acc[el] = true el ^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end end it 'registers an offense when called with no argument' do expect_offense(<<~RUBY) (1..4).#{method} do |acc, el| el ^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end it 'does not register an offense when comparing' do aggregate_failures do expect_no_offenses(<<~RUBY) values.#{method}(false) do |acc, el| acc == el end RUBY expect_no_offenses(<<~RUBY) values.#{method}(false) do |acc, el| el == acc end RUBY end end it 'does not register an offense when returning the accumulator' do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc end RUBY end it 'does not register an offense when assigning the accumulator' do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc = el end RUBY end it 'does not register an offense when op-assigning the accumulator' do aggregate_failures do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc += 5 end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc += el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| el += acc end RUBY end end it 'does not register an offense when or-assigning the accumulator' do aggregate_failures do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc ||= el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| el ||= acc end RUBY end end it 'does not register an offense when returning the accumulator in a boolean statement' do aggregate_failures do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc || el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| el || acc end RUBY end end it 'does not register an offense when and-assigning the accumulator' do aggregate_failures do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc &&= el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| el &&= acc end RUBY end end it 'does not register an offense when shovelling the accumulator' do aggregate_failures do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc << el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| el << acc end RUBY end end it 'does not register an offense when mutating the element with the accumulator' do aggregate_failures do expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el.method!(acc, foo) el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| method!(acc, foo, el) el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el << acc el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el << acc.foo el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el += acc el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el += acc.foo el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el &&= acc el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el &&= acc.foo el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el = acc el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el = acc.foo el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| x = acc el << x el end RUBY end end it 'does not register an offense when mutating the element with the another value' do aggregate_failures do expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el.method!(foo) el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| method!(foo, el) el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| x = acc el << x el end RUBY expect_no_offenses(<<~RUBY) values.#{method} do |acc, el| el = x = acc el end RUBY end end it 'registers an offense when mutating the accumulator with the element but not returning it' do expect_offense(<<~RUBY) values.#{method} do |acc, el| acc = el acc += el acc << el acc &&= el acc.method!(el) el ^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end it 'does not register an offense with the accumulator in interpolation' do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| "\#{acc}\#{el}" end RUBY end it 'registers an offense with the element in interpolation' do expect_offense(<<~RUBY) (1..4).#{method}(0) do |acc, el| "\#{el}" ^^^^^^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end it 'does not register an offense with the accumulator in heredoc' do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| <<~RESULT \#{acc}\#{el} RESULT end RUBY end it 'registers an offense with the element in heredoc' do expect_offense(<<~RUBY) (1..4).#{method}(0) do |acc, el| <<~RESULT ^^^^^^^^^ Ensure the accumulator `acc` will be modified by `#{method}`. \#{el} RESULT end RUBY end it 'does not register an offense when returning the accumulator in an expression' do aggregate_failures do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc + el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| el + acc end RUBY end end it 'does not register an offense when returning a method called on the accumulator' do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| acc.method end RUBY end it 'does not register an offense when returning a method called with the accumulator' do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| method(acc) end RUBY end it 'does not register an offense when calling a method on the accumulator with the element' do expect_no_offenses(<<~RUBY) foo.#{method} { |result, key| result.method(key) } RUBY end it 'registers an offense when returning an index of the accumulator' do expect_offense(<<~RUBY) %w(a b c).#{method}({}) do |acc, letter| acc[foo] ^^^^^^^^ Do not return an element of the accumulator in `#{method}`. end RUBY end it 'registers an offense when returning an index setter on the accumulator' do expect_offense(<<~RUBY) %w(a b c).#{method}({}) do |acc, letter| acc[foo] = bar ^^^^^^^^^^^^^^ Do not return an element of the accumulator in `#{method}`. end RUBY end it 'does not register an offense when returning accumulator[element]' do expect_no_offenses(<<~RUBY) foo.#{method} { |result, key| result[key] } RUBY end it 'registers an offense when returning accumulator[element]=' do expect_offense(<<~RUBY, method: method) foo.#{method} { |result, key| result[key] = foo } _{method} ^^^^^^^^^^^^^^^^^ Do not return an element of the accumulator in `#{method}`. RUBY end it 'registers an offense when returning an expression with the element' do expect_offense(<<~RUBY) (1..4).#{method}(0) do |acc, el| el + 2 ^^^^^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end it 'registers an offense for values returned with `next`' do expect_offense(<<~RUBY) (1..4).#{method}(0) do |acc, el| next el if el.even? ^^ Ensure the accumulator `acc` will be modified by `#{method}`. acc += 1 end RUBY end it 'registers an offense for values returned with `break`' do expect_offense(<<~RUBY) (1..4).#{method}(0) do |acc, el| break el if el.even? ^^ Ensure the accumulator `acc` will be modified by `#{method}`. acc += 1 end RUBY end it 'registers an offense for every violating return value' do expect_offense(<<~RUBY) (1..4).#{method}(0) do |acc, el| next el if el.even? ^^ Ensure the accumulator `acc` will be modified by `#{method}`. el * 2 ^^^^^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end it 'does not register an offense if the return value cannot be determined' do aggregate_failures do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| x + el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| self.x + el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| x + y end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| x = acc + el x end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| x = acc + el x ** 2 end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| x = acc x + el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| @var + el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| el + @var end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| foo.bar(el) end RUBY expect_no_offenses(<<~RUBY) enum.#{method} do |acc, el| x = [*acc, el] x << 42 if foo x end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| Foo.el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| foo.bar.baz.el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| self.el end RUBY expect_no_offenses(<<~RUBY) (1..4).#{method}(0) do |acc, el| "\#{self.el}\#{el}" end RUBY end end it 'does not look inside inner blocks' do expect_no_offenses(<<~RUBY) foo.#{method}(bar) do |acc, el| values.map do |v| next el if something? el end end RUBY end it 'does not look inside inner numblocks' do expect_no_offenses(<<~RUBY) foo.#{method}(bar) do |acc, el| values.map do next el if something? _1 end end RUBY end it 'does not look inside inner itblocks', :ruby34 do expect_no_offenses(<<~RUBY) foo.#{method}(bar) do |acc, el| values.map do next el if something? it end end RUBY end it 'allows break with no value' do expect_no_offenses(<<~RUBY) foo.#{method}([]) do |acc, el| break if something? acc << el end RUBY end it 'allows the element to be the return value if the accumulator is returned in any branch' do expect_no_offenses(<<~RUBY) values.#{method}(nil) do |result, value| break result if something? value end RUBY expect_no_offenses(<<~RUBY) values.#{method}(nil) do |result, value| next value if something? result end RUBY end context 'argument count' do it 'ignores when there are not enough block arguments' do expect_no_offenses(<<~RUBY) (1..4).#{method}(0) { |acc| acc.foo } RUBY end it 'ignores when there is a splat argument' do expect_no_offenses(<<~RUBY) values.#{method}(0) { |*x| x[0] + x[1] } RUBY end it 'registers an offense when there are more than two arguments but the element is returned' do expect_offense(<<~RUBY) (1..4).each_with_index.#{method}([]) do |acc, (el, index)| acc[el] = method(index) el ^^ Ensure the accumulator `acc` will be modified by `#{method}`. end RUBY end end context 'numblocks', :ruby27 do it 'registers an offense when returning the element' do expect_offense(<<~RUBY, method: method) (1..4).#{method}(0) { _2 } _{method} ^^ Ensure the accumulator `_1` will be modified by `#{method}`. RUBY end it 'registers an offense when returning the element in the block of safe navigation method call' do expect_offense(<<~RUBY, method: method) (1..4)&.#{method}(0) { _2 } _{method} ^^ Ensure the accumulator `_1` will be modified by `#{method}`. RUBY end it 'does not register an offense when returning the accumulator' do expect_no_offenses(<<~RUBY) values.#{method}(0) { _1 + _2 } RUBY end end end end it_behaves_like 'reduce/inject', :reduce it_behaves_like 'reduce/inject', :inject 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_super_spec.rb
spec/rubocop/cop/lint/missing_super_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::MissingSuper, :config do context 'constructor' do it 'registers an offense and does not autocorrect when no `super` call' do expect_offense(<<~RUBY) class Child < Parent def initialize ^^^^^^^^^^^^^^ Call `super` to initialize state of the parent class. end end RUBY expect_no_corrections end it 'registers an offense and does not autocorrect when no `super` call and when defining some method' do expect_offense(<<~RUBY) class Child < Parent def initialize ^^^^^^^^^^^^^^ Call `super` to initialize state of the parent class. end def do_something end end RUBY expect_no_corrections end it 'does not register an offense for the class without parent class' do expect_no_offenses(<<~RUBY) class Child def initialize end end RUBY end it 'does not register an offense for the class with stateless parent class' do expect_no_offenses(<<~RUBY) class Child < Object def initialize end end RUBY end it 'does not register an offense for the `Class.new` without parent class argument' do expect_no_offenses(<<~RUBY) class Child < Parent Class.new do def initialize end end end RUBY end it 'does not register an offense for the constructor-like method defined outside of a class' do expect_no_offenses(<<~RUBY) module M def initialize end end RUBY end it 'does not register an offense when there is a `super` call' do expect_no_offenses(<<~RUBY) class Child < Parent def initialize super end end RUBY end end context '`Class.new` block' do it 'registers an offense and does not autocorrect when no `super` call' do expect_offense(<<~RUBY) Class.new(Parent) do def initialize ^^^^^^^^^^^^^^ Call `super` to initialize state of the parent class. end end RUBY expect_no_corrections end it 'does not register an offense for the `Class.new` without parent class argument' do expect_no_offenses(<<~RUBY) Class.new do def initialize end end RUBY end it 'does not register an offense for the `Class.new` with stateless parent class argument' do expect_no_offenses(<<~RUBY) Class.new(Object) do def initialize end end RUBY end end context '`Class.new` numbered block', :ruby27 do it 'registers an offense and does not autocorrect when no `super` call' do expect_offense(<<~RUBY) Class.new(Parent) do def initialize ^^^^^^^^^^^^^^ Call `super` to initialize state of the parent class. end do_something(_1) end RUBY expect_no_corrections end it 'does not register an offense for the `Class.new` without parent class argument' do expect_no_offenses(<<~RUBY) Class.new do def initialize end do_something(_1) end RUBY end it 'does not register an offense for the `Class.new` with stateless parent class argument' do expect_no_offenses(<<~RUBY) Class.new(Object) do def initialize end do_something(_1) end RUBY end end context '`Class.new` `it` block', :ruby34 do it 'registers an offense and does not autocorrect when no `super` call' do expect_offense(<<~RUBY) Class.new(Parent) do def initialize ^^^^^^^^^^^^^^ Call `super` to initialize state of the parent class. end do_something(it) end RUBY expect_no_corrections end it 'does not register an offense for the `Class.new` without parent class argument' do expect_no_offenses(<<~RUBY) Class.new do def initialize end do_something(it) end RUBY end it 'does not register an offense for the `Class.new` with stateless parent class argument' do expect_no_offenses(<<~RUBY) Class.new(Object) do def initialize end do_something(it) end RUBY end end context 'callbacks' do it 'registers no offense when module callback without `super` call' do expect_no_offenses(<<~RUBY) module M def self.included(base) end end RUBY end it 'registers an offense and does not autocorrect when class callback without `super` call' do expect_offense(<<~RUBY) class Foo def self.inherited(base) ^^^^^^^^^^^^^^^^^^^^^^^^ Call `super` to invoke callback defined in the parent class. end end RUBY expect_no_corrections end it 'registers an offense and does not autocorrect when class callback within `self << class` and without `super` call' do expect_offense(<<~RUBY) class Foo class << self def inherited(base) ^^^^^^^^^^^^^^^^^^^ Call `super` to invoke callback defined in the parent class. end end end RUBY expect_no_corrections end it 'registers an offense and does not autocorrect when method callback is without `super` call' do expect_offense(<<~RUBY) class Foo def method_added(*) ^^^^^^^^^^^^^^^^^^^ Call `super` to invoke callback defined in the parent class. end end RUBY expect_no_corrections end it 'does not register an offense when callback has a `super` call' do expect_no_offenses(<<~RUBY) class Foo def self.inherited(base) do_something super end end RUBY end end context 'with custom AllowedParentClasses config' do let(:cop_config) { { 'AllowedParentClasses' => %w[Array] } } it 'does not register an offense for a class with custom stateless parent class' do expect_no_offenses(<<~RUBY) class Child < Array def initialize 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/empty_conditional_body_spec.rb
spec/rubocop/cop/lint/empty_conditional_body_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyConditionalBody, :config do let(:cop_config) { { 'AllowComments' => true } } it 'registers an offense for missing `if` body' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. end RUBY expect_no_corrections end it 'registers an offense for missing `if` and `else` body' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. else end RUBY expect_no_corrections end it 'registers an offense for missing `if` and `else` body with some indentation' do expect_offense(<<~RUBY) def foo if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. else end end RUBY expect_no_corrections end it 'registers an offense and corrects for missing `if` body with present `else` body' do expect_offense(<<~RUBY) class Foo if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. else do_something end end RUBY expect_correction(<<~RUBY) class Foo unless condition do_something end end RUBY end # This case is registered by `Style/IfWithSemicolon` cop. Therefore, this cop does not handle it. it 'does not register an offense for missing `if` body with present `else` body on single line' do expect_no_offenses(<<~RUBY) if condition; else do_something end RUBY end it 'does not register an offense for missing `if` body with a comment' do expect_no_offenses(<<~RUBY) if condition # noop end RUBY end it 'does not register an offense for missing 2nd `if` body with a comment' do expect_no_offenses(<<~RUBY) if condition1 do_something1 end if condition2 # noop end RUBY end it 'does not register an offense for missing 2nd `elsif` body with a comment' do expect_no_offenses(<<~RUBY) if condition1 do_something1 elsif condition2 do_something2 elsif condition3 # noop end RUBY end it 'does not register an offense for missing 3rd `elsif` body with a comment' do expect_no_offenses(<<~RUBY) if condition1 do_something1 elsif condition2 do_something2 elsif condition3 do_something3 elsif condition4 # noop end RUBY end it 'registers an offense for missing `elsif` body' do expect_offense(<<~RUBY) if condition do_something1 elsif other_condition1 ^^^^^^^^^^^^^^^^^^^^^^ Avoid `elsif` branches without a body. elsif other_condition2 do_something2 end RUBY expect_no_corrections end it 'registers an offense for missing `if` and `elsif` body' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. elsif other_condition1 ^^^^^^^^^^^^^^^^^^^^^^ Avoid `elsif` branches without a body. elsif other_condition2 do_something end RUBY expect_no_corrections end it 'registers an offense for missing all branches of `if` and `elsif` body' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. elsif other_condition ^^^^^^^^^^^^^^^^^^^^^ Avoid `elsif` branches without a body. end RUBY expect_no_corrections end it 'registers an offense for missing all branches of `if` and multiple `elsif` body' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. elsif other_condition1 ^^^^^^^^^^^^^^^^^^^^^^ Avoid `elsif` branches without a body. elsif other_condition2 ^^^^^^^^^^^^^^^^^^^^^^ Avoid `elsif` branches without a body. end RUBY expect_no_corrections end it 'registers an offense and corrects for missing `if` body with `else`' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. else do_something end RUBY expect_correction(<<~RUBY) unless condition do_something end RUBY end it 'registers an offense and corrects for missing `unless` body with `else`' do expect_offense(<<~RUBY) unless condition ^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body. else do_something end RUBY expect_correction(<<~RUBY) if condition do_something end RUBY end it 'registers an offense and corrects for missing `if` body with conditional `else` body' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. else do_something if x end RUBY expect_correction(<<~RUBY) unless condition do_something if x end RUBY end it 'registers an offense and corrects for missing `unless` body with conditional `else` body' do expect_offense(<<~RUBY) unless condition ^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body. else do_something if x end RUBY expect_correction(<<~RUBY) if condition do_something if x end RUBY end it 'registers an offense for missing `unless` and `else` body' do expect_offense(<<~RUBY) unless condition ^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body. else end RUBY expect_no_corrections end it 'registers an offense for missing `if` body with `elsif`' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. elsif other_condition do_something elsif another_condition do_something_else end RUBY expect_no_corrections end it 'registers an offense for missing `elsif` body with `end` on the same line' do expect_offense(<<~RUBY) if cond_a do_a elsif cond_b;end ^^^^^^^^^^^^^ Avoid `elsif` branches without a body. RUBY expect_no_corrections end it 'registers an offense for missing `elsif` and `else` bodies with `end` on the same line' do expect_offense(<<~RUBY) if cond_a do_a elsif cond_b;else;end ^^^^^^^^^^^^^ Avoid `elsif` branches without a body. RUBY expect_no_corrections end it 'does not register an offense for missing `elsif` body with a comment' do expect_no_offenses(<<~RUBY) if condition do_something elsif other_condition # noop end RUBY end it 'registers an offense for missing `elsif` body that is not the one with a comment' do expect_offense(<<~RUBY) if condition do_something elsif other_condition ^^^^^^^^^^^^^^^^^^^^^ Avoid `elsif` branches without a body. else # noop end RUBY expect_no_corrections end it 'does not register an offense for missing `elsif` body with an inline comment' do expect_no_offenses(<<~RUBY) if condition do_something elsif other_condition # no op, but avoid going into the else else do_other_things end RUBY end it 'registers an offense for missing second `elsif` body without an inline comment' do expect_offense(<<~RUBY) if foo do_foo elsif bar do_bar elsif baz ^^^^^^^^^ Avoid `elsif` branches without a body. end RUBY expect_no_corrections end it 'registers an offense for missing `unless` body' do expect_offense(<<~RUBY) unless condition ^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body. end RUBY expect_no_corrections end it 'registers an offense when missing `if` body and using method call for return value' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. end.do_something RUBY expect_no_corrections end it 'registers an offense when missing `if` body and using safe navigation method call for return value' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. end&.do_something RUBY expect_no_corrections end it 'does not register an offense for missing `unless` body with a comment' do expect_no_offenses(<<~RUBY) unless condition # noop end RUBY end it 'registers an offense when the if is assigned to a variable' do expect_offense(<<~RUBY) x = if foo ^^^^^^ Avoid `if` branches without a body. elsif bar 5 end RUBY expect_no_corrections end it 'registers an offense when there is only one branch with assignment' do expect_offense(<<~RUBY) x = if foo ^^^^^^ Avoid `if` branches without a body. end RUBY expect_no_corrections end it 'registers an offense when there is only one branch after `||`' do expect_offense(<<~RUBY) x || if foo ^^^^^^ Avoid `if` branches without a body. end RUBY expect_no_corrections end it 'does not register an offense for an `if` with `nil` body' do expect_no_offenses(<<~RUBY) if condition nil end RUBY end it 'does not register an offense for an `unless` with `nil` body' do expect_no_offenses(<<~RUBY) unless condition nil end RUBY end it 'does not register an offense for an `elsif` with `nil` body' do expect_no_offenses(<<~RUBY) if condition do_something elsif other_condition nil end RUBY end context '>= Ruby 3.1', :ruby31 do it 'registers an offense for multi-line value omission in `unless`' do expect_offense(<<~RUBY) var = # This is the value of `other:`, like so: `other: condition || other_condition` unless object.action value:, other: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body. condition || other_condition end RUBY expect_no_corrections end end context 'when `AllowComments` is `true`' do let(:cop_config) { { 'AllowComments' => true } } it 'does not register an offense for missing `if` body with a comment' do expect_no_offenses(<<~RUBY) if condition # noop end RUBY end it 'does not register an offense for missing `elsif` body with a comment' do expect_no_offenses(<<~RUBY) if condition do_something elsif other_condition # noop end RUBY end it 'does not register an offense for missing `unless` body with a comment' do expect_no_offenses(<<~RUBY) unless condition # noop end RUBY end end context 'when `AllowComments` is `false`' do let(:cop_config) { { 'AllowComments' => false } } it 'registers an offense for missing `if` body with a comment' do expect_offense(<<~RUBY) if condition ^^^^^^^^^^^^ Avoid `if` branches without a body. # noop end RUBY expect_no_corrections end it 'registers an offense for missing `elsif` body with a comment' do expect_offense(<<~RUBY) if condition do_something elsif other_condition ^^^^^^^^^^^^^^^^^^^^^ Avoid `elsif` branches without a body. # noop end RUBY expect_no_corrections end it 'registers an offense for missing `unless` body with a comment' do expect_offense(<<~RUBY) unless condition ^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body. # noop 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/binary_operator_with_identical_operands_spec.rb
spec/rubocop/cop/lint/binary_operator_with_identical_operands_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::BinaryOperatorWithIdenticalOperands, :config do %i[== != === <=> =~ && || > >= < <= | ^].each do |operator| it "registers an offense for `#{operator}` with duplicate operands" do expect_offense(<<~RUBY, operator: operator) y = a.x(arg) %{operator} a.x(arg) ^^^^^^^^^^{operator}^^^^^^^^^ Binary operator `%{operator}` has identical operands. RUBY end end %i[- + * / ** << >>].each do |operator| it "does not register an offense for `#{operator}` with duplicate operands" do expect_no_offenses(<<~RUBY) y = a.x(arg) #{operator} a.x(arg) RUBY end end it 'does not register an offense when using binary operator with different operands' do expect_no_offenses(<<~RUBY) x == y y = x && z y = a.x + b.x a.x(arg) > b.x(arg) a.(x) > b.(x) RUBY end it 'does not register an offense when using arithmetic operator with numerics' do expect_no_offenses(<<~RUBY) x = 2 + 2 x = 1 << 1 RUBY end it 'does not crash on operator without any argument' 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/ambiguous_range_spec.rb
spec/rubocop/cop/lint/ambiguous_range_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::AmbiguousRange, :config do { 'irange' => '..', 'erange' => '...' }.each do |node_type, operator| context "for an #{node_type}" do it 'registers an offense and corrects when not parenthesized' do expect_offense(<<~RUBY) x || 1#{operator}2 ^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (x || 1)#{operator}2 RUBY end it 'registers an offense and corrects when boundary is an operator expression' do expect_offense(<<~RUBY) x - 1#{operator}2 ^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (x - 1)#{operator}2 RUBY end it 'registers an offense and corrects when the entire range is parenthesized but contains complex boundaries' do expect_offense(<<~RUBY) (x || 1#{operator}2) ^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) ((x || 1)#{operator}2) RUBY end it 'registers an offense and corrects when there are clauses on both sides' do expect_offense(<<~RUBY, operator: operator) x || 1#{operator}y || 2 _{operator}^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. ^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (x || 1)#{operator}(y || 2) RUBY end it 'registers an offense and corrects when one side is parenthesized but the other is not' do expect_offense(<<~RUBY, operator: operator) (x || 1)#{operator}y || 2 _{operator}^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (x || 1)#{operator}(y || 2) RUBY end it 'does not register an offense if the range is parenthesized' do expect_no_offenses(<<~RUBY) x || (1#{operator}2) (x || 1)#{operator}2 RUBY end it 'does not register an offense when boundary is an element reference' do expect_no_offenses(<<~RUBY) x[1]#{operator}2 RUBY end it 'does not register an offense if the range is composed of literals' do expect_no_offenses(<<~RUBY) 1#{operator}2 'a'#{operator}'z' "\#{foo}-\#{bar}"#{operator}'123-4567' `date`#{operator}'foobar' :"\#{foo}-\#{bar}"#{operator}:baz /a/#{operator}/b/ 42#{operator}nil RUBY end it 'does not register an offense for a variable' do expect_no_offenses(<<~RUBY) @a#{operator}@b RUBY end it 'does not register an offense for a constant' do expect_no_offenses(<<~RUBY) Foo::MIN#{operator}Foo::MAX RUBY end it 'does not register an offense for `self`' do expect_no_offenses(<<~RUBY) self#{operator}42 42#{operator}self RUBY end it 'can handle an endless range', :ruby26 do expect_offense(<<~RUBY) x || 1#{operator} ^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (x || 1)#{operator} RUBY end it 'can handle a beginningless range', :ruby27 do expect_offense(<<~RUBY, operator: operator) #{operator}y || 1 _{operator}^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) #{operator}(y || 1) RUBY end context 'method calls' do shared_examples 'common behavior' do it 'does not register an offense for a non-chained method call' do expect_no_offenses(<<~RUBY) a#{operator}b RUBY end it 'does not register an offense for a unary +' do expect_no_offenses(<<~RUBY) +a#{operator}10 RUBY end it 'does not register an offense for a unary -' do expect_no_offenses(<<~RUBY) -a#{operator}10 RUBY end it 'does not register an offense for rational literals' do expect_no_offenses(<<~RUBY) 1/10r#{operator}1/3r RUBY end it 'requires parens when calling a method on a basic literal' do expect_offense(<<~RUBY, operator: operator) 1#{operator}2.to_a _{operator}^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) 1#{operator}(2.to_a) RUBY end end context 'with RequireParenthesesForMethodChains: true' do let(:cop_config) { { 'RequireParenthesesForMethodChains' => true } } it_behaves_like 'common behavior' it 'registers an offense for a chained method call without parens' do expect_offense(<<~RUBY) foo.bar#{operator}10 ^^^^^^^ Wrap complex range boundaries with parentheses to avoid ambiguity. RUBY expect_correction(<<~RUBY) (foo.bar)#{operator}10 RUBY end it 'does not register an offense for a chained method call with parens' do expect_no_offenses(<<~RUBY) (foo.bar)#{operator}10 RUBY end end context 'with RequireParenthesesForMethodChains: false' do let(:cop_config) { { 'RequireParenthesesForMethodChains' => false } } it_behaves_like 'common behavior' it 'does not register an offense for a chained method call without parens' do expect_no_offenses(<<~RUBY) foo.bar#{operator}10 RUBY end it 'does not register an offense for a chained method call with parens' do expect_no_offenses(<<~RUBY) (foo.bar)#{operator}10 RUBY end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/shadowed_exception_spec.rb
spec/rubocop/cop/lint/shadowed_exception_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ShadowedException, :config do context 'modifier rescue' do it 'accepts rescue in its modifier form' do expect_no_offenses('foo rescue nil') end end context 'single rescue' do it 'accepts an empty rescue' do expect_no_offenses(<<~RUBY) begin something rescue handle_exception end RUBY end it 'accepts rescuing a single exception' do expect_no_offenses(<<~RUBY) begin something rescue Exception handle_exception end RUBY end it 'rescue an exception without causing constant name deprecation warning' do expect do expect_no_offenses(<<~RUBY) def foo something rescue TimeoutError handle_exception end RUBY end.not_to output(/.*TimeoutError is deprecated/).to_stderr end it 'accepts rescuing a single custom exception' do expect_no_offenses(<<~RUBY) begin something rescue NonStandardException handle_exception end RUBY end it 'accepts rescuing a custom exception and a standard exception' do expect_no_offenses(<<~RUBY) begin something rescue Error, NonStandardException handle_exception end RUBY end it 'accepts rescuing multiple custom exceptions' do expect_no_offenses(<<~RUBY) begin something rescue CustomError, NonStandardException handle_exception end RUBY end it 'accepts rescue containing multiple same error code exceptions' do # System dependent error code depends on runtime environment. stub_const('Errno::EAGAIN::Errno', 35) stub_const('Errno::EWOULDBLOCK::Errno', 35) stub_const('Errno::ECONNABORTED::Errno', 53) expect_no_offenses(<<~RUBY) begin something rescue Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::ECONNABORTED handle_exception end RUBY end it 'registers an offense rescuing exceptions that are ancestors of each other' do expect_offense(<<~RUBY) def foo something rescue StandardError, RuntimeError ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. handle_exception end RUBY end it 'registers an offense rescuing Exception with any other error or exception' do expect_offense(<<~RUBY) begin something rescue NonStandardError, Exception ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. handle_exception end RUBY end it 'accepts rescuing a single exception that is assigned to a variable' do expect_no_offenses(<<~RUBY) begin something rescue Exception => e handle_exception(e) end RUBY end it 'accepts rescuing a single exception that has an ensure' do expect_no_offenses(<<~RUBY) begin something rescue Exception handle_exception ensure everything_is_ok end RUBY end it 'accepts rescuing a single exception that has an else' do expect_no_offenses(<<~RUBY) begin something rescue Exception handle_exception else handle_non_exception end RUBY end it 'accepts rescuing a multiple exceptions that are not ancestors that have an else' do expect_no_offenses(<<~RUBY) begin something rescue NoMethodError, ZeroDivisionError handle_exception else handle_non_exception end RUBY end context 'when there are multiple levels of exceptions in the same rescue' do it 'registers an offense for two exceptions' do expect_offense(<<~RUBY) begin something rescue StandardError, NameError ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. foo end RUBY end it 'registers an offense for more than two exceptions' do expect_offense(<<~RUBY) begin something rescue StandardError, NameError, NoMethodError ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. foo end RUBY end end it 'registers an offense for the same exception multiple times' do expect_offense(<<~RUBY) begin something rescue NameError, NameError ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. foo end RUBY end it 'accepts splat arguments passed to rescue' do expect_no_offenses(<<~RUBY) begin a rescue *FOO b end RUBY end end context 'multiple rescues' do it 'registers an offense when a higher level exception is rescued before ' \ 'a lower level exception' do expect_offense(<<~RUBY) begin something rescue NoMethodError handle_no_method_error rescue Exception ^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. handle_exception rescue StandardError handle_standard_error end RUBY end it 'registers an offense when a higher level exception is rescued before ' \ 'a lower level exception when there are multiple exceptions ' \ 'rescued in a group' do expect_offense(<<~RUBY) begin something rescue Exception ^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. handle_exception rescue NoMethodError, ZeroDivisionError handle_standard_error end RUBY end it 'registers an offense for two exceptions when there are ' \ 'multiple levels of exceptions in the same rescue' do expect_offense(<<~RUBY) begin something rescue ZeroDivisionError handle_exception rescue NoMethodError, StandardError ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. handle_standard_error end RUBY end it 'registers an offense rescuing out of order exceptions when there is an ensure' do expect_offense(<<~RUBY) begin something rescue Exception ^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. handle_exception rescue StandardError handle_standard_error ensure everything_is_ok end RUBY end it 'accepts rescuing exceptions in order of level' do expect_no_offenses(<<~RUBY) begin something rescue StandardError handle_standard_error rescue Exception handle_exception end RUBY end it 'accepts many (>= 7) rescue groups' do expect_no_offenses(<<~RUBY) begin something rescue StandardError handle_error rescue ErrorA handle_error rescue ErrorB handle_error rescue ErrorC handle_error rescue ErrorD handle_error rescue ErrorE handle_error rescue ErrorF handle_error end RUBY end it 'accepts rescuing exceptions in order of level with multiple exceptions in a group' do expect_no_offenses(<<~RUBY) begin something rescue NoMethodError, ZeroDivisionError handle_standard_error rescue Exception handle_exception end RUBY end it 'accepts rescuing exceptions in order of level with multiple ' \ 'exceptions in a group with custom exceptions' do expect_no_offenses(<<~RUBY) begin something rescue NonStandardError, NoMethodError handle_standard_error rescue Exception handle_exception end RUBY end it 'accepts rescuing custom exceptions in multiple rescue groups' do expect_no_offenses(<<~RUBY) begin something rescue NonStandardError, OtherError handle_standard_error rescue CustomError handle_exception end RUBY end context 'splat arguments' do it 'accepts splat arguments passed to multiple rescues' do expect_no_offenses(<<~RUBY) begin a rescue *FOO b rescue *BAR c end RUBY end it 'does not register an offense for splat arguments rescued after ' \ 'rescuing a known exception' do expect_no_offenses(<<~RUBY) begin a rescue StandardError b rescue *BAR c end RUBY end it 'registers an offense for splat arguments rescued after rescuing Exception' do expect_offense(<<~RUBY) begin a rescue Exception ^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. b rescue *BAR c end RUBY end end context 'exceptions from different ancestry chains' do it 'accepts rescuing exceptions in one order' do expect_no_offenses(<<~RUBY) begin a rescue ArgumentError b rescue Interrupt c end RUBY end it 'accepts rescuing exceptions in another order' do expect_no_offenses(<<~RUBY) begin a rescue Interrupt b rescue ArgumentError c end RUBY end end it 'accepts rescuing a known exception after an unknown exceptions' do expect_no_offenses(<<~RUBY) begin a rescue UnknownException b rescue StandardError c end RUBY end it 'accepts rescuing a known exception before an unknown exceptions' do expect_no_offenses(<<~RUBY) begin a rescue StandardError b rescue UnknownException c end RUBY end it 'accepts rescuing a known exception between unknown exceptions' do expect_no_offenses(<<~RUBY) begin a rescue UnknownException b rescue StandardError c rescue AnotherUnknownException d end RUBY end it 'registers an offense rescuing Exception before an unknown exceptions' do expect_offense(<<~RUBY) begin a rescue Exception ^^^^^^^^^^^^^^^^ Do not shadow rescued Exceptions. b rescue UnknownException c end RUBY end it 'ignores expressions of non-const' do expect_no_offenses(<<~RUBY) begin a rescue foo b rescue [bar] c end RUBY end context 'last rescue does not specify exception class' do it 'highlights range ending at rescue keyword' do expect_no_offenses(<<~RUBY) begin rescue A, B do_something rescue C do_something rescue do_something 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/or_assignment_to_constant_spec.rb
spec/rubocop/cop/lint/or_assignment_to_constant_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::OrAssignmentToConstant, :config do it 'registers an offense with or-assignment to a constant' do expect_offense(<<~RUBY) CONST ||= 1 ^^^ Avoid using or-assignment with constants. RUBY expect_correction(<<~RUBY) CONST = 1 RUBY end it 'registers an offense with or-assignment to a constant in method definition' do expect_offense(<<~RUBY) def foo M::CONST ||= 1 ^^^ Avoid using or-assignment with constants. end RUBY expect_no_corrections end it 'registers an offense with or-assignment to a constant in singleton method definition' do expect_offense(<<~RUBY) def self.foo M::CONST ||= 1 ^^^ Avoid using or-assignment with constants. end RUBY expect_no_corrections end it 'registers an offense with or-assignment to a constant in method definition using `define_method`' do expect_offense(<<~RUBY) define_method :foo do M::CONST ||= 1 ^^^ Avoid using or-assignment with constants. end RUBY expect_correction(<<~RUBY) define_method :foo do M::CONST = 1 end RUBY end it 'does not register an offense with plain assignment to a constant' do expect_no_offenses(<<~RUBY) CONST = 1 RUBY end [ ['a local variable', 'var'], ['an instance variable', '@var'], ['a class variable', '@@var'], ['a global variable', '$var'], ['an attribute', 'self.var'] ].each do |type, var| it "does not register an offense with or-assignment to #{type}" do expect_no_offenses(<<~RUBY) #{var} ||= 1 RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/redundant_dir_glob_sort_spec.rb
spec/rubocop/cop/lint/redundant_dir_glob_sort_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantDirGlobSort, :config do context 'when Ruby 3.0 or higher', :ruby30 do it 'registers an offense and correction when using `Dir.glob.sort`' do expect_offense(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb')).sort.each(&method(:require)) ^^^^ Remove redundant `sort`. RUBY expect_correction(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb')).each(&method(:require)) RUBY end it 'registers an offense and correction when using `::Dir.glob.sort`' do expect_offense(<<~RUBY) ::Dir.glob(Rails.root.join('test', '*.rb')).sort.each(&method(:require)) ^^^^ Remove redundant `sort`. RUBY expect_correction(<<~RUBY) ::Dir.glob(Rails.root.join('test', '*.rb')).each(&method(:require)) RUBY end it 'registers an offense and correction when using `Dir[].sort.each do`' do expect_offense(<<~RUBY) Dir['./lib/**/*.rb'].sort.each do |file| ^^^^ Remove redundant `sort`. end RUBY expect_correction(<<~RUBY) Dir['./lib/**/*.rb'].each do |file| end RUBY end it 'registers an offense and correction when using `Dir[].sort.each(&do_something)`' do expect_offense(<<~RUBY) Dir['./lib/**/*.rb'].sort.each(&method(:require)) ^^^^ Remove redundant `sort`. RUBY expect_correction(<<~RUBY) Dir['./lib/**/*.rb'].each(&method(:require)) RUBY end it 'does not register an offense when not using `sort` with `sort: false` option for `Dir`' do expect_no_offenses(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb'), sort: false).each do end RUBY end it "does not register an offense when using `Dir.glob('./b/*.txt', './a/*.txt').sort`" do expect_no_offenses(<<~RUBY) Dir.glob('./b/*.txt', './a/*.txt').sort.each(&method(:require)) RUBY end it 'does not register an offense when using `Dir.glob(*path).sort`' do expect_no_offenses(<<~RUBY) Dir.glob(*path).sort.each(&method(:require)) RUBY end it "does not register an offense when using `Dir['./b/*.txt', './a/*.txt'].sort`" do expect_no_offenses(<<~RUBY) Dir['./b/*.txt', './a/*.txt'].sort.each(&method(:require)) RUBY end it 'does not register an offense when using `Dir[*path].sort`' do expect_no_offenses(<<~RUBY) Dir[*path].sort.each(&method(:require)) RUBY end it 'does not register an offense when using `collection.sort`' do expect_no_offenses(<<~RUBY) collection.sort RUBY end end context 'when Ruby 2.7 or lower', :ruby27, unsupported_on: :prism do it 'does not register an offense when using `Dir.glob.sort`' do expect_no_offenses(<<~RUBY) Dir.glob(Rails.root.join('test', '*.rb')).sort.each(&method(:require)) RUBY end it 'does not register an offense when using `::Dir.glob.sort`' do expect_no_offenses(<<~RUBY) ::Dir.glob(Rails.root.join('test', '*.rb')).sort.each(&method(:require)) RUBY end it 'does not register an offense when using `Dir[].sort.each do`' do expect_no_offenses(<<~RUBY) Dir['./lib/**/*.rb'].sort.each do |file| end RUBY end it 'does not register an offense when using `Dir[].sort.each(&do_something)`' do expect_no_offenses(<<~RUBY) Dir['./lib/**/*.rb'].sort.each(&method(:require)) RUBY end end it 'does not register an offense when not using `sort` for `Dir`' do expect_no_offenses(<<~RUBY) Dir['./lib/**/*.rb'].each do |file| end RUBY end it 'does not register an offense when using `sort` without a receiver' do expect_no_offenses(<<~RUBY) sort.do_something RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/redundant_with_object_spec.rb
spec/rubocop/cop/lint/redundant_with_object_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RedundantWithObject, :config do it 'registers an offense and corrects when using `ary.each_with_object { |v| v }`' do expect_offense(<<~RUBY) ary.each_with_object([]) { |v| v } ^^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. RUBY expect_correction(<<~RUBY) ary.each { |v| v } RUBY end it 'registers an offense and corrects when using `ary&.each_with_object { |v| v }`' do expect_offense(<<~RUBY) ary&.each_with_object([]) { |v| v } ^^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. RUBY expect_correction(<<~RUBY) ary&.each { |v| v } RUBY end it 'registers an offense and corrects when using `ary.each.with_object([]) { |v| v }`' do expect_offense(<<~RUBY) ary.each.with_object([]) { |v| v } ^^^^^^^^^^^^^^^ Remove redundant `with_object`. RUBY expect_correction(<<~RUBY) ary.each { |v| v } RUBY end it 'registers an offense and corrects when using ary.each_with_object([]) do-end block' do expect_offense(<<~RUBY) ary.each_with_object([]) do |v| ^^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. v end RUBY expect_correction(<<~RUBY) ary.each do |v| v end RUBY end it 'registers an offense and corrects when using ' \ 'ary.each_with_object do-end block without parentheses' do expect_offense(<<~RUBY) ary.each_with_object [] do |v| ^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. v end RUBY expect_correction(<<~RUBY) ary.each do |v| v end RUBY end it 'an object is used as a block argument' do expect_no_offenses('ary.each_with_object([]) { |v, o| v; o }') end context 'when missing argument to `each_with_object`' do it 'does not register an offense when block has 2 arguments' do expect_no_offenses('ary.each_with_object { |v, o| v; o }') end it 'does not register an offense when block has 1 argument' do expect_no_offenses('ary.each_with_object { |v| v }') end end context 'Ruby 2.7', :ruby27 do it 'registers an offense and corrects when using `ary.each_with_object { _1 }`' do expect_offense(<<~RUBY) ary.each_with_object([]) { _1 } ^^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. RUBY expect_correction(<<~RUBY) ary.each { _1 } RUBY end it 'registers an offense and corrects when using `ary&.each_with_object { _1 }`' do expect_offense(<<~RUBY) ary&.each_with_object([]) { _1 } ^^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. RUBY expect_correction(<<~RUBY) ary&.each { _1 } RUBY end it 'registers an offense and corrects when using `ary.each.with_object([]) { _1 }`' do expect_offense(<<~RUBY) ary.each.with_object([]) { _1 } ^^^^^^^^^^^^^^^ Remove redundant `with_object`. RUBY expect_correction(<<~RUBY) ary.each { _1 } RUBY end end context 'Ruby 3.4', :ruby34 do it 'registers an offense and corrects when using `ary.each_with_object { it }`' do expect_offense(<<~RUBY) ary.each_with_object([]) { it } ^^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. RUBY expect_correction(<<~RUBY) ary.each { it } RUBY end it 'registers an offense and corrects when using `ary&.each_with_object { it }`' do expect_offense(<<~RUBY) ary&.each_with_object([]) { it } ^^^^^^^^^^^^^^^^^^^^ Use `each` instead of `each_with_object`. RUBY expect_correction(<<~RUBY) ary&.each { it } RUBY end it 'registers an offense and corrects when using `ary.each.with_object([]) { it }`' do expect_offense(<<~RUBY) ary.each.with_object([]) { it } ^^^^^^^^^^^^^^^ Remove redundant `with_object`. RUBY expect_correction(<<~RUBY) ary.each { it } RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/useless_or_spec.rb
spec/rubocop/cop/lint/useless_or_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessOr, :config do described_class::TRUTHY_RETURN_VALUE_METHODS.each do |method| it "registers an offense with `x.#{method} || fallback`" do expect_offense(<<~RUBY, method: method) x.#{method} || fallback _{method} ^^^^^^^^^^^ `fallback` will never evaluate because `x.#{method}` always returns a truthy value. RUBY expect_correction(<<~RUBY) x.#{method} RUBY end it "registers an offense with `x.#{method} or fallback`" do expect_offense(<<~RUBY, method: method) x.#{method} or fallback _{method} ^^^^^^^^^^^ `fallback` will never evaluate because `x.#{method}` always returns a truthy value. RUBY expect_correction(<<~RUBY) x.#{method} RUBY end it "registers an offense with `x.#{method} || fallback || other_fallback`" do expect_offense(<<~RUBY, method: method) x.#{method} || fallback || other_fallback _{method} ^^^^^^^^^^^ `fallback` will never evaluate because `x.#{method}` always returns a truthy value. RUBY expect_correction(<<~RUBY) x.#{method} RUBY end it "registers an offense with `foo || x.#{method} || fallback`" do expect_offense(<<~RUBY, method: method) foo || x.#{method} || fallback _{method} ^^^^^^^^^^^ `fallback` will never evaluate because `x.#{method}` always returns a truthy value. RUBY expect_correction(<<~RUBY) foo || x.#{method} RUBY end it "registers an offense with `(foo || x.#{method}) || fallback`" do expect_offense(<<~RUBY, method: method) (foo || x.#{method}) || fallback _{method} ^^^^^^^^^^^ `fallback` will never evaluate because `x.#{method}` always returns a truthy value. RUBY expect_correction(<<~RUBY) (foo || x.#{method}) RUBY end it "does not register an offense with `(foo || x.#{method}) && operand`" do expect_no_offenses(<<~RUBY) (foo || x.#{method}) && operand RUBY end it "does not register an offense with `foo || x.#{method}`" do expect_no_offenses(<<~RUBY) foo || x.#{method} RUBY end it "does not register an offense with `x&.#{method} || fallback`" do expect_no_offenses(<<~RUBY) x&.#{method} || fallback RUBY end it "does not register an offense with `x.#{method}`" do expect_no_offenses(<<~RUBY) x.#{method} RUBY end end it 'does not register an offense with `x.foo || fallback`' do expect_no_offenses(<<~RUBY) x.foo || fallback 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/nested_percent_literal_spec.rb
spec/rubocop/cop/lint/nested_percent_literal_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::NestedPercentLiteral, :config do it 'registers no offense for empty array' do expect_no_offenses('%i[]') end it 'registers no offense for array' do expect_no_offenses('%i[a b c d xyz]') end it 'registers no offense for percent modifier character in isolation' do expect_no_offenses('%i[% %i %I %q %Q %r %s %w %W %x]') end it 'registers no offense for nestings under percent' do expect_no_offenses('%[a b %[c d] xyz]') expect_no_offenses('%[a b %i[c d] xyz]') end it 'registers no offense for percents in the middle of literals' do expect_no_offenses('%w[1%+ 2]') end it 'registers an offense for nested percent literals' do expect_offense(<<~RUBY) %i[a b %i[c d] xyz] ^^^^^^^^^^^^^^^^^^^ Within percent literals, nested percent literals do not function and may be unwanted in the result. RUBY end it 'registers an offense for repeated nested percent literals' do expect_offense(<<~RUBY) %i[a b %i[c d] %i[xyz]] ^^^^^^^^^^^^^^^^^^^^^^^ Within percent literals, nested percent literals do not function and may be unwanted in the result. RUBY end it 'registers an offense for multiply nested percent literals' do # TODO: This emits only one offense for the entire snippet, though it # would be more correct to emit two offenses. This is tricky to fix, as # the AST parses %i[b, %i[c, and d]] as separate tokens. expect_offense(<<~RUBY) %i[a %i[b %i[c d]] xyz] ^^^^^^^^^^^^^^^^^^^^^^^ Within percent literals, nested percent literals do not function and may be unwanted in the result. RUBY end context 'when handling invalid UTF8 byte sequence' do it 'registers no offense for array' do expect_no_offenses('%W[\xff]') end it 'registers an offense for nested percent literal' do expect_offense(<<~RUBY) %W[\\xff %W[]] ^^^^^^^^^^^^^ Within percent literals, nested percent literals do not function and may be unwanted in the result. 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_assignment_spec.rb
spec/rubocop/cop/lint/ambiguous_assignment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::AmbiguousAssignment, :config do described_class::MISTAKES.each_key do |mistake| operator = mistake[1] %i[x @x @@x $x X].each do |lhs| it "registers an offense when using `#{operator}` with `#{lhs}`" do expect_offense(<<~RUBY, operator: operator, lhs: lhs) %{lhs} =%{operator} y _{lhs} ^^{operator} Suspicious assignment detected. Did you mean `%{operator}=`? RUBY end it 'does not register an offense when no mistype assignments' do expect_no_offenses(<<~RUBY) x #{operator}= y x = #{operator}y 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/self_assignment_spec.rb
spec/rubocop/cop/lint/self_assignment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SelfAssignment, :config do it 'registers an offense when using local var self-assignment' do expect_offense(<<~RUBY) foo = foo ^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using local var assignment' do expect_no_offenses(<<~RUBY) foo = bar RUBY end it 'registers an offense when using instance var self-assignment' do expect_offense(<<~RUBY) @foo = @foo ^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using instance var assignment' do expect_no_offenses(<<~RUBY) @foo = @bar RUBY end it 'registers an offense when using class var self-assignment' do expect_offense(<<~RUBY) @@foo = @@foo ^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using class var assignment' do expect_no_offenses(<<~RUBY) @@foo = @@bar RUBY end it 'registers an offense when using global var self-assignment' do expect_offense(<<~RUBY) $foo = $foo ^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using global var assignment' do expect_no_offenses(<<~RUBY) $foo = $bar RUBY end it 'registers an offense when using constant var self-assignment' do expect_offense(<<~RUBY) Foo = Foo ^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using constant var assignment for constant from another scope' do expect_no_offenses(<<~RUBY) Foo = ::Foo RUBY end it 'does not register an offense when using constant var or-assignment for constant from another scope' do expect_no_offenses(<<~RUBY) Foo ||= ::Foo RUBY end it 'registers an offense when using multiple var self-assignment' do expect_offense(<<~RUBY) foo, bar = foo, bar ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'registers an offense when using multiple var self-assignment through array' do expect_offense(<<~RUBY) foo, bar = [foo, bar] ^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using multiple var assignment' do expect_no_offenses(<<~RUBY) foo, bar = bar, foo RUBY end it 'does not register an offense when using multiple var assignment through splat' do expect_no_offenses(<<~RUBY) foo, bar = *something RUBY end it 'does not register an offense when using multiple var assignment through method call' do expect_no_offenses(<<~RUBY) foo, bar = something RUBY end it 'registers an offense when using shorthand-or var self-assignment' do expect_offense(<<~RUBY) foo ||= foo ^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using shorthand-or var assignment' do expect_no_offenses(<<~RUBY) foo ||= bar RUBY end it 'registers an offense when using shorthand-and var self-assignment' do expect_offense(<<~RUBY) foo &&= foo ^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using shorthand-and var assignment' do expect_no_offenses(<<~RUBY) foo &&= bar RUBY end it 'registers an offense when using attribute self-assignment' do expect_offense(<<~RUBY) foo.bar = foo.bar ^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'registers an offense when using attribute self-assignment with a safe navigation call' do expect_offense(<<~RUBY) foo&.bar = foo&.bar ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using attribute assignment with different attributes' do expect_no_offenses(<<~RUBY) foo.bar = foo.baz RUBY end it 'does not register an offense when using attribute assignment with different receivers' do expect_no_offenses(<<~RUBY) bar.foo = baz.foo RUBY end it 'does not register an offense when using attribute assignment with extra expression' do expect_no_offenses(<<~RUBY) foo.bar = foo.bar + 1 RUBY end it 'does not register an offense when using attribute assignment with method call with arguments' do expect_no_offenses(<<~RUBY) foo.bar = foo.bar(arg) RUBY end it 'does not register an offense when using attribute assignment with literals' do expect_no_offenses(<<~RUBY) foo.bar = true RUBY end it 'registers an offense when using []= self-assignment with same string literals' do expect_offense(<<~RUBY) foo["bar"] = foo["bar"] ^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different string literals' do expect_no_offenses(<<~RUBY) foo["bar"] = foo["baz"] RUBY end it 'registers an offense when using []= self-assignment with same integer literals' do expect_offense(<<~RUBY) foo[1] = foo[1] ^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different integer literals' do expect_no_offenses(<<~RUBY) foo[1] = foo[2] RUBY end it 'registers an offense when using []= self-assignment with same float literals' do expect_offense(<<~RUBY) foo[1.2] = foo[1.2] ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different float literals' do expect_no_offenses(<<~RUBY) foo[1.2] = foo[2.2] RUBY end it 'registers an offense when using []= self-assignment with same constant reference' do expect_offense(<<~RUBY) foo[Foo] = foo[Foo] ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different constant references' do expect_no_offenses(<<~RUBY) foo[Foo] = foo[Bar] RUBY end it 'registers an offense when using []= self-assignment with same symbol literals' do expect_offense(<<~RUBY) foo[:bar] = foo[:bar] ^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different symbol literals' do expect_no_offenses(<<~RUBY) foo[:foo] = foo[:bar] RUBY end it 'registers an offense when using []= self-assignment with same local variables' do expect_offense(<<~RUBY) var = 1 foo[var] = foo[var] ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different local variables' do expect_no_offenses(<<~RUBY) var1 = 1 var2 = 2 foo[var1] = foo[var2] RUBY end it 'registers an offense when using []= self-assignment with same instance variables' do expect_offense(<<~RUBY) foo[@var] = foo[@var] ^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different instance variables' do expect_no_offenses(<<~RUBY) foo[@var1] = foo[@var2] RUBY end it 'registers an offense when using []= self-assignment with same class variables' do expect_offense(<<~RUBY) foo[@@var] = foo[@@var] ^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different class variables' do expect_no_offenses(<<~RUBY) foo[@@var1] = foo[@@var2] RUBY end it 'registers an offense when using []= self-assignment with same global variables' do expect_offense(<<~RUBY) foo[$var] = foo[$var] ^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using []= self-assignment with different global variables' do expect_no_offenses(<<~RUBY) foo[$var1] = foo[$var2] RUBY end it 'does not register an offense when using []= assignment with method calls' do expect_no_offenses(<<~RUBY) foo[bar] = foo[bar] RUBY end it 'does not register an offense when using []= assignment with different receivers' do expect_no_offenses(<<~RUBY) bar["foo"] = baz["foo"] RUBY end it 'does not register an offense when using []= assignment with extra expression' do expect_no_offenses(<<~RUBY) foo["bar"] = foo["bar"] + 1 RUBY end it 'registers an offense when using []= self-assignment with a safe navigation method call' do expect_offense(<<~RUBY) foo&.[]=("bar", foo["bar"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'registers an offense when ussing `[]=` self-assignment with multiple key arguments' do expect_offense(<<~RUBY) matrix[1, 2] = matrix[1, 2] ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when ussing `[]=` self-assignment with multiple key arguments with arguments mismatch' do expect_no_offenses(<<~RUBY) matrix[1, 2] = matrix[1, 3] RUBY end it 'does not register an offense when ussing `[]=` self-assignment with multiple key arguments with method call argument' do expect_no_offenses(<<~RUBY) matrix[1, foo] = matrix[1, foo] RUBY end it 'registers an offense when ussing `[]=` self-assignment with using zero key arguments' do expect_offense(<<~RUBY) singleton[] = singleton[] ^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'does not register an offense when using `[]=` assignment with no arguments' do expect_no_offenses(<<~RUBY) foo.[]= RUBY end describe 'RBS::Inline annotation' do context 'when config option is disabled' do let(:cop_config) { { 'AllowRBSInlineAnnotation' => false } } it 'registers offenses and it has a comment' do expect_offense(<<~RUBY) foo = foo #: Integer ^^^^^^^^^ Self-assignment detected. @foo = @foo #: Integer ^^^^^^^^^^^ Self-assignment detected. @@foo = @@foo #: Integer ^^^^^^^^^^^^^ Self-assignment detected. $foo = $foo #: Integer ^^^^^^^^^^^ Self-assignment detected. Foo = Foo #: Integer ^^^^^^^^^ Self-assignment detected. foo, bar = foo, bar #: Integer ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo ||= foo #: Integer ^^^^^^^^^^^ Self-assignment detected. foo &&= foo #: Integer ^^^^^^^^^^^ Self-assignment detected. foo.bar = foo.bar #: Integer ^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.bar = foo&.bar #: Integer ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo["bar"] = foo["bar"] #: Integer ^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.[]=("bar", foo["bar"]) #: Integer ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end it 'registers an offense and it has a no comment' do expect_offense(<<~RUBY) foo = foo ^^^^^^^^^ Self-assignment detected. @foo = @foo ^^^^^^^^^^^ Self-assignment detected. @@foo = @@foo ^^^^^^^^^^^^^ Self-assignment detected. $foo = $foo ^^^^^^^^^^^ Self-assignment detected. Foo = Foo ^^^^^^^^^ Self-assignment detected. foo, bar = foo, bar ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo ||= foo ^^^^^^^^^^^ Self-assignment detected. foo &&= foo ^^^^^^^^^^^ Self-assignment detected. foo.bar = foo.bar ^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.bar = foo&.bar ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo["bar"] = foo["bar"] ^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.[]=("bar", foo["bar"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo = foo # comment ^^^^^^^^^ Self-assignment detected. @foo = @foo # comment ^^^^^^^^^^^ Self-assignment detected. @@foo = @@foo # comment ^^^^^^^^^^^^^ Self-assignment detected. $foo = $foo # comment ^^^^^^^^^^^ Self-assignment detected. Foo = Foo # comment ^^^^^^^^^ Self-assignment detected. foo, bar = foo, bar # comment ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo ||= foo # comment ^^^^^^^^^^^ Self-assignment detected. foo &&= foo # comment ^^^^^^^^^^^ Self-assignment detected. foo.bar = foo.bar # comment ^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.bar = foo&.bar # comment ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo["bar"] = foo["bar"] # comment ^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.[]=("bar", foo["bar"]) # comment ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. RUBY end end context 'when config option is enabled' do let(:cop_config) { { 'AllowRBSInlineAnnotation' => true } } it 'does not register an offense and it has a comment' do expect_no_offenses(<<~RUBY) foo = foo #: Integer @foo = @foo #: Integer @@foo = @@foo #: Integer $foo = $foo #: Integer Foo = Foo #: Integer foo, bar = foo, bar #: Integer foo ||= foo #: Integer foo &&= foo #: Integer foo.bar = foo.bar #: Integer foo&.bar = foo&.bar #: Integer foo["bar"] = foo["bar"] #: Integer foo&.[]=("bar", foo["bar"]) #: Integer RUBY end it 'registers an offense and it has a no comment' do expect_offense(<<~RUBY) foo = foo ^^^^^^^^^ Self-assignment detected. @foo = @foo ^^^^^^^^^^^ Self-assignment detected. @@foo = @@foo ^^^^^^^^^^^^^ Self-assignment detected. $foo = $foo ^^^^^^^^^^^ Self-assignment detected. Foo = Foo ^^^^^^^^^ Self-assignment detected. foo, bar = foo, bar ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo ||= foo ^^^^^^^^^^^ Self-assignment detected. foo &&= foo ^^^^^^^^^^^ Self-assignment detected. foo.bar = foo.bar ^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.bar = foo&.bar ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo["bar"] = foo["bar"] ^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.[]=("bar", foo["bar"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo = foo # comment ^^^^^^^^^ Self-assignment detected. @foo = @foo # comment ^^^^^^^^^^^ Self-assignment detected. @@foo = @@foo # comment ^^^^^^^^^^^^^ Self-assignment detected. $foo = $foo # comment ^^^^^^^^^^^ Self-assignment detected. Foo = Foo # comment ^^^^^^^^^ Self-assignment detected. foo, bar = foo, bar # comment ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo ||= foo # comment ^^^^^^^^^^^ Self-assignment detected. foo &&= foo # comment ^^^^^^^^^^^ Self-assignment detected. foo.bar = foo.bar # comment ^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.bar = foo&.bar # comment ^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo["bar"] = foo["bar"] # comment ^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. foo&.[]=("bar", foo["bar"]) # comment ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Self-assignment detected. 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/require_parentheses_spec.rb
spec/rubocop/cop/lint/require_parentheses_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RequireParentheses, :config do it 'registers an offense for missing parentheses around expression with && operator' do expect_offense(<<~RUBY) if day.is? 'monday' && month == :jan ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses in the method call to avoid confusion about precedence. foo end RUBY end it 'registers an offense for missing parentheses around expression with || operator' do expect_offense(<<~RUBY) day_is? 'tuesday' || true ^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses in the method call to avoid confusion about precedence. RUBY end it 'registers an offense for missing parentheses around expression in ternary' do expect_offense(<<~RUBY) wd.include? 'tuesday' && true == true ? a : b ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses in the method call to avoid confusion about precedence. RUBY end context 'when using safe navigation operator' do it 'registers an offense for missing parentheses around expression with && operator' do expect_offense(<<~RUBY) if day&.is? 'monday' && month == :jan ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses in the method call to avoid confusion about precedence. foo end RUBY end end it 'accepts missing parentheses around expression with + operator' do expect_no_offenses(<<~RUBY) if day_is? 'tuesday' + rest end RUBY end it 'accepts method calls without parentheses followed by keyword and/or' do expect_no_offenses(<<~RUBY) if day.is? 'tuesday' and month == :jan end if day.is? 'tuesday' or month == :jan end RUBY end it 'accepts method calls that are all operations' do expect_no_offenses(<<~RUBY) if current_level == max + 1 end RUBY end it 'accepts condition that is not a call' do expect_no_offenses(<<~RUBY) if @debug end RUBY end it 'accepts parentheses around expression with boolean operator' do expect_no_offenses(<<~RUBY) if day.is?('tuesday' && true == true) end RUBY end it 'accepts method call with parentheses in ternary' do expect_no_offenses("wd.include?('tuesday' && true == true) ? a : b") end it 'accepts missing parentheses when method is not a predicate' do expect_no_offenses("weekdays.foo 'tuesday' && true == true") end it 'accepts missing parentheses when using ternary operator' do expect_no_offenses('foo && bar ? baz : qux') end it 'accepts missing parentheses when using ternary operator in square brackets' do expect_no_offenses('do_something[foo && bar ? baz : qux]') end it 'accepts missing parentheses when assigning ternary operator' do expect_no_offenses('self.foo = bar && baz ? qux : quux') end it 'accepts calls to methods that are setters' do expect_no_offenses('s.version = @version || ">= 1.8.5"') end it 'accepts calls to methods that are operators' do expect_no_offenses('a[b || c]') 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_elsif_condition_spec.rb
spec/rubocop/cop/lint/duplicate_elsif_condition_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateElsifCondition, :config do it 'registers an offense for repeated elsif conditions' do expect_offense(<<~RUBY) if x == 1 elsif x == 2 elsif x == 1 ^^^^^^ Duplicate `elsif` condition detected. end RUBY end it 'registers an offense for subsequent repeated elsif conditions' do expect_offense(<<~RUBY) if x == 1 elsif x == 2 elsif x == 2 ^^^^^^ Duplicate `elsif` condition detected. end RUBY end it 'registers multiple offenses for multiple repeated elsif conditions' do expect_offense(<<~RUBY) if x == 1 elsif x == 2 elsif x == 1 ^^^^^^ Duplicate `elsif` condition detected. elsif x == 2 ^^^^^^ Duplicate `elsif` condition detected. end RUBY end it 'does not register an offense for non-repeated elsif conditions' do expect_no_offenses(<<~RUBY) if x == 1 elsif x == 2 else end RUBY end it 'does not register an offense for partially repeated elsif conditions' do expect_no_offenses(<<~RUBY) if x == 1 elsif x == 1 && x == 2 end RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/send_with_mixin_argument_spec.rb
spec/rubocop/cop/lint/send_with_mixin_argument_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SendWithMixinArgument, :config do it 'registers an offense when using `send` with `include`' do expect_offense(<<~RUBY) Foo.send(:include, Bar) ^^^^^^^^^^^^^^^^^^^ Use `include Bar` instead of `send(:include, Bar)`. RUBY expect_correction(<<~RUBY) Foo.include Bar RUBY end it 'registers an offense when using `send` with `prepend`' do expect_offense(<<~RUBY) Foo.send(:prepend, Bar) ^^^^^^^^^^^^^^^^^^^ Use `prepend Bar` instead of `send(:prepend, Bar)`. RUBY expect_correction(<<~RUBY) Foo.prepend Bar RUBY end it 'registers an offense when using `send` with `extend`' do expect_offense(<<~RUBY) Foo.send(:extend, Bar) ^^^^^^^^^^^^^^^^^^ Use `extend Bar` instead of `send(:extend, Bar)`. RUBY expect_correction(<<~RUBY) Foo.extend Bar RUBY end context 'when specifying a mixin method as a string' do it 'registers an offense when using `send` with `include`' do expect_offense(<<~RUBY) Foo.send('include', Bar) ^^^^^^^^^^^^^^^^^^^^ Use `include Bar` instead of `send('include', Bar)`. RUBY expect_correction(<<~RUBY) Foo.include Bar RUBY end it 'registers an offense when using `send` with `prepend`' do expect_offense(<<~RUBY) Foo.send('prepend', Bar) ^^^^^^^^^^^^^^^^^^^^ Use `prepend Bar` instead of `send('prepend', Bar)`. RUBY expect_correction(<<~RUBY) Foo.prepend Bar RUBY end it 'registers an offense when using `send` with `extend`' do expect_offense(<<~RUBY) Foo.send('extend', Bar) ^^^^^^^^^^^^^^^^^^^ Use `extend Bar` instead of `send('extend', Bar)`. RUBY expect_correction(<<~RUBY) Foo.extend Bar RUBY end end it 'registers an offense when using `public_send` method' do expect_offense(<<~RUBY) Foo.public_send(:include, Bar) ^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `include Bar` instead of `public_send(:include, Bar)`. RUBY expect_correction(<<~RUBY) Foo.include Bar RUBY end it 'registers an offense when using `__send__` method' do expect_offense(<<~RUBY) Foo.__send__(:include, Bar) ^^^^^^^^^^^^^^^^^^^^^^^ Use `include Bar` instead of `__send__(:include, Bar)`. RUBY expect_correction(<<~RUBY) Foo.include Bar RUBY end it 'does not register an offense when not using a mixin method' do expect_no_offenses(<<~RUBY) Foo.send(:do_something, Bar) RUBY end it 'does not register an offense when using `include`' do expect_no_offenses(<<~RUBY) Foo.include Bar RUBY end it 'does not register an offense when using `prepend`' do expect_no_offenses(<<~RUBY) Foo.prepend Bar RUBY end it 'does not register an offense when using `extend`' do expect_no_offenses(<<~RUBY) Foo.extend Bar RUBY end context 'when using namespace for module' do it 'registers an offense when using `send` with `include`' do expect_offense(<<~RUBY) A::Foo.send(:include, B::Bar) ^^^^^^^^^^^^^^^^^^^^^^ Use `include B::Bar` instead of `send(:include, B::Bar)`. RUBY expect_correction(<<~RUBY) A::Foo.include B::Bar RUBY end end context 'when multiple arguments are passed' do it 'registers an offense' do expect_offense(<<~RUBY) Foo.send(:include, Bar, Baz) ^^^^^^^^^^^^^^^^^^^^^^^^ Use `include Bar, Baz` instead of `send(:include, Bar, Baz)`. RUBY expect_correction(<<~RUBY) Foo.include Bar, Baz RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/unescaped_bracket_in_regexp_spec.rb
spec/rubocop/cop/lint/unescaped_bracket_in_regexp_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnescapedBracketInRegexp, :config do around { |example| RuboCop::Util.silence_warnings(&example) } context 'literal Regexp' do context 'when unescaped bracket is the first character' do it 'does not register an offense' do # this does not register a Ruby warning expect_no_offenses(<<~RUBY) /]/ RUBY end end context 'unescaped bracket in regexp' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) /abc]123/ ^ Regular expression has `]` without escape. RUBY expect_correction(<<~'RUBY') /abc\]123/ RUBY end end context 'unescaped bracket in regexp with regexp options' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) /abc]123/i ^ Regular expression has `]` without escape. RUBY expect_correction(<<~'RUBY') /abc\]123/i RUBY end end context 'multiple unescaped brackets in regexp' do it 'registers an offense for each bracket' do expect_offense(<<~RUBY) /abc]123]/ ^ Regular expression has `]` without escape. ^ Regular expression has `]` without escape. RUBY expect_correction(<<~'RUBY') /abc\]123\]/ RUBY end end context 'escaped bracket in regexp' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') /abc\]123/ RUBY end end context 'character class' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) /[abc]/ RUBY end end context 'character class in lookbehind' do # See https://github.com/ammar/regexp_parser/issues/93 it 'does not register an offense' do expect_no_offenses(<<~RUBY) /(?<=[<>=:])/ RUBY end end end context '%r{} Regexp' do context 'when unescaped bracket is the first character' do it 'does not register an offense' do # this does not register a Ruby warning expect_no_offenses(<<~RUBY) %r{]} RUBY end end context 'unescaped bracket in regexp' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) %r{abc]123} ^ Regular expression has `]` without escape. RUBY expect_correction(<<~'RUBY') %r{abc\]123} RUBY end end context 'unescaped bracket in regexp with regexp options' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) %r{abc]123}i ^ Regular expression has `]` without escape. RUBY expect_correction(<<~'RUBY') %r{abc\]123}i RUBY end end context 'multiple unescaped brackets in regexp' do it 'registers an offense for each bracket' do expect_offense(<<~RUBY) %r{abc]123]} ^ Regular expression has `]` without escape. ^ Regular expression has `]` without escape. RUBY expect_correction(<<~'RUBY') %r{abc\]123\]} RUBY end end context 'escaped bracket in regexp' do it 'does not register an offense' do expect_no_offenses(<<~'RUBY') %r{abc\]123} RUBY end end context 'character class' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) %r{[abc]} RUBY end end context 'character class in lookbehind' do # See https://github.com/ammar/regexp_parser/issues/93 it 'does not register an offense' do expect_no_offenses(<<~RUBY) %r{(?<=[<>=:])} RUBY end end end %i[new compile].each do |method| context "Regexp.#{method}" do context 'when unescaped bracket is the first character' do it 'does not register an offense' do # this does not register a Ruby warning expect_no_offenses(<<~RUBY) Regexp.#{method}(']') RUBY end end context 'unescaped bracket in regexp' do it 'registers an offense and corrects' do expect_offense(<<~RUBY, method: method) Regexp.#{method}('abc]123') _{method} ^ Regular expression has `]` without escape. RUBY expect_correction(<<~RUBY) Regexp.#{method}('abc\\]123') RUBY end end context 'unescaped bracket in regexp with regexp options' do it 'registers an offense and corrects' do expect_offense(<<~RUBY, method: method) Regexp.#{method}('abc]123', 'i') _{method} ^ Regular expression has `]` without escape. RUBY expect_correction(<<~RUBY) Regexp.#{method}('abc\\]123', 'i') RUBY end end context 'multiple unescaped brackets in regexp' do it 'registers an offense for each bracket' do expect_offense(<<~RUBY, method: method) Regexp.#{method}('abc]123]') _{method} ^ Regular expression has `]` without escape. _{method} ^ Regular expression has `]` without escape. RUBY expect_correction(<<~RUBY) Regexp.#{method}('abc\\]123\\]') RUBY end end context 'escaped bracket in regexp' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Regexp.#{method}('abc\\]123') RUBY end end context 'character class' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Regexp.#{method}('[abc]') RUBY end end context 'containing `dstr` node' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) Regexp.#{method}("(?:\#{arr[1]}:\\s*)") RUBY end end context 'invalid regular expressions' do %w[+ * {42} \xff].each do |invalid_regexp| it "does not register an offense for single invalid `/#{invalid_regexp}/` regexp`" do expect_no_offenses(<<~RUBY) Regexp.#{method}("#{invalid_regexp}") RUBY end it "registers an offense for regexp following invalid `/#{invalid_regexp}/` regexp" do expect_offense(<<~RUBY, method: method, invalid_regexp: invalid_regexp) [Regexp.#{method}('#{invalid_regexp}'), Regexp.#{method}('abc]123')] _{method} _{invalid_regexp} _{method} ^ Regular expression has `]` without escape. RUBY end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/syntax_spec.rb
spec/rubocop/cop/lint/syntax_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::Syntax, :config do describe '.offenses_from_processed_source' do let(:commissioner) { RuboCop::Cop::Commissioner.new([cop]) } let(:offenses) { commissioner.investigate(processed_source).offenses } let(:ruby_version) { 3.3 } # The minimum version Prism can parse is 3.3. let(:syntax_error_message) do parser_engine == :parser_whitequark ? 'unexpected token $end' : 'expected a matching `)`' end context 'with a diagnostic error' do let(:source) { '(' } it 'returns an offense' do expect(offenses.size).to eq(1) message = <<~MESSAGE.chomp #{syntax_error_message} (Using Ruby 3.3 parser; configure using `TargetRubyVersion` parameter, under `AllCops`) MESSAGE offense = offenses.first expect(offense.message).to eq(message) expect(offense.severity).to eq(:fatal) end context 'with --display-cop-names option' do let(:cop_options) { { display_cop_names: true } } it 'returns an offense with cop name' do expect(offenses.size).to eq(1) message = <<~MESSAGE.chomp Lint/Syntax: #{syntax_error_message} (Using Ruby 3.3 parser; configure using `TargetRubyVersion` parameter, under `AllCops`) MESSAGE offense = offenses.first expect(offense.message).to eq(message) expect(offense.severity).to eq(:fatal) end end context 'with --autocorrect --disable-uncorrectable options' do let(:cop_options) do { autocorrect: true, safe_autocorrect: true, disable_uncorrectable: true } end it 'returns an offense' do expect(offenses.size).to eq(1) message = <<~MESSAGE.chomp #{syntax_error_message} (Using Ruby 3.3 parser; configure using `TargetRubyVersion` parameter, under `AllCops`) MESSAGE offense = offenses.first expect(offense.message).to eq(message) expect(offense.severity).to eq(:fatal) end end context 'with `--lsp` option', :lsp do it 'does not include a configuration information in the offense message' do expect(offenses.first.message).to eq(syntax_error_message) end end end context 'with a diagnostic warning and error' do let(:source) { <<~RUBY } # warning: ambiguous `*` has been interpreted as an argument prefix foo *some_array ( RUBY it 'shows only syntax errors' do expect(processed_source.diagnostics.map(&:level)).to contain_exactly(:warning, :error) expect(offenses.size).to eq(1) message = <<~MESSAGE.chomp #{syntax_error_message} (Using Ruby 3.3 parser; configure using `TargetRubyVersion` parameter, under `AllCops`) MESSAGE offense = offenses.first expect(offense.message).to eq(message) expect(offense.severity).to eq(:fatal) end end context 'with a parser error' do let(:source) { <<~RUBY } # \xf9 RUBY it 'returns an offense' do expect(offenses.size).to eq(1) offense = offenses.first expect(offense.message).to eq('Invalid byte sequence in utf-8.') expect(offense.severity).to eq(:fatal) expect(offense.location).to eq(RuboCop::Cop::Offense::NO_LOCATION) end context 'with --display-cop-names option' do let(:cop_options) { { display_cop_names: true } } it 'returns an offense with cop name' do expect(offenses.size).to eq(1) message = <<~MESSAGE.chomp Lint/Syntax: Invalid byte sequence in utf-8. MESSAGE offense = offenses.first expect(offense.message).to eq(message) expect(offense.severity).to eq(:fatal) 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/duplicate_set_element_spec.rb
spec/rubocop/cop/lint/duplicate_set_element_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateSetElement, :config do %w[Set SortedSet].each do |class_name| it "registers an offense when using duplicate symbol element in `#{class_name}[...]`" do expect_offense(<<~RUBY, class_name: class_name) #{class_name}[:foo, :bar, :foo] _{class_name} ^^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) #{class_name}[:foo, :bar] RUBY end it "registers an offense when using duplicate symbol element in `::#{class_name}[...]`" do expect_offense(<<~RUBY, class_name: class_name) ::#{class_name}[:foo, :bar, :foo] _{class_name} ^^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) ::#{class_name}[:foo, :bar] RUBY end it 'registers an offense when using multiple duplicate symbol element' do expect_offense(<<~RUBY, class_name: class_name) #{class_name}[:foo, :bar, :foo, :baz, :baz] _{class_name} ^^^^ Remove the duplicate element in #{class_name}. _{class_name} ^^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) #{class_name}[:foo, :bar, :baz] RUBY end it 'registers an offense when using duplicate lvar element' do expect_offense(<<~RUBY, class_name: class_name) foo = do_foo bar = do_bar #{class_name}[foo, bar, foo] _{class_name} ^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) foo = do_foo bar = do_bar #{class_name}[foo, bar] RUBY end it 'registers an offense when using duplicate ivar element' do expect_offense(<<~RUBY, class_name: class_name) #{class_name}[@foo, @bar, @foo] _{class_name} ^^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) #{class_name}[@foo, @bar] RUBY end it 'registers an offense when using duplicate constant element' do expect_offense(<<~RUBY, class_name: class_name) #{class_name}[Foo, Bar, Foo] _{class_name} ^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) #{class_name}[Foo, Bar] RUBY end it 'does not register an offense when using duplicate method call element' do expect_no_offenses(<<~RUBY) #{class_name}[foo, bar, foo] RUBY end it 'does not register an offense when using duplicate safe navigation method call element' do expect_no_offenses(<<~RUBY) #{class_name}[obj&.foo, obj&.bar, obj&.foo] RUBY end it 'does not register an offense when using duplicate ternary operator element' do expect_no_offenses(<<~RUBY) #{class_name}[rand > 0.5 ? 1 : 2, rand > 0.5 ? 1 : 2] RUBY end it "registers an offense when using duplicate symbol element in `#{class_name}.new([...])`" do expect_offense(<<~RUBY, class_name: class_name) #{class_name}.new([:foo, :bar, :foo]) _{class_name} ^^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) #{class_name}.new([:foo, :bar]) RUBY end it "registers an offense when using duplicate symbol element in `#{class_name}.new(%i[...])`" do expect_offense(<<~RUBY, class_name: class_name) #{class_name}.new(%i[foo bar foo]) _{class_name} ^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) #{class_name}.new(%i[foo bar]) RUBY end it "registers an offense when using duplicate symbol element in `::#{class_name}.new([...])`" do expect_offense(<<~RUBY, class_name: class_name) ::#{class_name}.new([:foo, :bar, :foo]) _{class_name} ^^^^ Remove the duplicate element in #{class_name}. RUBY expect_correction(<<~RUBY) ::#{class_name}.new([:foo, :bar]) RUBY end it "does not register an offense when not using duplicate method call element in `#{class_name}[...]`" do expect_no_offenses(<<~RUBY) #{class_name}[foo, bar] RUBY end it "does not register an offense when not using duplicate symbol element in `#{class_name}.new([...])`" do expect_no_offenses(<<~RUBY) #{class_name}.new([:foo, :bar]) RUBY end it "does not register an offense when using empty element in `#{class_name}[]`" do expect_no_offenses(<<~RUBY) #{class_name}[] RUBY end it "does not register an offense when using one element in `#{class_name}[...]`" do expect_no_offenses(<<~RUBY) #{class_name}[:foo] RUBY end end it 'registers an offense when using duplicate symbol element in `[...].to_set`' do expect_offense(<<~RUBY) [:foo, :bar, :foo].to_set ^^^^ Remove the duplicate element in Set. RUBY expect_correction(<<~RUBY) [:foo, :bar].to_set RUBY end it 'registers an offense when using duplicate symbol element in `[...]&.to_set`' do expect_offense(<<~RUBY) [:foo, :bar, :foo]&.to_set ^^^^ Remove the duplicate element in Set. RUBY expect_correction(<<~RUBY) [:foo, :bar]&.to_set RUBY end it 'does not register an offense when using duplicate symbol element in `Array[...]`' do expect_no_offenses(<<~RUBY) Array[:foo, :bar, :foo] RUBY end it 'does not register an offense when using duplicate symbol element in `Array.new([...])`' do expect_no_offenses(<<~RUBY) Array.new([:foo, :bar, :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/unused_block_argument_spec.rb
spec/rubocop/cop/lint/unused_block_argument_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UnusedBlockArgument, :config do let(:cop_config) { { 'AllowUnusedKeywordArguments' => false } } context 'inspection' do context 'when a block takes multiple arguments' do context 'and an argument is unused' do it 'registers an offense' do message = "Unused block argument - `value`. If it's " \ 'necessary, use `_` or `_value` as an argument ' \ "name to indicate that it won't be used." expect_offense(<<~RUBY) hash.each do |key, value| ^^^^^ #{message} puts key end RUBY expect_correction(<<~RUBY) hash.each do |key, _value| puts key end RUBY end end context 'and all arguments are used' do it 'accepts' do expect_no_offenses(<<~RUBY) obj.method { |foo, bar| stuff(foo, bar) } RUBY end end context 'and arguments are swap-assigned' do it 'accepts' do expect_no_offenses(<<~RUBY) hash.each do |key, value| key, value = value, key 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 block argument - `key`. ' \ "If it's necessary, use `_` or `_key` as an argument " \ "name to indicate that it won't be used." expect_offense(<<~RUBY) hash.each do |key, value| ^^^ #{message} key, value = value, 42 end RUBY expect_correction(<<~RUBY) hash.each do |_key, value| key, value = value, 42 end RUBY end end context 'and a splat argument is unused' do it 'registers an offense and preserves splat' do message = 'Unused block argument - `bars`. ' \ "If it's necessary, use `_` or `_bars` as an argument " \ "name to indicate that it won't be used." expect_offense(<<~RUBY) obj.method { |foo, *bars, baz| stuff(foo, baz) } ^^^^ #{message} RUBY expect_correction(<<~RUBY) obj.method { |foo, *_bars, baz| stuff(foo, baz) } RUBY end end context 'and an argument with default value is unused' do it 'registers an offense and preserves default value' do message = 'Unused block argument - `bar`. ' \ "If it's necessary, use `_` or `_bar` as an argument " \ "name to indicate that it won't be used." expect_offense(<<~RUBY) obj.method do |foo, bar = baz| ^^^ #{message} stuff(foo) end RUBY expect_correction(<<~RUBY) obj.method do |foo, _bar = baz| stuff(foo) end RUBY end end context 'and all the arguments are unused' do it 'registers offenses and suggests omitting them' do (key_message, value_message) = %w[key value].map do |arg| "Unused block argument - `#{arg}`. You can omit all the " \ "arguments if you don't care about them." end expect_offense(<<~RUBY) hash = { foo: 'FOO', bar: 'BAR' } hash.each do |key, value| ^^^^^ #{value_message} ^^^ #{key_message} puts :something end RUBY expect_correction(<<~RUBY) hash = { foo: 'FOO', bar: 'BAR' } hash.each do |_key, _value| puts :something end RUBY end context 'and unused arguments span multiple lines' do it 'registers offenses and suggests omitting them' do key_message, value_message = %w[key value].map do |arg| "Unused block argument - `#{arg}`. You can omit all the " \ "arguments if you don't care about them." end expect_offense(<<~RUBY) hash.each do |key, ^^^ #{key_message} value| ^^^^^ #{value_message} puts :something end RUBY expect_correction(<<~RUBY) hash.each do |_key, _value| puts :something end RUBY end end end end context 'when a block takes single argument' do context 'and the argument is unused' do it 'registers an offense and suggests omitting that' do message = 'Unused block argument - `index`. ' \ "You can omit the argument if you don't care about it." expect_offense(<<~RUBY) 1.times do |index| ^^^^^ #{message} puts :something end RUBY expect_correction(<<~RUBY) 1.times do |_index| puts :something end RUBY end end context 'and the method call is `define_method`' do it 'registers an offense' do message = 'Unused block argument - `bar`. ' \ "If it's necessary, use `_` or `_bar` as an argument " \ "name to indicate that it won't be used." expect_offense(<<~RUBY) define_method(:foo) do |bar| ^^^ #{message} puts 'baz' end RUBY expect_correction(<<~RUBY) define_method(:foo) do |_bar| puts 'baz' end RUBY end end end context 'when a block have a block local variable' do context 'and the variable is unused' do it 'registers an offense' do expect_offense(<<~RUBY) 1.times do |index; block_local_variable| ^^^^^^^^^^^^^^^^^^^^ Unused block local variable - `block_local_variable`. puts index end RUBY expect_correction(<<~RUBY) 1.times do |index; _block_local_variable| puts index end RUBY end end context 'and the variable is used' do it 'does not register offense' do expect_no_offenses(<<~RUBY) 1.times do |index; x| x = 10 puts index end RUBY end end end context 'when a lambda block takes arguments' do context 'and all the arguments are unused' do it 'registers offenses and suggests using a proc' do (foo_message, bar_message) = %w[foo bar].map do |arg| "Unused block argument - `#{arg}`. " \ "If it's necessary, use `_` or `_#{arg}` as an argument name " \ "to indicate that it won't be used. " \ 'Also consider using a proc without arguments instead of a ' \ "lambda if you want it to accept any arguments but don't care " \ 'about them.' end expect_offense(<<~RUBY) -> (foo, bar) { do_something } ^^^ #{bar_message} ^^^ #{foo_message} RUBY expect_correction(<<~RUBY) -> (_foo, _bar) { do_something } RUBY end end context 'and an argument is unused' do it 'registers an offense' do message = 'Unused block argument - `foo`. ' \ "If it's necessary, use `_` or `_foo` as an argument " \ "name to indicate that it won't be used." expect_offense(<<~RUBY) -> (foo, bar) { puts bar } ^^^ #{message} RUBY expect_correction(<<~RUBY) -> (_foo, bar) { puts bar } RUBY end end end context 'when an underscore-prefixed block argument is not used' do it 'accepts' do expect_no_offenses(<<~RUBY) 1.times do |_index| puts 'foo' end RUBY end end context 'when an optional keyword argument is unused' do context 'when the method call is `define_method`' do it 'registers an offense' do message = 'Unused block argument - `bar`. ' \ "If it's necessary, use `_` or `_bar` as an argument name " \ "to indicate that it won't be used." expect_offense(<<~RUBY) define_method(:foo) do |bar: 'default'| ^^^ #{message} puts 'bar' end RUBY expect_no_corrections end context 'when AllowUnusedKeywordArguments set' do let(:cop_config) { { 'AllowUnusedKeywordArguments' => true } } it 'does not care' do expect_no_offenses(<<~RUBY) define_method(:foo) do |bar: 'default'| puts 'bar' end RUBY end end end context 'when the method call is not `define_method`' do it 'registers an offense' do message = 'Unused block argument - `bar`. ' \ "You can omit the argument if you don't care about it." expect_offense(<<~RUBY) foo(:foo) do |bar: 'default'| ^^^ #{message} puts 'bar' end RUBY expect_no_corrections end context 'when AllowUnusedKeywordArguments set' do let(:cop_config) { { 'AllowUnusedKeywordArguments' => true } } it 'does not care' do expect_no_offenses(<<~RUBY) foo(:foo) do |bar: 'default'| puts 'bar' end RUBY end end end end context 'when a method argument is not used' do it 'does not care' do expect_no_offenses(<<~RUBY) def some_method(foo) end RUBY end end context 'when a variable is not used' do it 'does not care' do expect_no_offenses(<<~RUBY) 1.times do foo = 1 end RUBY end end context 'in a method calling `binding` without arguments' do it 'accepts all arguments' do expect_no_offenses(<<~RUBY) test do |key, value| puts something(binding) end RUBY end context 'inside a method definition' do it 'registers offenses' do (key_message, value_message) = %w[key value].map do |arg| "Unused block argument - `#{arg}`. You can omit all the " \ "arguments if you don't care about them." end expect_offense(<<~RUBY) test do |key, value| ^^^^^ #{value_message} ^^^ #{key_message} def other(a) puts something(binding) end end RUBY expect_correction(<<~RUBY) test do |_key, _value| 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 (key_message, value_message) = %w[key value].map do |arg| "Unused block argument - `#{arg}`. You can omit all the " \ "arguments if you don't care about them." end expect_offense(<<~RUBY) test do |key, value| ^^^^^ #{value_message} ^^^ #{key_message} puts something(binding(:other)) end RUBY expect_correction(<<~RUBY) test do |_key, _value| puts something(binding(:other)) end RUBY end end end context 'with an empty block' do context 'when not configured to ignore empty blocks' do let(:cop_config) { { 'IgnoreEmptyBlocks' => false } } it 'registers an offense' do message = 'Unused block argument - `bar`. You can omit the ' \ "argument if you don't care about it." expect_offense(<<~RUBY) super { |bar| } ^^^ #{message} RUBY expect_correction(<<~RUBY) super { |_bar| } RUBY end end context 'when configured to ignore empty blocks' do let(:cop_config) { { 'IgnoreEmptyBlocks' => true } } it 'does not register an offense' do expect_no_offenses('super { |bar| }') end end end end context 'when IgnoreEmptyBlocks config parameter is set' do let(:cop_config) { { 'IgnoreEmptyBlocks' => true } } it 'accepts an empty block with a single unused parameter' do expect_no_offenses('->(arg) { }') end it 'registers an offense for a non-empty block with an unused parameter' do message = "Unused block argument - `arg`. If it's necessary, use `_` " \ "or `_arg` as an argument name to indicate that it won't " \ 'be used. Also consider using a proc without arguments ' \ 'instead of a lambda if you want it to accept any arguments ' \ "but don't care about them." expect_offense(<<~RUBY) ->(arg) { 1 } ^^^ #{message} RUBY expect_correction(<<~RUBY) ->(_arg) { 1 } RUBY end it 'accepts an empty block with multiple unused parameters' do expect_no_offenses('->(arg1, arg2, *others) { }') end it 'registers an offense for a non-empty block with multiple unused args' do (arg1_msg, arg2_msg, others_msg) = %w[arg1 arg2 others].map do |arg| "Unused block argument - `#{arg}`. If it's necessary, use `_` or " \ "`_#{arg}` as an argument name to indicate that it won't be used. " \ 'Also consider using a proc without arguments instead of a lambda ' \ "if you want it to accept any arguments but don't care about them." end expect_offense(<<~RUBY) ->(arg1, arg2, *others) { 1 } ^^^^^^ #{others_msg} ^^^^ #{arg2_msg} ^^^^ #{arg1_msg} RUBY expect_correction(<<~RUBY) ->(_arg1, _arg2, *_others) { 1 } RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/parentheses_as_grouped_expression_spec.rb
spec/rubocop/cop/lint/parentheses_as_grouped_expression_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ParenthesesAsGroupedExpression, :config do it 'registers an offense and corrects for method call with space before the parenthesis' do expect_offense(<<~RUBY) a.func (x) ^ `(x)` interpreted as grouped expression. RUBY expect_correction(<<~RUBY) a.func(x) RUBY end it 'registers an offense and corrects for predicate method call with space before the parenthesis' do expect_offense(<<~RUBY) is? (x) ^ `(x)` interpreted as grouped expression. RUBY expect_correction(<<~RUBY) is?(x) RUBY end it 'registers an offense and corrects for method call with space before the parenthesis when block argument and parenthesis' do expect_offense(<<~RUBY) a.concat ((1..1).map { |i| i * 10 }) ^ `((1..1).map { |i| i * 10 })` interpreted as grouped expression. RUBY expect_correction(<<~RUBY) a.concat((1..1).map { |i| i * 10 }) RUBY end it 'does not register an offense method call with space before the parenthesis when block argument is no parenthesis' do expect_no_offenses(<<~RUBY) a.concat (1..1).map { |i| i * 10 } RUBY end context 'when using numbered parameter', :ruby27 do it 'registers an offense and corrects for method call with space before the parenthesis when block argument and parenthesis' do expect_offense(<<~RUBY) a.concat ((1..1).map { _1 * 10 }) ^ `((1..1).map { _1 * 10 })` interpreted as grouped expression. RUBY expect_correction(<<~RUBY) a.concat((1..1).map { _1 * 10 }) RUBY end it 'does not register an offense for method call with space before the parenthesis when block argument is no parenthesis' do expect_no_offenses(<<~RUBY) a.concat (1..1).map { _1 * 10 } RUBY end end context 'when using `it` parameter', :ruby34 do it 'registers an offense and corrects for method call with space before the parenthesis when block argument and parenthesis' do expect_offense(<<~RUBY) a.concat ((1..1).map { it * 10 }) ^ `((1..1).map { it * 10 })` interpreted as grouped expression. RUBY expect_correction(<<~RUBY) a.concat((1..1).map { it * 10 }) RUBY end it 'does not register an offense for method call with space before the parenthesis when block argument is no parenthesis' do expect_no_offenses(<<~RUBY) a.concat (1..1).map { it * 10 } RUBY end end it 'does not register an offense for expression followed by an operator' do expect_no_offenses(<<~RUBY) func (x) || y RUBY end it 'does not register an offense for expression followed by chained expression' do expect_no_offenses(<<~RUBY) func (x).func.func.func.func.func RUBY end it 'does not register an offense for expression followed by chained expression with safe navigation operator' do expect_no_offenses(<<~RUBY) func (x).func.func.func.func&.func RUBY end it 'does not register an offense for math expression' do expect_no_offenses(<<~RUBY) puts (2 + 3) * 4 RUBY end it 'does not register an offense for math expression with `to_i`' do expect_no_offenses(<<~RUBY) do_something.eq (foo * bar).to_i RUBY end it 'does not register an offense when method argument parentheses are omitted and ' \ 'hash argument key is enclosed in parentheses' do expect_no_offenses(<<~RUBY) transition (foo - bar) => value RUBY end it 'does not register an offense for ternary operator' do expect_no_offenses(<<~RUBY) foo (cond) ? 1 : 2 RUBY end it 'accepts a method call without arguments' do expect_no_offenses('func') end it 'accepts a method call with arguments but no parentheses' do expect_no_offenses('puts x') end it 'accepts a chain of method calls' do expect_no_offenses(<<~RUBY) a.b a.b 1 a.b(1) RUBY end it 'accepts method with parens as arg to method without' do expect_no_offenses('a b(c)') end it 'accepts an operator call with argument in parentheses' do expect_no_offenses(<<~RUBY) a % (b + c) a.b = (c == d) RUBY end it 'accepts a space inside opening paren followed by left paren' do expect_no_offenses('a( (b) )') end it 'accepts parenthesis for compound range literals' do expect_no_offenses(<<-RUBY) rand (a - b)..(c - d) RUBY end it 'does not accepts parenthesis for simple range literals' do expect_offense(<<~RUBY) rand (1..10) ^ `(1..10)` interpreted as grouped expression. RUBY expect_correction(<<~RUBY) rand(1..10) RUBY end it 'does not register an offense for a call with multiple arguments' do expect_no_offenses('assert_equal (0..1.9), acceleration.domain') end it 'does not register an offense when heredoc has a space between the same string as the method name and `(`' do expect_no_offenses(<<~RUBY) foo( <<~EOS foo ( ) EOS ) RUBY end context 'when using safe navigation operator' do it 'registers an offense and corrects for method call with space before the parenthesis' do expect_offense(<<~RUBY) a&.func (x) ^ `(x)` interpreted as grouped expression. RUBY expect_correction(<<~RUBY) a&.func(x) RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/return_in_void_context_spec.rb
spec/rubocop/cop/lint/return_in_void_context_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ReturnInVoidContext, :config do context 'with an initialize method containing a return with a value' do it 'registers an offense' do expect_offense(<<~RUBY) class A def initialize return :qux if bar? ^^^^^^ Do not return a value in `initialize`. end end RUBY end it 'registers an offense when the value is returned in a block' do expect_offense(<<~RUBY) class A def initialize foo do return :qux ^^^^^^ Do not return a value in `initialize`. end end end RUBY end it 'registers an offense when the value is returned in a numblock' do expect_offense(<<~RUBY) class A def initialize foo do _1 return :qux ^^^^^^ Do not return a value in `initialize`. end end end RUBY end it 'registers an offense when the value is returned in an itblock', :ruby34 do expect_offense(<<~RUBY) class A def initialize foo do it return :qux ^^^^^^ Do not return a value in `initialize`. end end end RUBY end it 'registers no offense when return is used in `define_method`' do expect_no_offenses(<<~RUBY) class A def initialize define_method(:foo) do return bar end end end RUBY end it 'registers no offense when return is used in `define_method` with receiver' do expect_no_offenses(<<~RUBY) class A def initialize self.define_method(:foo) do return bar end end end RUBY end it 'registers no offense when return is used in `define_singleton_method`' do expect_no_offenses(<<~RUBY) class A def initialize define_singleton_method(:foo) do return bar end end end RUBY end it 'registers no offense when return is used in nested method definition' do expect_no_offenses(<<~RUBY) class A def initialize def foo return bar end end end RUBY end it 'registers no offense when return is used in nested singleton method definition' do expect_no_offenses(<<~RUBY) class A def initialize def self.foo return bar end end end RUBY end it 'registers an offense when the value is returned from inside a proc' do expect_offense(<<~RUBY) class A def initialize proc do return :qux ^^^^^^ Do not return a value in `initialize`. end end end RUBY end it 'registers no offense when the value is returned from inside a lamdba' do expect_no_offenses(<<~RUBY) class A def initialize lambda do return :qux end end end RUBY end end context 'with an initialize method containing a return without a value' do it 'accepts' do expect_no_offenses(<<~RUBY) class A def initialize return if bar? end end RUBY end it 'accepts when the return is in a block' do expect_no_offenses(<<~RUBY) class A def initialize foo do return if bar? end end end RUBY end end context 'with a setter method containing a return with a value' do it 'registers an offense' do expect_offense(<<~RUBY) class A def foo=(bar) return 42 ^^^^^^ Do not return a value in `foo=`. end end RUBY end end context 'with a setter method containing a return without a value' do it 'accepts' do expect_no_offenses(<<~RUBY) class A def foo=(bar) return end end RUBY end end context 'with a non initialize method containing a return' do it 'accepts' do expect_no_offenses(<<~RUBY) class A def bar foo return :qux if bar? foo end end RUBY end end context 'with a class method called initialize containing a return' do it 'accepts' do expect_no_offenses(<<~RUBY) class A def self.initialize foo return :qux if bar? foo end end RUBY end end context 'when return is in top scope' do it 'accepts' do expect_no_offenses(<<~RUBY) return if true 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/suppressed_exception_in_number_conversion_spec.rb
spec/rubocop/cop/lint/suppressed_exception_in_number_conversion_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SuppressedExceptionInNumberConversion, :config, :ruby26 do it 'registers an offense when using `Integer(arg) rescue nil`' do expect_offense(<<~RUBY) Integer(arg) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^ Use `Integer(arg, exception: false)` instead. RUBY expect_correction(<<~RUBY) Integer(arg, exception: false) RUBY end it 'registers an offense when using `Integer(arg, base) rescue nil`' do expect_offense(<<~RUBY) Integer(arg, base) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Integer(arg, base, exception: false)` instead. RUBY expect_correction(<<~RUBY) Integer(arg, base, exception: false) RUBY end it 'registers an offense when using `Float(arg) rescue nil`' do expect_offense(<<~RUBY) Float(arg) rescue nil ^^^^^^^^^^^^^^^^^^^^^ Use `Float(arg, exception: false)` instead. RUBY expect_correction(<<~RUBY) Float(arg, exception: false) RUBY end it 'registers an offense when using `BigDecimal(s) rescue nil`' do expect_offense(<<~RUBY) BigDecimal(s) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^ Use `BigDecimal(s, exception: false)` instead. RUBY expect_correction(<<~RUBY) BigDecimal(s, exception: false) RUBY end it 'registers an offense when using `BigDecimal(s, n) rescue nil`' do expect_offense(<<~RUBY) BigDecimal(s, n) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `BigDecimal(s, n, exception: false)` instead. RUBY expect_correction(<<~RUBY) BigDecimal(s, n, exception: false) RUBY end it 'registers an offense when using `Complex(s) rescue nil`' do expect_offense(<<~RUBY) Complex(s) rescue nil ^^^^^^^^^^^^^^^^^^^^^ Use `Complex(s, exception: false)` instead. RUBY expect_correction(<<~RUBY) Complex(s, exception: false) RUBY end it 'registers an offense when using `Complex(r, i) rescue nil`' do expect_offense(<<~RUBY) Complex(r, i) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Complex(r, i, exception: false)` instead. RUBY expect_correction(<<~RUBY) Complex(r, i, exception: false) RUBY end it 'registers an offense when using `Rational(x) rescue nil`' do expect_offense(<<~RUBY) Rational(x) rescue nil ^^^^^^^^^^^^^^^^^^^^^^ Use `Rational(x, exception: false)` instead. RUBY expect_correction(<<~RUBY) Rational(x, exception: false) RUBY end it 'registers an offense when using `Rational(x, y) rescue nil`' do expect_offense(<<~RUBY) Rational(x, y) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Rational(x, y, exception: false)` instead. RUBY expect_correction(<<~RUBY) Rational(x, y, exception: false) RUBY end it 'registers an offense when using `Integer(arg)` with `rescue nil` in `begin`' do expect_offense(<<~RUBY) begin ^^^^^ Use `Integer(arg, exception: false)` instead. Integer(arg) rescue nil end RUBY expect_correction(<<~RUBY) Integer(arg, exception: false) RUBY end it 'registers an offense when using `Integer(arg)` with `rescue ArgumentError` in `begin`' do expect_offense(<<~RUBY) begin ^^^^^ Use `Integer(arg, exception: false)` instead. Integer(arg) rescue ArgumentError nil end RUBY expect_correction(<<~RUBY) Integer(arg, exception: false) RUBY end it 'registers an offense when using `Integer(arg)` with `rescue ArgumentError, TypeError` in `begin`' do expect_offense(<<~RUBY) begin ^^^^^ Use `Integer(arg, exception: false)` instead. Integer(arg) rescue ArgumentError, TypeError nil end RUBY expect_correction(<<~RUBY) Integer(arg, exception: false) RUBY end it 'registers an offense when using `Integer(arg)` with `rescue ::ArgumentError, ::TypeError` in `begin`' do expect_offense(<<~RUBY) begin ^^^^^ Use `Integer(arg, exception: false)` instead. Integer(arg) rescue ::ArgumentError, ::TypeError nil end RUBY expect_correction(<<~RUBY) Integer(arg, exception: false) RUBY end it 'does not register an offense when using `Integer(arg)` with `rescue CustomError` in `begin`' do expect_no_offenses(<<~RUBY) begin Integer(arg) rescue CustomError nil end RUBY end it 'registers an offense when using `Integer(arg)` with `rescue` with implicit `nil` in `begin`' do expect_offense(<<~RUBY) begin ^^^^^ Use `Integer(arg, exception: false)` instead. Integer(arg) rescue end RUBY expect_correction(<<~RUBY) Integer(arg, exception: false) RUBY end it 'registers an offense when using `Kernel::Integer(arg) rescue nil`' do expect_offense(<<~RUBY) Kernel::Integer(arg) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Kernel::Integer(arg, exception: false)` instead. RUBY expect_correction(<<~RUBY) Kernel::Integer(arg, exception: false) RUBY end it 'registers an offense when using `::Kernel::Integer(arg) rescue nil`' do expect_offense(<<~RUBY) ::Kernel::Integer(arg) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `::Kernel::Integer(arg, exception: false)` instead. RUBY expect_correction(<<~RUBY) ::Kernel::Integer(arg, exception: false) RUBY end it 'registers an offense when using `::Kernel&.Integer(arg) rescue nil`' do expect_offense(<<~RUBY) ::Kernel&.Integer(arg) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `::Kernel&.Integer(arg, exception: false)` instead. RUBY expect_correction(<<~RUBY) ::Kernel&.Integer(arg, exception: false) RUBY end it 'registers an offense when using `::Kernel&.Float(arg) rescue nil`' do expect_offense(<<~RUBY) ::Kernel&.Float(arg) rescue nil ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `::Kernel&.Float(arg, exception: false)` instead. RUBY expect_correction(<<~RUBY) ::Kernel&.Float(arg, exception: false) RUBY end it 'does not register an offense when using `Integer(42, exception: false)`' do expect_no_offenses(<<~RUBY) Integer(42, exception: false) RUBY end it 'does not register an offense when using `Integer(arg) rescue 42`' do expect_no_offenses(<<~RUBY) Integer(arg) rescue 42 RUBY end it 'does not register an offense when using `Integer(arg)` with `rescue 42` in `begin`' do expect_no_offenses(<<~RUBY) begin Integer(arg) rescue 42 end RUBY end it 'does not register an offense when using `Integer(arg)` with `rescue nil else 42` in `begin`' do expect_no_offenses(<<~RUBY) begin Integer(arg) rescue nil else 42 end RUBY end it 'does not register an offense when using `Integer(arg)` and `do_something` with `rescue 42` in `begin`' do expect_no_offenses(<<~RUBY) begin Integer(arg) do_something rescue 42 end RUBY end it 'does not register an offense when using `Float(arg, unexpected_arg) rescue nil`' do expect_no_offenses(<<~RUBY) Float(arg, unexpected_arg) rescue nil RUBY end context '>= Ruby 2.5', :ruby25, unsupported_on: :prism do it 'does not register an offense when using `Integer(arg) rescue nil`' do expect_no_offenses(<<~RUBY) Integer(arg) rescue nil RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/constant_reassignment_spec.rb
spec/rubocop/cop/lint/constant_reassignment_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ConstantReassignment, :config do it 'registers an offense when reassigning a constant on top-level namespace' do expect_offense(<<~RUBY) FOO = :bar FOO = :baz ^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. RUBY end it 'registers an offense when reassigning a constant on top-level namespace referencing self' do expect_offense(<<~RUBY) self::FOO = :bar self::FOO = :baz ^^^^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. RUBY end it 'registers an offense when reassigning a constant in a class' do expect_offense(<<~RUBY) class A FOO = :bar FOO = :baz ^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. end RUBY end it 'registers an offense when reassigning a constant in a class referencing self' do expect_offense(<<~RUBY) class A self::FOO = :bar self::FOO = :baz ^^^^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. end RUBY end it 'registers an offense when reassigning a constant in a module' do expect_offense(<<~RUBY) module A FOO = :bar FOO = :baz ^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. end RUBY end it 'registers an offense when reassigning a constant in a module referencing self' do expect_offense(<<~RUBY) module A self::FOO = :bar self::FOO = :baz ^^^^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. end RUBY end it 'registers an offense when reassigning a constant by referencing a relative namespace' do expect_offense(<<~RUBY) class A FOO = :bar end A::FOO = :baz ^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. RUBY end it 'registers an offense when reassigning a constant by referencing an absolute namespace' do expect_offense(<<~RUBY) class A FOO = :bar end ::A::FOO = :baz ^^^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. RUBY end it 'registers an offense when reassigning a constant by referencing a nested relative namespace' do expect_offense(<<~RUBY) module A class B FOO = :bar end end A::B::FOO = :baz ^^^^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. RUBY end it 'registers an offense when reassigning a constant by referencing a nested absolute namespace' do expect_offense(<<~RUBY) module A class B FOO = :bar end end ::A::B::FOO = :baz ^^^^^^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. RUBY end it 'registers an offense when reassigning a top-level constant assigned under a different namespace' do expect_offense(<<~RUBY) class A ::FOO = :bar end FOO = :baz ^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. RUBY end it 'registers an offense when reassigning a class constant from a module' do expect_offense(<<~RUBY) module A class B FOO = :bar end B::FOO = :baz ^^^^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. end RUBY end it 'registers an offense when reassigning a constant in a reopened class' do expect_offense(<<~RUBY) module A class B FOO = :bar end class B FOO = :baz ^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. end end RUBY end it 'registers an offense when reassigning a constant within another constant' do expect_offense(<<~RUBY) class A ALL = [ FOO = :a, BAR = :b, BAZ = :c, FOO = :d, ^^^^^^^^ Constant `FOO` is already assigned in this namespace. ] end RUBY end it 'registers an offense when reassigning a constant within another constant with freeze' do expect_offense(<<~RUBY) class A ALL = [ FOO = :a, BAR = :b, BAZ = :c, FOO = :d, ^^^^^^^^ Constant `FOO` is already assigned in this namespace. ].freeze end RUBY end it 'registers an offense when reassigning a constant within a conditionally defined class' do expect_offense(<<~RUBY) class A FOO = :bar FOO = :baz ^^^^^^^^^^ Constant `FOO` is already assigned in this namespace. end unless defined?(A) RUBY end it 'does not register an offense when using OR assignment' do expect_no_offenses(<<~RUBY) FOO = :bar FOO ||= :baz RUBY end it 'does not register an offense when assigning a constant with the same name in a different class' do expect_no_offenses(<<~RUBY) class A FOO = :bar end class B FOO = :baz end RUBY end it 'does not register an offense when assigning a constant with the same name in a different module' do expect_no_offenses(<<~RUBY) module A FOO = :bar end module B FOO = :baz end RUBY end it 'does not register an offense when assigning a constant with the same name in a class with the same name in a different namespace' do expect_no_offenses(<<~RUBY) module A class C FOO = :bar end end module B class C FOO = :baz end end RUBY end it 'does not register an offense when assigning a constant with the same name on top-level and class namespace' do expect_no_offenses(<<~RUBY) FOO = :bar class A FOO = :baz end RUBY end it 'does not register an offense when assigning a constant with the same name on top-level and class namespace referencing self' do expect_no_offenses(<<~RUBY) FOO = :bar class A self::FOO = :baz end RUBY end it 'does not register an offense when assigning a constant with the same name on top-level and module namespace' do expect_no_offenses(<<~RUBY) FOO = :bar module A FOO = :baz end RUBY end it 'does not register an offense when assigning a constant in a namespace with the same name but on top-level' do expect_no_offenses(<<~RUBY) module A FOO = :bar ::FOO = :baz end RUBY end it 'does not register an offense when assigning a constant with the same name and namespace name but on top-level' do expect_no_offenses(<<~RUBY) module A module B FOO = :bar end ::B::FOO = :baz end RUBY end it 'does not register an offense when assigning a constant with the same name as top-level constant after remove_const with symbol argument' do expect_no_offenses(<<~RUBY) FOO = :bar class A FOO = :baz remove_const :FOO FOO = :quux end RUBY end it 'does not register an offense when assigning a constant with the same name as top-level constant after remove_const with string argument' do expect_no_offenses(<<~RUBY) FOO = :bar class A FOO = :baz remove_const 'FOO' FOO = :quux end RUBY end it 'does not raise an error when using remove_const with variable argument' do expect do expect_no_offenses(<<~RUBY) class A FOO = :bar constant = :FOO remove_const constant end RUBY end.not_to raise_error end it 'does not register an offense when assigning a constant with the same name as top-level constant after self.remove_const' do expect_no_offenses(<<~RUBY) FOO = :bar class A FOO = :baz self.remove_const :FOO FOO = :quux end RUBY end it 'does not register an offense when reassigning a constant inside a block' do expect_no_offenses(<<~RUBY) class A FOO = :bar silence_warnings do FOO = :baz end end RUBY end it 'does not register an offense when reassigning a constant inside a block with multiple statements' do expect_no_offenses(<<~RUBY) class A FOO = :bar silence_warnings do FOO = :baz BAR = :quux end end RUBY end it 'does not register an offense for simple constant assignment' do expect_no_offenses(<<~RUBY) FOO = :bar RUBY end it 'does not register an offense for constant assignment with a condition' do expect_no_offenses(<<~RUBY) FOO = :bar FOO = :baz unless something RUBY end it 'does not register an offense for constant assignment within an if...else block' do expect_no_offenses(<<~RUBY) if something FOO = :bar else FOO = :baz end RUBY end it 'does not register an offense for constant assignment within an if...else block with multiple statements' do expect_no_offenses(<<~RUBY) FOO = :bar if something FOO = :baz FOO = :quux else FOO = :baz end RUBY end it 'does not register an offense for constant assignment within an if...else block with multiple statements inside a class' do expect_no_offenses(<<~RUBY) class Foo FOO = :bar if something FOO = :baz FOO = :quux end end RUBY end it 'does not register an offense for constant assignment within an if statement inside a class' do expect_no_offenses(<<~RUBY) class Foo if something FOO = :bar end end RUBY end it 'does not register an offense when reassigning a constant in a Class.new block' do expect_no_offenses(<<~RUBY) FOO = :bar Class.new do FOO = :baz end RUBY end it 'does not register an offense when assigning a constant in a begin...rescue block' do expect_no_offenses(<<~RUBY) begin FOO = File.read(filename) rescue FOO = nil end RUBY end it 'does not register an offense when constant is reasigned with a variable path' do expect_no_offenses(<<~RUBY) lvar::FOO = 1 lvar::FOO = 2 RUBY end it 'does not register an offense when a nested constant is reassigned with a variable path' do expect_no_offenses(<<~RUBY) lvar::FOO::BAR = 1 lvar::FOO::BAR = 2 RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/useless_rescue_spec.rb
spec/rubocop/cop/lint/useless_rescue_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UselessRescue, :config do it 'registers an offense when single `rescue` which only anonymously reraises' do expect_offense(<<~RUBY) def foo do_something rescue ^^^^^^ Useless `rescue` detected. raise end RUBY end it 'registers an offense when single `rescue` which only reraises exception variable' do expect_offense(<<~RUBY) def foo do_something rescue => e ^^^^^^^^^^^ Useless `rescue` detected. raise e end RUBY expect_offense(<<~RUBY) def foo do_something rescue ^^^^^^ Useless `rescue` detected. raise $! end RUBY expect_offense(<<~RUBY) def foo do_something rescue ^^^^^^ Useless `rescue` detected. raise $ERROR_INFO end RUBY end it 'does not register an offense when `rescue` not only reraises' do expect_no_offenses(<<~RUBY) def foo do_something rescue do_cleanup raise e end RUBY end it 'does not register an offense when `rescue` only reraises but not exception variable' do expect_no_offenses(<<~RUBY) def foo do_something rescue => e raise x end RUBY end it 'does not register an offense when `rescue` does not exception variable and `ensure` has empty body' do expect_no_offenses(<<~RUBY) def foo rescue => e ensure end RUBY end it 'does not register an offense when using exception variable in `ensure` clause' do expect_no_offenses(<<~RUBY) def foo do_something rescue => e raise ensure do_something(e) end RUBY end it 'registers an offense when multiple `rescue`s and last is only reraises' do expect_offense(<<~RUBY) def foo do_something rescue ArgumentError # noop rescue ^^^^^^ Useless `rescue` detected. raise end RUBY end it 'does not register an offense when multiple `rescue`s and not last is only reraises' do expect_no_offenses(<<~RUBY) def foo do_something rescue ArgumentError raise rescue # noop end RUBY end it 'does not register an offense when using `Thread#raise` in `rescue` clause' do expect_no_offenses(<<~RUBY) def foo do_something rescue Thread.current.raise end RUBY end it 'does not register an offense when using modifier `rescue`' do expect_no_offenses(<<~RUBY) do_something rescue nil 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/array_literal_in_regexp_spec.rb
spec/rubocop/cop/lint/array_literal_in_regexp_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ArrayLiteralInRegexp, :config do shared_examples 'character class' do |source, correction| it "registers an offense and corrects for `#{source}`" do expect_offense(<<~'RUBY', source: source) /#{%{source}}/ ^^^{source}^ Use a character class instead of interpolating an array in a regexp. RUBY expect_correction("#{correction}\n") end end shared_examples 'alternation' do |source, correction| it "registers an offense and corrects for `#{source}`" do expect_offense(<<~'RUBY', source: source) /#{%{source}}/ ^^^{source}^ Use alternation instead of interpolating an array in a regexp. RUBY expect_correction("#{correction}\n") end end shared_examples 'offense' do |source| it "registers an offense but does not correct for `#{source}`" do expect_offense(<<~'RUBY', source: source) /#{%{source}}/ ^^^{source}^ Use alternation or a character class instead of interpolating an array in a regexp. RUBY expect_no_corrections end end it_behaves_like 'character class', '%w[a]', '/[a]/' it_behaves_like 'character class', '%w[a b c]', '/[abc]/' it_behaves_like 'character class', '["a", "b", "c"]', '/[abc]/' it_behaves_like 'character class', '%i[a b c]', '/[abc]/' it_behaves_like 'character class', '[:a, :b, :c]', '/[abc]/' it_behaves_like 'character class', '[1, 2, 3]', '/[123]/' it_behaves_like 'character class', '%w[^ - $ |]', '/[\^\-\$\|]/' it_behaves_like 'character class', '%w[あ い 🐧]', '/[γ‚γ„πŸ§]/' it_behaves_like 'alternation', '%w[foo]', '/(?:foo)/' it_behaves_like 'alternation', '%w[foo bar baz]', '/(?:foo|bar|baz)/' it_behaves_like 'alternation', '%w[a b cat]', '/(?:a|b|cat)/' it_behaves_like 'alternation', '[1.0, 2.5, 4.7]', '/(?:1\.0|2\.5|4\.7)/' it_behaves_like 'alternation', '["a", 5, 18.9]', '/(?:a|5|18\.9)/' it_behaves_like 'alternation', '%w[^^ -- $$ || ++ **]', '/(?:\^\^|\-\-|\$\$|\|\||\+\+|\*\*)/' it_behaves_like 'alternation', '%w[true false nil]', '/(?:true|false|nil)/' it_behaves_like 'alternation', '[true, false, nil]', '/(?:true|false|nil)/' it_behaves_like 'alternation', '%w[❀️ πŸ’š πŸ’™]', '/(?:❀️|πŸ’š|πŸ’™)/' it_behaves_like 'offense', '[foo]' it_behaves_like 'offense', '["#{foo}"]' it_behaves_like 'offense', '[:"#{foo}"]' it_behaves_like 'offense', '[`foo`]' it_behaves_like 'offense', '[1r]' it_behaves_like 'offense', '[1i]' it_behaves_like 'offense', '[1..2]' it_behaves_like 'offense', '[1...2]' it_behaves_like 'offense', '[/abc/]' it_behaves_like 'offense', '[[]]' it_behaves_like 'offense', '[{}]' it 'does not register an offense without interpolation' do expect_no_offenses(<<~RUBY) /[abc]/ RUBY end it 'does not register an offense when the interpolated value is not an array' do expect_no_offenses(<<~'RUBY') /#{foo}/ RUBY end it 'does not register an offense when an interpolated array is inside a string' do expect_no_offenses(<<~'RUBY') "#{%w[a b c]}" RUBY end it 'does not register an offense with empty interpolation' do expect_no_offenses(<<~'RUBY') /#{}/ RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/out_of_range_regexp_ref_spec.rb
spec/rubocop/cop/lint/out_of_range_regexp_ref_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::OutOfRangeRegexpRef, :config do it 'registers an offense when references are used before any regexp' do expect_offense(<<~RUBY) puts $3 ^^ $3 is out of range (no regexp capture groups detected). RUBY end it 'registers an offense when out of range references are used for named captures' do expect_offense(<<~RUBY) /(?<foo>FOO)(?<bar>BAR)/ =~ "FOOBAR" puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'registers an offense when out of range references are used for numbered captures' do expect_offense(<<~RUBY) /(foo)(bar)/ =~ "foobar" puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'registers an offense when out of range references are used for mix of numbered and named captures' do expect_offense(<<~RUBY) /(?<foo>FOO)(BAR)/ =~ "FOOBAR" puts $2 ^^ $2 is out of range (1 regexp capture group detected). RUBY end it 'registers an offense when out of range references are used for non captures' do expect_offense(<<~RUBY) /bar/ =~ 'foo' puts $1 ^^ $1 is out of range (no regexp capture groups detected). RUBY end it 'does not register offense to a regexp with valid references for named captures' do expect_no_offenses(<<~RUBY) /(?<foo>FOO)(?<bar>BAR)/ =~ "FOOBAR" puts $1 puts $2 RUBY end it 'does not register offense to a regexp with valid references for numbered captures' do expect_no_offenses(<<~RUBY) /(foo)(bar)/ =~ "foobar" puts $1 puts $2 RUBY end it 'does not register offense to a regexp with valid references for a mix named and numbered captures' do expect_no_offenses(<<~RUBY) /(?<foo>FOO)(BAR)/ =~ "FOOBAR" puts $1 RUBY end it 'does not register offense to a regexp with encoding option and valid references for numbered captures' do expect_no_offenses(<<~RUBY) /(foo)(bar)/u =~ "foobar" puts $1 puts $2 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. it 'does not register an offense regexp containing non literal' do expect_no_offenses(<<~'RUBY') var = '(\d+)' /(?<foo>#{var}*)/ =~ "12" puts $1 puts $2 RUBY end it 'registers an offense when the regexp appears on the right hand side of `=~`' do expect_offense(<<~RUBY) "foobar" =~ /(foo)(bar)/ puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'registers an offense when the regexp is matched with `===`' do expect_offense(<<~RUBY) /(foo)(bar)/ === "foobar" puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'registers an offense when the regexp is matched with `match`' do expect_offense(<<~RUBY) /(foo)(bar)/.match("foobar") puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'ignores calls to `match?`' do expect_offense(<<~RUBY) /(foo)(bar)/.match("foobar") /(foo)(bar)(baz)/.match?("foobarbaz") puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'ignores `match` with no arguments' do expect_no_offenses(<<~RUBY) foo.match RUBY end it 'ignores `match` with no receiver' do expect_no_offenses(<<~RUBY) match(bar) RUBY end it 'only registers an offense when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) foo_bar_regexp = /(foo)(bar)/ foo_regexp = /(foo)/ foo_bar_regexp =~ 'foobar' puts $2 RUBY end it 'does not register an offense when in range references are used inside a when clause' do expect_no_offenses(<<~RUBY) case "foobar" when /(foo)(bar)/ $2 end RUBY end it 'registers an offense when out of range references are used inside a when clause' do expect_offense(<<~RUBY) case "foobar" when /(foo)(bar)/ $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end it 'uses the maximum number of captures for when clauses with multiple conditions' do expect_no_offenses(<<~RUBY) case "foobarbaz" when /(foo)(bar)/, /(bar)baz/ $2 end RUBY expect_offense(<<~RUBY) case "foobarbaz" when /(foo)(bar)/, /(bar)baz/ $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end it 'only registers an offense for when clauses when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) case some_string when some_regexp $2 end RUBY end it 'ignores regexp when clause conditions that contain interpolations' do expect_offense(<<~'RUBY') case "foobarbaz" when /(foo)(bar)/, /#{var}/ $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end context 'pattern matching', :ruby27 do context 'matching variable' do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) case "foobar" in /(foo)(bar)/ $2 end RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) case "foobar" in /(foo)(bar)/ $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end context 'matching arrays' do it 'uses the maximum number of captures with multiple patterns' do expect_no_offenses(<<~RUBY) case array in [/(foo)(bar)/, /(bar)baz/] $2 end RUBY expect_offense(<<~RUBY) case array in [/(foo)(bar)/, /(bar)baz/] $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end context 'matching hashes' do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) case hash in a: /(foo)(bar)/ $2 end RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) case hash in a: /(foo)(bar)/, b: /(bar)baz/ $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end context 'matching pins' do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) a = 1 case array in [^a, /(foo)(bar)/] $2 end RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) a = 1 case array in [^a, /(foo)(bar)/, /(foo)bar/] $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end context 'matching with aliases' do context 'variable aliases' do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) case "foobar" in /(foo)(bar)/ => x $2 end RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) case "foobar" in /(foo)(bar)/ => x $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end context 'array aliases' do it 'uses the maximum number of captures with multiple patterns' do expect_no_offenses(<<~RUBY) case array in [/(foo)(bar)/, /(bar)baz/] => x $2 end RUBY expect_offense(<<~RUBY) case array in [/(foo)(bar)/, /(bar)baz/] => x $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end end context 'matching alternatives' do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) case "foobar" in /(foo)(bar)/ | "foo" $2 end RUBY expect_no_offenses(<<~RUBY) case "foobar" in /(foo)(bar)/ | "foo" => x $2 end RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) case "foobar" in /(foo)(bar)/ | "foo" $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end it 'uses the maximum number of captures with multiple patterns' do expect_no_offenses(<<~RUBY) case "foobar" in /(foo)baz/ | /(foo)(bar)/ $2 end RUBY expect_offense(<<~RUBY) case "foobar" in /(foo)baz/ | /(foo)(bar)/ $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end it 'only registers an offense when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) case some_string in some_regexp $2 end RUBY end it 'ignores regexp when clause conditions contain interpolations' do expect_offense(<<~'RUBY') case array in [/(foo)(bar)/, /#{var}/] $3 ^^ $3 is out of range (2 regexp capture groups detected). end RUBY end end context 'matching with `grep`' do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) %w[foo foobar].grep(/(foo)/) { $1 } RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) %w[foo foobar].grep(/(foo)/) { $2 } ^^ $2 is out of range (1 regexp capture group detected). RUBY end it 'only registers an offense when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) %w[foo foobar].grep(some_regexp) { $2 } RUBY end end context 'matching with `[]`' do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) "foobar"[/(foo)(bar)/] puts $2 RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) "foobar"[/(foo)(bar)/] puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'only registers an offense when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) "foobar"[some_regexp] puts $3 RUBY end end context 'when both the LHS and RHS use regexp' do it 'only considers the RHS regexp' do expect_no_offenses(<<~RUBY) if "foo bar".gsub(/\s+/, "") =~ /foo(bar)/ p $1 end RUBY expect_offense(<<~RUBY) if "foo bar".gsub(/(\s+)/, "") =~ /foobar/ p $1 ^^ $1 is out of range (no regexp capture groups detected). end RUBY end end context 'when calling a regexp method on a nth-ref node' do it 'does not register an offense when calling gsub on a valid nth-ref' do expect_no_offenses(<<~RUBY) if "some : line " =~ / : (.+)/ $1.gsub(/\s{2}/, " ") end RUBY end it 'registers an offense when calling gsub on an invalid nth-ref' do expect_offense(<<~RUBY) if "some : line " =~ / : (.+)/ $2.gsub(/\s{2}/, " ") ^^ $2 is out of range (1 regexp capture group detected). end RUBY end it 'registers an offense if the capturing groups have changed' do expect_offense(<<~RUBY) "some : line " =~ / : (.+)/ $1.gsub(/\s{2}/, " ") puts $1 ^^ $1 is out of range (no regexp capture groups detected). RUBY end end %i[gsub gsub! sub sub! scan].each do |method| context "matching with #{method}" do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) "foobar".#{method}(/(foo)(bar)/) { $2 } RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY, method: method) "foobar".%{method}(/(foo)(bar)/) { $3 } _{method} ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'only registers an offense when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) some_string.#{method}(some_regexp) { $3 } RUBY end end end %i[match slice slice! index rindex partition rpartition start_with? end_with?].each do |method| context "matching with #{method}" do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) "foobar".#{method}(/(foo)(bar)/) puts $2 RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) "foobar".#{method}(/(foo)(bar)/) puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'only registers an offense when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) "foobar".#{method}(some_regexp) puts $3 RUBY end end context "matching with #{method} using safe navigation" do it 'does not register an offense when in range references are used' do expect_no_offenses(<<~RUBY) "foobar"&.#{method}(/(foo)(bar)/) puts $2 RUBY end it 'registers an offense when out of range references are used' do expect_offense(<<~RUBY) "foobar"&.#{method}(/(foo)(bar)/) puts $3 ^^ $3 is out of range (2 regexp capture groups detected). RUBY end it 'only registers an offense when the regexp is matched as a literal' do expect_no_offenses(<<~RUBY) "foobar"&.#{method}(some_regexp) puts $3 RUBY end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/constant_resolution_spec.rb
spec/rubocop/cop/lint/constant_resolution_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::ConstantResolution, :config do it 'registers no offense when qualifying a const' do expect_no_offenses(<<~RUBY) ::MyConst RUBY end it 'registers no offense qualifying a namespace const' do expect_no_offenses(<<~RUBY) ::MyConst::MY_CONST RUBY end it 'registers an offense not qualifying a const' do expect_offense(<<~RUBY) MyConst ^^^^^^^ Fully qualify this constant to avoid possibly ambiguous resolution. RUBY end it 'registers an offense not qualifying a namespace const' do expect_offense(<<~RUBY) MyConst::MY_CONST ^^^^^^^ Fully qualify this constant to avoid possibly ambiguous resolution. RUBY end context 'module & class definitions' do it 'does not register offense' do expect_no_offenses(<<~RUBY) module Foo; end class Bar; end RUBY end end context 'with Only set' do let(:cop_config) { { 'Only' => ['MY_CONST'] } } it 'registers no offense when qualifying a const' do expect_no_offenses(<<~RUBY) ::MyConst RUBY end it 'registers no offense qualifying a namespace const' do expect_no_offenses(<<~RUBY) ::MyConst::MY_CONST RUBY end it 'registers no offense not qualifying another const' do expect_no_offenses(<<~RUBY) MyConst RUBY end it 'registers no with a namespace const' do expect_no_offenses(<<~RUBY) MyConst::MY_CONST RUBY end it 'registers an offense with an unqualified const' do expect_offense(<<~RUBY) MY_CONST ^^^^^^^^ Fully qualify this constant to avoid possibly ambiguous resolution. RUBY end it 'registers an offense when an unqualified namespace const' do expect_offense(<<~RUBY) MY_CONST::B ^^^^^^^^ Fully qualify this constant to avoid possibly ambiguous resolution. RUBY end end context 'with Ignore set' do let(:cop_config) { { 'Ignore' => ['MY_CONST'] } } it 'registers no offense when qualifying a const' do expect_no_offenses(<<~RUBY) ::MyConst RUBY end it 'registers no offense qualifying a namespace const' do expect_no_offenses(<<~RUBY) ::MyConst::MY_CONST RUBY end it 'registers an offense not qualifying another const' do expect_offense(<<~RUBY) MyConst ^^^^^^^ Fully qualify this constant to avoid possibly ambiguous resolution. RUBY end it 'registers an offense with a namespace const' do expect_offense(<<~RUBY) MyConst::MY_CONST ^^^^^^^ Fully qualify this constant to avoid possibly ambiguous resolution. RUBY end it 'registers no offense with an unqualified const' do expect_no_offenses(<<~RUBY) MY_CONST RUBY end it 'registers no offense when an unqualified namespace const' do expect_no_offenses(<<~RUBY) MY_CONST::B RUBY end it 'registers no offense when using `__ENCODING__`' do expect_no_offenses(<<~RUBY) __ENCODING__ 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_branch_spec.rb
spec/rubocop/cop/lint/duplicate_branch_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::DuplicateBranch, :config do shared_examples 'literal if allowed' do |type, value| context "when returning a #{type} in multiple branches" do it 'allows branches to be duplicated' do expect_no_offenses(<<~RUBY) if x #{value} elsif y #{value} else #{value} end RUBY end end end shared_examples 'literal if disallowed' do |type, value| context "when returning a #{type} in multiple branches" do it 'registers an offense' do expect_offense(<<~RUBY) if x #{value} elsif y ^^^^^^^ Duplicate branch body detected. #{value} else ^^^^ Duplicate branch body detected. #{value} end RUBY end end end shared_examples 'literal case allowed' do |type, value| context "when returning a #{type} in multiple branches" do it 'allows branches to be duplicated' do expect_no_offenses(<<~RUBY) case foo when x then #{value} when y then #{value} else #{value} end RUBY end end end shared_examples 'literal case disallowed' do |type, value| context "when returning a #{type} in multiple branches" do it 'registers an offense' do expect_offense(<<~RUBY, value: value) case foo when x then #{value} when y then #{value} ^^^^^^^^^^^^^{value} Duplicate branch body detected. else #{value} ^^^^ Duplicate branch body detected. end RUBY end end end shared_examples 'literal case-match allowed' do |type, value| context "when returning a #{type} in multiple branches", :ruby27 do it 'allows branches to be duplicated' do expect_no_offenses(<<~RUBY) case foo in x then #{value} in y then #{value} else #{value} end RUBY end end end shared_examples 'literal case-match disallowed' do |type, value| context "when returning a #{type} in multiple branches", :ruby27 do it 'registers an offense' do expect_offense(<<~RUBY, value: value) case foo in x then #{value} in y then #{value} ^^^^^^^^^^^{value} Duplicate branch body detected. else #{value} ^^^^ Duplicate branch body detected. end RUBY end end end shared_examples 'literal rescue allowed' do |type, value| context "when returning a #{type} in multiple branches" do it 'allows branches to be duplicated' do expect_no_offenses(<<~RUBY) begin foo rescue FooError #{value} rescue BarError #{value} else #{value} end RUBY end end end shared_examples 'literal rescue disallowed' do |type, value| context "when returning a #{type} in multiple branches" do it 'registers an offense' do expect_offense(<<~RUBY) begin foo rescue FooError #{value} rescue BarError ^^^^^^^^^^^^^^^ Duplicate branch body detected. #{value} else ^^^^ Duplicate branch body detected. #{value} end RUBY end end end it 'registers an offense when `if` has duplicate `else` branch' do expect_offense(<<~RUBY) if foo do_foo else ^^^^ Duplicate branch body detected. do_foo end if foo do_foo do_something_else else ^^^^ Duplicate branch body detected. do_foo do_something_else end RUBY end it 'registers an offense when `unless` has duplicate `else` branch' do expect_offense(<<~RUBY) unless foo do_bar else ^^^^ Duplicate branch body detected. do_bar end RUBY end it 'registers an offense when `if` has duplicate `elsif` branch' do expect_offense(<<~RUBY) if foo do_foo elsif bar ^^^^^^^^^ Duplicate branch body detected. do_foo end RUBY end it 'registers an offense when `if` has multiple duplicate branches' do expect_offense(<<~RUBY) if foo do_foo elsif bar do_bar elsif baz ^^^^^^^^^ Duplicate branch body detected. do_foo elsif quux ^^^^^^^^^^ Duplicate branch body detected. do_bar end RUBY end it 'does not register an offense when `if` has no duplicate branches' do expect_no_offenses(<<~RUBY) if foo do_foo elsif bar do_bar end RUBY end it 'does not register an offense when `unless` has no duplicate branches' do expect_no_offenses(<<~RUBY) unless foo do_bar else do_foo end RUBY end it 'does not register an offense for simple `if` without other branches' do expect_no_offenses(<<~RUBY) if foo do_foo end RUBY end it 'does not register an offense for simple `unless` without other branches' do expect_no_offenses(<<~RUBY) unless foo do_bar end RUBY end it 'does not register an offense for empty `if`' do expect_no_offenses(<<~RUBY) if foo # Comment. end RUBY end it 'does not register an offense for empty `unless`' do expect_no_offenses(<<~RUBY) unless foo # Comment. end RUBY end it 'does not register an offense for modifier `if`' do expect_no_offenses(<<~RUBY) do_foo if foo RUBY end it 'does not register an offense for modifier `unless`' do expect_no_offenses(<<~RUBY) do_bar unless foo RUBY end it 'registers an offense when ternary has duplicate branches' do expect_offense(<<~RUBY) res = foo ? do_foo : do_foo ^^^^^^ Duplicate branch body detected. RUBY end it 'does not register an offense when ternary has no duplicate branches' do expect_no_offenses(<<~RUBY) res = foo ? do_foo : do_bar RUBY end it 'registers an offense when `case` has duplicate `when` branch' do expect_offense(<<~RUBY) case x when foo do_foo when bar ^^^^^^^^ Duplicate branch body detected. do_foo end RUBY end it 'registers an offense when `case` has duplicate `else` branch' do expect_offense(<<~RUBY) case x when foo do_foo else ^^^^ Duplicate branch body detected. do_foo end RUBY end it 'registers an offense when `case` has multiple duplicate branches' do expect_offense(<<~RUBY) case x when foo do_foo when bar do_bar when baz ^^^^^^^^ Duplicate branch body detected. do_foo when quux ^^^^^^^^^ Duplicate branch body detected. do_bar end RUBY end it 'does not register an offense when `case` has no duplicate branches' do expect_no_offenses(<<~RUBY) case x when foo do_foo when bar do_bar end RUBY end it 'registers an offense when `rescue` has duplicate `resbody` branch' do expect_offense(<<~RUBY) begin do_something rescue FooError handle_error(x) rescue BarError ^^^^^^^^^^^^^^^ Duplicate branch body detected. handle_error(x) end RUBY end it 'registers an offense when `rescue` has duplicate `else` branch' do expect_offense(<<~RUBY) begin do_something rescue FooError handle_error(x) else ^^^^ Duplicate branch body detected. handle_error(x) end RUBY end it 'registers an offense when `rescue` has multiple duplicate `resbody` branches' do expect_offense(<<~RUBY) begin do_something rescue FooError handle_foo_error(x) rescue BarError handle_bar_error(x) rescue BazError ^^^^^^^^^^^^^^^ Duplicate branch body detected. handle_foo_error(x) rescue QuuxError ^^^^^^^^^^^^^^^^ Duplicate branch body detected. handle_bar_error(x) end RUBY end it 'does not register an offense when `rescue` has no duplicate branches' do expect_no_offenses(<<~RUBY) begin do_something rescue FooError handle_foo_error(x) rescue BarError handle_bar_error(x) end RUBY end context 'with IgnoreLiteralBranches: true' do let(:cop_config) { { 'IgnoreLiteralBranches' => true } } %w[if case rescue].each do |keyword| context "with `#{keyword}`" do it_behaves_like "literal #{keyword} allowed", 'integer', '5' it_behaves_like "literal #{keyword} allowed", 'float', '5.0' it_behaves_like "literal #{keyword} allowed", 'rational', '5r' it_behaves_like "literal #{keyword} allowed", 'complex', '5i' it_behaves_like "literal #{keyword} allowed", 'string', '"string"' it_behaves_like "literal #{keyword} allowed", 'symbol', ':symbol' it_behaves_like "literal #{keyword} allowed", 'true', 'true' it_behaves_like "literal #{keyword} allowed", 'false', 'false' it_behaves_like "literal #{keyword} allowed", 'nil', 'nil' it_behaves_like "literal #{keyword} allowed", 'regexp', '/foo/' it_behaves_like "literal #{keyword} allowed", 'regexp with modifier', '/foo/i' it_behaves_like "literal #{keyword} allowed", 'simple irange', '1..5' it_behaves_like "literal #{keyword} allowed", 'simple erange', '1...5' it_behaves_like "literal #{keyword} allowed", 'empty array', '[]' it_behaves_like "literal #{keyword} allowed", 'array of literals', '[1, 2, 3]' it_behaves_like "literal #{keyword} allowed", 'empty hash', '{}' it_behaves_like "literal #{keyword} allowed", 'hash of literals', '{ foo: 1, bar: 2 }' it_behaves_like "literal #{keyword} disallowed", 'dstr', '"#{foo}"' it_behaves_like "literal #{keyword} disallowed", 'dsym', ':"#{foo}"' it_behaves_like "literal #{keyword} disallowed", 'xstr', '`foo bar`' it_behaves_like "literal #{keyword} disallowed", 'complex array', '[foo, bar, baz]' it_behaves_like "literal #{keyword} disallowed", 'complex hash', '{ foo: foo, bar: bar }' it_behaves_like "literal #{keyword} disallowed", 'complex irange', '1..foo' it_behaves_like "literal #{keyword} disallowed", 'complex erange', '1...foo' it_behaves_like "literal #{keyword} disallowed", 'complex regexp', '/#{foo}/i' it_behaves_like "literal #{keyword} disallowed", 'variable', 'foo' it_behaves_like "literal #{keyword} disallowed", 'method call', 'foo(bar)' context 'and IgnoreConstBranches: true' do let(:cop_config) { super().merge('IgnoreConstantBranches' => true) } it_behaves_like "literal #{keyword} allowed", 'array of constants', '[CONST1, CONST2]' it_behaves_like "literal #{keyword} allowed", 'hash of constants', '{ foo: CONST1, bar: CONST2 }' end context 'and IgnoreConstBranches: false' do let(:cop_config) { super().merge('IgnoreConstantBranches' => false) } it_behaves_like "literal #{keyword} disallowed", 'array of constants', '[CONST1, CONST2]' it_behaves_like "literal #{keyword} disallowed", 'hash of constants', '{ foo: CONST1, bar: CONST2 }' end end end end context 'with IgnoreConstantBranches: true' do let(:cop_config) { { 'IgnoreConstantBranches' => true } } %w[if case case-match rescue].each do |keyword| context "with `#{keyword}`" do it_behaves_like "literal #{keyword} allowed", 'constant', 'MY_CONST' it_behaves_like "literal #{keyword} disallowed", 'object', 'Object.new' end end end context 'with IgnoreDuplicateElseBranch: true' do let(:cop_config) { { 'IgnoreDuplicateElseBranch' => true } } it 'allows duplicate `else` branch for `if-elsif`' do expect_no_offenses(<<~RUBY) if x foo elsif y bar else bar end RUBY end it 'registers an offense for duplicate `if-else`' do expect_offense(<<~RUBY) if x foo else ^^^^ Duplicate branch body detected. foo end RUBY end it 'allows duplicate `else` branch for `case` with multiple `when` branches' do expect_no_offenses(<<~RUBY) case x when foo do_foo when bar do_bar else do_bar end RUBY end it 'registers an offense for duplicate `else` branch for `case` with single `when` branch' do expect_offense(<<~RUBY) case x when foo do_foo else ^^^^ Duplicate branch body detected. do_foo end RUBY end it 'allows duplicate `else` branch for `case` with multiple `match` branches' do expect_no_offenses(<<~RUBY) case x in foo then do_foo in bar then do_bar else do_bar end RUBY end it 'registers an offense for duplicate `else` branch for `case` with single `match` branch' do expect_offense(<<~RUBY) case x in foo then do_foo else do_foo ^^^^ Duplicate branch body detected. end RUBY end it 'allows duplicate `else` branch for `rescue` with multiple `resbody` branches' do expect_no_offenses(<<~RUBY) begin x rescue FooError foo rescue BarError bar else bar end RUBY end it 'registers an offense for duplicate `else` branch for `rescue` with single `resbody` branch' do expect_offense(<<~RUBY) begin x rescue FooError foo else ^^^^ Duplicate branch body detected. 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/symbol_conversion_spec.rb
spec/rubocop/cop/lint/symbol_conversion_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::SymbolConversion, :config do shared_examples 'offense' do |from, to| it "registers an offense for #{from}" do expect_offense(<<~RUBY, from: from) #{from} ^{from} Unnecessary symbol conversion; use `#{to}` instead. RUBY expect_correction(<<~RUBY, loop: false) #{to} RUBY end end # Unnecessary `to_sym` it_behaves_like 'offense', ':foo.to_sym', ':foo' it_behaves_like 'offense', '"foo".to_sym', ':foo' it_behaves_like 'offense', '"foo_bar".to_sym', ':foo_bar' it_behaves_like 'offense', '"foo-bar".to_sym', ':"foo-bar"' it_behaves_like 'offense', '"foo-#{bar}".to_sym', ':"foo-#{bar}"' # Unnecessary `intern` it_behaves_like 'offense', ':foo.intern', ':foo' it_behaves_like 'offense', '"foo".intern', ':foo' it_behaves_like 'offense', '"foo_bar".intern', ':foo_bar' it_behaves_like 'offense', '"foo-bar".intern', ':"foo-bar"' it_behaves_like 'offense', '"foo-#{bar}".intern', ':"foo-#{bar}"' # Unnecessary quoted symbol it_behaves_like 'offense', ':"foo"', ':foo' it_behaves_like 'offense', ':"foo_bar"', ':foo_bar' it 'does not register an offense for a normal symbol' do expect_no_offenses(<<~RUBY) :foo RUBY end it 'does not register an offense for a symbol that requires double quotes' do expect_no_offenses(<<~RUBY) :"foo-bar" RUBY end it 'does not register an offense for a symbol that requires single quotes' do expect_no_offenses(<<~RUBY) :'foo-bar' RUBY end it 'does not register an offense for a symbol that requires single quotes, when it includes double quotes' do expect_no_offenses(<<~RUBY) :'foo-bar""' RUBY end context 'in a hash' do context 'keys' do it 'does not register an offense for a normal symbol' do expect_no_offenses(<<~RUBY) { foo: 'bar' } RUBY end it 'does not register an offense for a require quoted symbol' do expect_no_offenses(<<~RUBY) { 'foo-bar': 'bar' } RUBY end it 'does not register an offense for a require quoted symbol that contains `:`' do expect_no_offenses(<<~RUBY) { 'foo:bar': 'bar' } RUBY end it 'does not register an offense for a require quoted symbol that ends with `=`' do expect_no_offenses(<<~RUBY) { 'foo=': 'bar' } RUBY end it 'registers an offense for a quoted symbol' do expect_offense(<<~RUBY) { 'foo': 'bar' } ^^^^^ Unnecessary symbol conversion; use `foo:` instead. RUBY expect_correction(<<~RUBY) { foo: 'bar' } RUBY end it 'registers and corrects an offense for a quoted symbol that ends with `!`' do expect_offense(<<~RUBY) { 'foo!': 'bar' } ^^^^^^ Unnecessary symbol conversion; use `foo!:` instead. RUBY expect_correction(<<~RUBY) { foo!: 'bar' } RUBY end it 'registers and corrects an offense for a quoted symbol that ends with `?`' do expect_offense(<<~RUBY) { 'foo?': 'bar' } ^^^^^^ Unnecessary symbol conversion; use `foo?:` instead. RUBY expect_correction(<<~RUBY) { foo?: 'bar' } RUBY end it 'does not register an offense for operators' do expect_no_offenses(<<~RUBY) { '==': 'bar' } RUBY end it 'does not register an offense for dstr' do expect_no_offenses(<<~'RUBY') { "foo-#{'bar'}": 'baz' } RUBY end end context 'values' do it 'does not register an offense for a normal symbol' do expect_no_offenses(<<~RUBY) { foo: :bar } RUBY end it 'registers an offense for a quoted symbol key' do expect_offense(<<~RUBY) { :'foo' => :bar } ^^^^^^ Unnecessary symbol conversion; use `:foo` instead. RUBY expect_correction(<<~RUBY) { :foo => :bar } RUBY end it 'registers an offense for a quoted symbol value' do expect_offense(<<~RUBY) { foo: :'bar' } ^^^^^^ Unnecessary symbol conversion; use `:bar` instead. RUBY expect_correction(<<~RUBY) { foo: :bar } RUBY end it 'registers an offense for dstr' do expect_offense(<<~'RUBY') { foo: "bar-#{'baz'}".to_sym } ^^^^^^^^^^^^^^^^^^^^^ Unnecessary symbol conversion; use `:"bar-#{'baz'}"` instead. RUBY expect_correction(<<~'RUBY') { foo: :"bar-#{'baz'}" } RUBY end end end context 'in an alias' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) alias foo bar alias == equal alias eq? == RUBY end end context 'inside a percent literal array' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) %i(foo bar foo-bar) %I(foo bar foo-bar) RUBY end end context 'single quoted symbol' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) :'Foo/Bar/Baz' RUBY end end context 'implicit `to_sym` call' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) to_sym == other RUBY end end context 'EnforcedStyle: consistent' do let(:cop_config) { { 'EnforcedStyle' => 'consistent' } } context 'hash where no keys need to be quoted' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) { a: 1, b: 2 } RUBY end end context 'hash where keys are quoted but do not need to be' do it 'registers an offense' do expect_offense(<<~RUBY) { a: 1, 'b': 2 ^^^ Unnecessary symbol conversion; use `b:` instead. } RUBY expect_correction(<<~RUBY) { a: 1, b: 2 } RUBY end end context 'hash where there are keys needing quoting' do it 'registers an offense for unquoted keys' do expect_offense(<<~RUBY) { a: 1, ^ Symbol hash key should be quoted for consistency; use `"a":` instead. b: 2, ^ Symbol hash key should be quoted for consistency; use `"b":` instead. 'c': 3, 'd-e': 4 } RUBY expect_correction(<<~RUBY) { "a": 1, "b": 2, 'c': 3, 'd-e': 4 } RUBY end end context 'with a key with =' do it 'requires symbols to be quoted' do expect_offense(<<~RUBY) { 'a=': 1, b: 2 ^ Symbol hash key should be quoted for consistency; use `"b":` instead. } RUBY expect_correction(<<~RUBY) { 'a=': 1, "b": 2 } RUBY end end context 'with different quote styles' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) { 'a': 1, "b": 2, "c-d": 3, 'e-f': 4 } RUBY end end context 'with a mix of string and symbol keys' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) { 'a' => 1, 'b-c': 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/lint/debugger_spec.rb
spec/rubocop/cop/lint/debugger_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::Debugger, :config do context 'with the DebuggerMethods configuration' do let(:cop_config) { { 'DebuggerMethods' => %w[custom_debugger] } } it 'does not register an offense for a byebug call' do expect_no_offenses(<<~RUBY) byebug RUBY end it 'does not register an offense for a `custom_debugger` call when used in assignment' do expect_no_offenses(<<~RUBY) x.y = custom_debugger RUBY end it 'registers an offense for a `custom_debugger` call' do expect_offense(<<~RUBY) custom_debugger ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. RUBY end it 'registers an offense for a `custom_debugger` call when used in block' do expect_offense(<<~RUBY) x.y = do_something { custom_debugger } ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. RUBY end it 'registers an offense for a `custom_debugger` call when used in numbered block' do expect_offense(<<~RUBY) x.y = do_something do z(_1) custom_debugger ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. end RUBY end it 'registers an offense for a `custom_debugger` call when used in `it` block', :ruby34 do expect_offense(<<~RUBY) x.y = do_something do z(it) custom_debugger ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. end RUBY end it 'registers an offense for a `custom_debugger` call when used in lambda literal' do expect_offense(<<~RUBY) x.y = -> { custom_debugger } ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. RUBY end it 'registers an offense for a `custom_debugger` call when used in `lambda`' do expect_offense(<<~RUBY) x.y = lambda { custom_debugger } ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. RUBY end it 'registers an offense for a `custom_debugger` call when used in `proc`' do expect_offense(<<~RUBY) x.y = proc { custom_debugger } ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. RUBY end it 'registers an offense for a `custom_debugger` call when used in `Proc.new`' do expect_offense(<<~RUBY) x.y = Proc.new { custom_debugger } ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. RUBY end it 'registers an offense for a `custom_debugger` call when used within method arguments a `begin`...`end` block' do expect_offense(<<~RUBY) do_something( begin custom_debugger ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. end ) RUBY end context 'nested custom configurations' do let(:cop_config) { { 'DebuggerMethods' => { 'Custom' => %w[custom_debugger] } } } it 'registers an offense for a `custom_debugger call' do expect_offense(<<~RUBY) custom_debugger ^^^^^^^^^^^^^^^ Remove debugger entry point `custom_debugger`. RUBY end end context 'with a method chain' do let(:cop_config) { { 'DebuggerMethods' => %w[debugger.foo.bar] } } it 'registers an offense for a `debugger.foo.bar` call' do expect_offense(<<~RUBY) debugger.foo.bar ^^^^^^^^^^^^^^^^ Remove debugger entry point `debugger.foo.bar`. RUBY end end context 'with a const chain' do let(:cop_config) { { 'DebuggerMethods' => %w[Foo::Bar::Baz.debug] } } it 'registers an offense for a `Foo::Bar::Baz.debug` call' do expect_offense(<<~RUBY) Foo::Bar::Baz.debug ^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `Foo::Bar::Baz.debug`. RUBY end end context 'with a const chain and a method chain' do let(:cop_config) { { 'DebuggerMethods' => %w[Foo::Bar::Baz.debug.this.code] } } it 'registers an offense for a `Foo::Bar::Baz.debug.this.code` call' do expect_offense(<<~RUBY) Foo::Bar::Baz.debug.this.code ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `Foo::Bar::Baz.debug.this.code`. RUBY end end end context 'with the DebuggerRequires configuration' do let(:cop_config) do { 'DebuggerRequires' => { 'my_debugger' => %w[my_debugger], 'other_debugger' => %w[other_debugger/start] } } end it 'registers an offense' do expect_offense(<<~RUBY) require 'my_debugger' ^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `require 'my_debugger'`. RUBY end it 'registers no offense for a require without arguments' do expect_no_offenses('require') end it 'registers no offense for a require with multiple arguments' do expect_no_offenses('require "my_debugger", "something_else"') end it 'registers no offense for a require with non-string arguments' do expect_no_offenses('require my_debugger') end context 'when a require group is disabled with nil' do before { cop_config['DebuggerRequires']['my_debugger'] = nil } it 'does not register an offense for a require call' do expect_no_offenses('require "my_debugger"') end it 'does register an offense for another group' do expect_offense(<<~RUBY) require 'other_debugger/start' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `require 'other_debugger/start'`. RUBY end end context 'when the config is specified as an array' do let(:cop_config) { { 'DebuggerRequires' => %w[start_debugging] } } it 'registers an offense' do expect_offense(<<~RUBY) require 'start_debugging' ^^^^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `require 'start_debugging'`. RUBY end end end context 'built-in methods' do it 'registers an offense for a `binding.irb` call' do expect_offense(<<~RUBY) binding.irb ^^^^^^^^^^^ Remove debugger entry point `binding.irb`. RUBY end it 'registers an offense for a `Kernel.binding.irb` call' do expect_offense(<<~RUBY) Kernel.binding.irb ^^^^^^^^^^^^^^^^^^ Remove debugger entry point `Kernel.binding.irb`. RUBY end end context 'when print debug method is configured by user' do let(:cop_config) { { 'DebuggerMethods' => %w[p] } } it 'registers an offense for a p call' do expect_offense(<<~RUBY) p 'foo' ^^^^^^^ Remove debugger entry point `p 'foo'`. RUBY end it 'registers an offense for a p call with foo method argument' do expect_offense(<<~RUBY) foo(p 'foo') ^^^^^^^ Remove debugger entry point `p 'foo'`. RUBY end it 'registers an offense for a p call with p method argument' do expect_offense(<<~RUBY) p(p 'foo') ^^^^^^^ Remove debugger entry point `p 'foo'`. ^^^^^^^^^^ Remove debugger entry point `p(p 'foo')`. RUBY end it 'does not register an offense for a p.do_something call' do expect_no_offenses(<<~RUBY) p.do_something RUBY end it 'does not register an offense for a p with Foo call' do expect_no_offenses(<<~RUBY) Foo.p RUBY end it 'does not register an offense when `p` is an argument of method call' do expect_no_offenses(<<~RUBY) let(:p) { foo } it { expect(do_something(p)).to eq bar } RUBY end it 'does not register an offense when `p` is an argument of safe navigation method call' do expect_no_offenses(<<~RUBY) let(:p) { foo } it { expect(obj&.do_something(p)).to eq bar } RUBY end it 'does not register an offense when `p` is a keyword argument of method call' do expect_no_offenses(<<~RUBY) let(:p) { foo } it { expect(do_something(k: p)).to eq bar } RUBY end it 'does not register an offense when `p` is an array argument of method call' do expect_no_offenses(<<~RUBY) let(:p) { foo } it { expect(do_something([k, p])).to eq bar } RUBY end end context 'byebug' do it 'registers an offense for a byebug call' do expect_offense(<<~RUBY) byebug ^^^^^^ Remove debugger entry point `byebug`. RUBY end it 'registers an offense for a byebug with an argument call' do expect_offense(<<~RUBY) byebug foo ^^^^^^^^^^ Remove debugger entry point `byebug foo`. RUBY end it 'registers an offense for a Kernel.byebug call' do expect_offense(<<~RUBY) Kernel.byebug ^^^^^^^^^^^^^ Remove debugger entry point `Kernel.byebug`. RUBY end it 'registers an offense for a remote_byebug call' do expect_offense(<<~RUBY) remote_byebug ^^^^^^^^^^^^^ Remove debugger entry point `remote_byebug`. RUBY end it 'registers an offense for a Kernel.remote_byebug call' do expect_offense(<<~RUBY) Kernel.remote_byebug ^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `Kernel.remote_byebug`. RUBY end end context 'capybara' do it 'registers an offense for save_and_open_page' do expect_offense(<<~RUBY) save_and_open_page ^^^^^^^^^^^^^^^^^^ Remove debugger entry point `save_and_open_page`. RUBY end it 'registers an offense for save_and_open_screenshot' do expect_offense(<<~RUBY) save_and_open_screenshot ^^^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `save_and_open_screenshot`. RUBY end it 'registers an offense for save_page' do expect_offense(<<~RUBY) save_page ^^^^^^^^^ Remove debugger entry point `save_page`. RUBY end it 'registers an offense for save_screenshot' do expect_offense(<<~RUBY) save_screenshot ^^^^^^^^^^^^^^^ Remove debugger entry point `save_screenshot`. RUBY end context 'with an argument' do it 'registers an offense for save_and_open_page' do expect_offense(<<~RUBY) save_and_open_page foo ^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `save_and_open_page foo`. RUBY end it 'registers an offense for save_and_open_screenshot' do expect_offense(<<~RUBY) save_and_open_screenshot foo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `save_and_open_screenshot foo`. RUBY end it 'registers an offense for save_page' do expect_offense(<<~RUBY) save_page foo ^^^^^^^^^^^^^ Remove debugger entry point `save_page foo`. RUBY end it 'registers an offense for save_screenshot' do expect_offense(<<~RUBY) save_screenshot foo ^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `save_screenshot foo`. RUBY end end context 'with a page receiver' do it 'registers an offense for save_and_open_page' do expect_offense(<<~RUBY) page.save_and_open_page ^^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `page.save_and_open_page`. RUBY end it 'registers an offense for save_and_open_screenshot' do expect_offense(<<~RUBY) page.save_and_open_screenshot ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `page.save_and_open_screenshot`. RUBY end it 'registers an offense for save_page' do expect_offense(<<~RUBY) page.save_page ^^^^^^^^^^^^^^ Remove debugger entry point `page.save_page`. RUBY end it 'registers an offense for save_screenshot' do expect_offense(<<~RUBY) page.save_screenshot ^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `page.save_screenshot`. RUBY end end end context 'debug.rb' do it 'registers an offense for a `b` binding call' do expect_offense(<<~RUBY) binding.b ^^^^^^^^^ Remove debugger entry point `binding.b`. RUBY end it 'registers an offense for a `break` binding call' do expect_offense(<<~RUBY) binding.break ^^^^^^^^^^^^^ Remove debugger entry point `binding.break`. RUBY end it 'registers an offense for a `binding.b` with `Kernel` call' do expect_offense(<<~RUBY) Kernel.binding.b ^^^^^^^^^^^^^^^^ Remove debugger entry point `Kernel.binding.b`. RUBY end it 'registers an offense for a `binding.break` with `Kernel` call' do expect_offense(<<~RUBY) Kernel.binding.break ^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `Kernel.binding.break`. RUBY end end context 'pry' do it 'registers an offense for a pry call' do expect_offense(<<~RUBY) pry ^^^ Remove debugger entry point `pry`. RUBY end it 'registers an offense for a pry with an argument call' do expect_offense(<<~RUBY) pry foo ^^^^^^^ Remove debugger entry point `pry foo`. RUBY end it 'registers an offense for a pry binding call' do expect_offense(<<~RUBY) binding.pry ^^^^^^^^^^^ Remove debugger entry point `binding.pry`. RUBY end it 'registers an offense for a remote_pry binding call' do expect_offense(<<~RUBY) binding.remote_pry ^^^^^^^^^^^^^^^^^^ Remove debugger entry point `binding.remote_pry`. RUBY end it 'registers an offense for a pry_remote binding call' do expect_offense(<<~RUBY) binding.pry_remote ^^^^^^^^^^^^^^^^^^ Remove debugger entry point `binding.pry_remote`. RUBY end it 'registers an offense for a pry binding with an argument call' do expect_offense(<<~RUBY) binding.pry foo ^^^^^^^^^^^^^^^ Remove debugger entry point `binding.pry foo`. RUBY end it 'registers an offense for a remote_pry binding with an argument call' do expect_offense(<<~RUBY) binding.remote_pry foo ^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `binding.remote_pry foo`. RUBY end it 'registers an offense for a pry_remote binding with an argument call' do expect_offense(<<~RUBY) binding.pry_remote foo ^^^^^^^^^^^^^^^^^^^^^^ Remove debugger entry point `binding.pry_remote foo`. RUBY end it 'registers an offense for a binding.pry with Kernel call' do expect_offense(<<~RUBY) Kernel.binding.pry ^^^^^^^^^^^^^^^^^^ Remove debugger entry point `Kernel.binding.pry`. RUBY end it 'registers an offense for a Pry.rescue call' do expect_offense(<<~RUBY) def method Pry.rescue { puts 1 } ^^^^^^^^^^ Remove debugger entry point `Pry.rescue`. ::Pry.rescue { puts 1 } ^^^^^^^^^^^^ Remove debugger entry point `::Pry.rescue`. end RUBY end it 'does not register an offense for a `rescue` call without Pry' do expect_no_offenses(<<~RUBY) begin rescue StandardError end RUBY end end context 'rails' do it 'registers an offense for a debugger call' do expect_offense(<<~RUBY) debugger ^^^^^^^^ Remove debugger entry point `debugger`. RUBY end it 'registers an offense for a debugger with an argument call' do expect_offense(<<~RUBY) debugger foo ^^^^^^^^^^^^ Remove debugger entry point `debugger foo`. RUBY end it 'registers an offense for a debugger with Kernel call' do expect_offense(<<~RUBY) Kernel.debugger ^^^^^^^^^^^^^^^ Remove debugger entry point `Kernel.debugger`. RUBY end it 'registers an offense for a debugger with ::Kernel call' do expect_offense(<<~RUBY) ::Kernel.debugger ^^^^^^^^^^^^^^^^^ Remove debugger entry point `::Kernel.debugger`. RUBY end end context 'RubyJard' do it 'registers an offense for a jard call' do expect_offense(<<~RUBY) jard ^^^^ Remove debugger entry point `jard`. RUBY end end context 'web console' do it 'registers an offense for a `binding.console` call' do expect_offense(<<~RUBY) binding.console ^^^^^^^^^^^^^^^ Remove debugger entry point `binding.console`. RUBY end it 'does not register an offense for `console` without a receiver' do expect_no_offenses('console') end end it 'does not register an offense for a binding method that is not disallowed' do expect_no_offenses('binding.pirate') end %w[debugger byebug console pry remote_pry pry_remote irb save_and_open_page save_and_open_screenshot remote_byebug].each do |src| it "does not register an offense for a #{src} in comments" do expect_no_offenses(<<~RUBY) # #{src} # Kernel.#{src} RUBY end it "does not register an offense for a #{src} method" do expect_no_offenses("code.#{src}") end end context 'when a method group is disabled with nil' do let!(:old_pry_config) { cur_cop_config['DebuggerMethods']['Pry'] } before { cur_cop_config['DebuggerMethods']['Pry'] = nil } after { cur_cop_config['DebuggerMethods']['Pry'] = old_pry_config } it 'does not register an offense for a Pry debugger call' do expect_no_offenses('binding.pry') end it 'does register an offense for another group' do expect_offense(<<~RUBY) binding.irb ^^^^^^^^^^^ Remove debugger entry point `binding.irb`. RUBY end end context 'when a method group is disabled with false' do let!(:old_pry_config) { cur_cop_config['DebuggerMethods']['Pry'] } before { cur_cop_config['DebuggerMethods']['Pry'] = false } after { cur_cop_config['DebuggerMethods']['Pry'] = old_pry_config } it 'does not register an offense for a Pry debugger call' do expect_no_offenses('binding.pry') end it 'does register an offense for another group' do expect_offense(<<~RUBY) binding.irb ^^^^^^^^^^^ Remove debugger entry point `binding.irb`. 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/ineffective_access_modifier_spec.rb
spec/rubocop/cop/lint/ineffective_access_modifier_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::IneffectiveAccessModifier, :config do context 'when `private` is applied to a class method' do it 'registers an offense' do expect_offense(<<~RUBY) class C private def self.method ^^^ `private` (on line 2) does not make singleton methods private. Use `private_class_method` or `private` inside a `class << self` block instead. puts "hi" end end RUBY end end context 'when `protected` is applied to a class method' do it 'registers an offense' do expect_offense(<<~RUBY) class C protected def self.method ^^^ `protected` (on line 2) does not make singleton methods protected. Use `protected` inside a `class << self` block instead. puts "hi" end end RUBY end end context 'when `private_class_method` is used' do context 'when `private_class_method` contains all private method names' do it "doesn't register an offense" do expect_no_offenses(<<~RUBY) class C private def self.method puts "hi" end private_class_method :method end RUBY end end context 'when `private_class_method` does not contain the method' do it 'registers an offense' do expect_offense(<<~RUBY) class C private def self.method2 ^^^ `private` (on line 2) does not make singleton methods private. Use `private_class_method` or `private` inside a `class << self` block instead. puts "hi" end private_class_method :method end RUBY end end end context 'when no access modifier is used' do it "doesn't register an offense" do expect_no_offenses(<<~RUBY) class C def self.method puts "hi" end def self.method2 puts "hi" end end RUBY end end context 'when a `class << self` block is used' do it "doesn't register an offense" do expect_no_offenses(<<~RUBY) class C private class << self def self.method puts "hi" end end end RUBY end end context 'when there is an intervening instance method' do it 'still registers an offense' do expect_offense(<<~RUBY) class C private def instance_method end def self.method ^^^ `private` (on line 3) does not make singleton methods private. Use `private_class_method` or `private` inside a `class << self` block instead. puts "hi" end end RUBY end end context 'when there is `begin` before a method definition' do it 'does not register an offense' do expect_no_offenses(<<~RUBY) class C begin end def do_something end end RUBY end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/hash_compare_by_identity_spec.rb
spec/rubocop/cop/lint/hash_compare_by_identity_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::HashCompareByIdentity, :config do it 'registers an offense when using hash methods with `object_id` on receiver as a key' do expect_offense(<<~RUBY) hash.key?(foo.object_id) ^^^^^^^^^^^^^^^^^^^^^^^^ Use `Hash#compare_by_identity` instead of using `object_id` for keys. hash.has_key?(foo.object_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Hash#compare_by_identity` instead of using `object_id` for keys. hash[foo.object_id] = bar ^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Hash#compare_by_identity` instead of using `object_id` for keys. hash[foo.object_id] ^^^^^^^^^^^^^^^^^^^ Use `Hash#compare_by_identity` instead of using `object_id` for keys. hash.fetch(foo.object_id, 42) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Hash#compare_by_identity` instead of using `object_id` for keys. RUBY end it 'registers an offense when using hash method with `object_id` as a key' do expect_offense(<<~RUBY) hash.key?(object_id) ^^^^^^^^^^^^^^^^^^^^ Use `Hash#compare_by_identity` instead of using `object_id` for keys. RUBY end it 'registers an offense when using hash method with `object_id` as a key with safe navigation' do expect_offense(<<~RUBY) hash&.key?(object_id) ^^^^^^^^^^^^^^^^^^^^^ Use `Hash#compare_by_identity` instead of using `object_id` for keys. RUBY end it 'does not register an offense for hash methods without `object_id` as key' do expect_no_offenses(<<~RUBY) hash.key?(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/empty_file_spec.rb
spec/rubocop/cop/lint/empty_file_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::EmptyFile, :config do let(:commissioner) { RuboCop::Cop::Commissioner.new([cop]) } let(:offenses) { commissioner.investigate(processed_source).offenses } let(:cop_config) { { 'AllowComments' => true } } let(:source) { '' } it 'registers an offense when the file is empty' do expect(offenses.size).to eq(1) offense = offenses.first expect(offense.message).to eq('Empty file detected.') expect(offense.severity).to eq(:warning) end it 'does not register an offense when the file contains code' do expect_no_offenses(<<~RUBY) foo.bar RUBY end it 'does not register an offense when the file contains comments' do expect_no_offenses(<<~RUBY) # comment RUBY end context 'when AllowComments is false' do let(:cop_config) { { 'AllowComments' => false } } let(:source) { '# comment' } it 'registers an offense when the file contains comments' do expect(offenses.size).to eq(1) end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/require_range_parentheses_spec.rb
spec/rubocop/cop/lint/require_range_parentheses_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RequireRangeParentheses, :config do it 'registers an offense when the end of the range (`..`) is line break' do expect_offense(<<~RUBY) 42.. ^^^^ Wrap the endless range literal `42..` to avoid precedence ambiguity. do_something RUBY end it 'registers an offense when the end of the range (`...`) is line break' do expect_offense(<<~RUBY) 42... ^^^^^ Wrap the endless range literal `42...` to avoid precedence ambiguity. do_something RUBY end it 'does not register an offense when the end of the range (`..`) is line break and is enclosed in parentheses' do expect_no_offenses(<<~RUBY) (42.. do_something) RUBY end context 'Ruby >= 2.6', :ruby26 do it 'does not register an offense when using endless range only' do expect_no_offenses(<<~RUBY) 42.. RUBY end end context 'Ruby >= 2.7', :ruby27 do it 'does not register an offense when using beginless range only' do expect_no_offenses(<<~RUBY) ..42 RUBY end end it 'does not register an offense when using `42..nil`' do expect_no_offenses(<<~RUBY) 42..nil RUBY end it 'does not register an offense when using `nil..42`' do expect_no_offenses(<<~RUBY) nil..42 RUBY end it 'does not register an offense when begin and end of the range are on the same line' do expect_no_offenses(<<~RUBY) 42..do_something RUBY end it 'does not register an offense when the begin element ends on another line' do expect_no_offenses(<<~RUBY) foo( bar)..baz(quux) 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/big_decimal_new_spec.rb
spec/rubocop/cop/lint/big_decimal_new_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::BigDecimalNew, :config do it 'registers an offense and corrects using `BigDecimal.new()`' do expect_offense(<<~RUBY) BigDecimal.new(123.456, 3) ^^^ `BigDecimal.new()` is deprecated. Use `BigDecimal()` instead. RUBY expect_correction(<<~RUBY) BigDecimal(123.456, 3) RUBY end it 'registers an offense and corrects using `::BigDecimal.new()`' do expect_offense(<<~RUBY) ::BigDecimal.new(123.456, 3) ^^^ `BigDecimal.new()` is deprecated. Use `BigDecimal()` instead. RUBY expect_correction(<<~RUBY) BigDecimal(123.456, 3) RUBY end it 'does not register an offense when using `BigDecimal()`' do expect_no_offenses(<<~RUBY) BigDecimal(123.456, 3) RUBY end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/spec/rubocop/cop/lint/uri_escape_unescape_spec.rb
spec/rubocop/cop/lint/uri_escape_unescape_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::UriEscapeUnescape, :config do it "registers an offense when using `URI.escape('http://example.com')`" do expect_offense(<<~RUBY) URI.escape('http://example.com') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `URI.escape` method is obsolete and should not be used. Instead, use `CGI.escape`, `URI.encode_www_form` or `URI.encode_www_form_component` depending on your specific use case. RUBY end it "registers an offense when using `URI.escape('@?@!', '!?')`" do expect_offense(<<~RUBY) URI.escape('@?@!', '!?') ^^^^^^^^^^^^^^^^^^^^^^^^ `URI.escape` method is obsolete and should not be used. Instead, use `CGI.escape`, `URI.encode_www_form` or `URI.encode_www_form_component` depending on your specific use case. RUBY end it "registers an offense when using `::URI.escape('http://example.com')`" do expect_offense(<<~RUBY) ::URI.escape('http://example.com') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `::URI.escape` method is obsolete and should not be used. Instead, use `CGI.escape`, `URI.encode_www_form` or `URI.encode_www_form_component` depending on your specific use case. RUBY end it "registers an offense when using `URI.encode('http://example.com')`" do expect_offense(<<~RUBY) URI.encode('http://example.com') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `URI.encode` method is obsolete and should not be used. Instead, use `CGI.escape`, `URI.encode_www_form` or `URI.encode_www_form_component` depending on your specific use case. RUBY end it "registers an offense when using `::URI.encode('http://example.com)`" do expect_offense(<<~RUBY) ::URI.encode('http://example.com') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `::URI.encode` method is obsolete and should not be used. Instead, use `CGI.escape`, `URI.encode_www_form` or `URI.encode_www_form_component` depending on your specific use case. RUBY end it 'registers an offense when using `URI.unescape(enc_uri)`' do expect_offense(<<~RUBY) URI.unescape(enc_uri) ^^^^^^^^^^^^^^^^^^^^^ `URI.unescape` method is obsolete and should not be used. Instead, use `CGI.unescape`, `URI.decode_www_form` or `URI.decode_www_form_component` depending on your specific use case. RUBY end it 'registers an offense when using `::URI.unescape(enc_uri)`' do expect_offense(<<~RUBY) ::URI.unescape(enc_uri) ^^^^^^^^^^^^^^^^^^^^^^^ `::URI.unescape` method is obsolete and should not be used. Instead, use `CGI.unescape`, `URI.decode_www_form` or `URI.decode_www_form_component` depending on your specific use case. RUBY end it 'registers an offense when using `URI.decode(enc_uri)`' do expect_offense(<<~RUBY) URI.decode(enc_uri) ^^^^^^^^^^^^^^^^^^^ `URI.decode` method is obsolete and should not be used. Instead, use `CGI.unescape`, `URI.decode_www_form` or `URI.decode_www_form_component` depending on your specific use case. RUBY end it 'registers an offense when using `::URI.decode(enc_uri)`' do expect_offense(<<~RUBY) ::URI.decode(enc_uri) ^^^^^^^^^^^^^^^^^^^^^ `::URI.decode` method is obsolete and should not be used. Instead, use `CGI.unescape`, `URI.decode_www_form` or `URI.decode_www_form_component` depending on your specific use case. 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/heredoc_method_call_position_spec.rb
spec/rubocop/cop/lint/heredoc_method_call_position_spec.rb
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::HeredocMethodCallPosition, :config do context 'correct cases' do it 'accepts simple correct case' do expect_no_offenses(<<~RUBY) <<~SQL foo SQL RUBY end it 'accepts chained correct case' do expect_no_offenses(<<~RUBY) <<~SQL.bar foo SQL RUBY end it 'ignores if no call' do expect_no_offenses(<<~RUBY) <<-SQL foo SQL RUBY end end context 'incorrect cases' do context 'simple incorrect case' do it 'detects' do expect_offense(<<~RUBY) <<-SQL foo SQL .strip_indent ^ Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening. RUBY expect_correction(<<~RUBY) <<-SQL.strip_indent foo SQL RUBY end end context 'simple incorrect case with paren' do it 'detects' do expect_offense(<<~RUBY) <<-SQL foo SQL .foo(bar_baz) ^ Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening. RUBY expect_correction(<<~RUBY) <<-SQL.foo(bar_baz) foo SQL RUBY end end context 'chained case no parens' do it 'detects' do expect_offense(<<~RUBY) <<-SQL foo SQL .strip_indent.foo ^ Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening. RUBY expect_correction(<<~RUBY) <<-SQL.strip_indent.foo foo SQL RUBY end end context 'chained case with parens' do it 'detects' do expect_offense(<<~RUBY) <<-SQL foo SQL .abc(1, 2, 3).foo ^ Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening. RUBY expect_correction(<<~RUBY) <<-SQL.abc(1, 2, 3).foo foo SQL RUBY end end context 'with trailing comma in method call' do it 'detects' do expect_offense(<<~RUBY) bar(<<-SQL foo SQL .abc, ^ Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening. ) RUBY expect_correction(<<~RUBY) bar(<<-SQL.abc, foo SQL ) RUBY end end context 'chained case with multiple line args' do it 'detects' do expect_offense(<<~RUBY) <<-SQL foo SQL .abc(1, 2, ^ Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening. 3).foo RUBY expect_no_corrections end end context 'chained case without args' do it 'detects' do expect_offense(<<~RUBY) <<-SQL foo SQL .abc ^ Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening. .foo RUBY expect_no_corrections end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false