diff options
Diffstat (limited to 'spec/rubocop/cop')
69 files changed, 627 insertions, 911 deletions
diff --git a/spec/rubocop/cop/active_record_association_reload_spec.rb b/spec/rubocop/cop/active_record_association_reload_spec.rb index 8dbe6daeeca..f28c4e60f3c 100644 --- a/spec/rubocop/cop/active_record_association_reload_spec.rb +++ b/spec/rubocop/cop/active_record_association_reload_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../rubocop/cop/active_record_association_reload' RSpec.describe RuboCop::Cop::ActiveRecordAssociationReload do - include CopHelper - subject(:cop) { described_class.new } context 'when using ActiveRecord::Base' do diff --git a/spec/rubocop/cop/api/base_spec.rb b/spec/rubocop/cop/api/base_spec.rb index de05ab93874..ec646b9991b 100644 --- a/spec/rubocop/cop/api/base_spec.rb +++ b/spec/rubocop/cop/api/base_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/api/base' RSpec.describe RuboCop::Cop::API::Base do - include CopHelper - subject(:cop) { described_class.new } let(:corrected) do @@ -17,7 +14,7 @@ RSpec.describe RuboCop::Cop::API::Base do CORRECTED end - ['Grape::API', '::Grape::API', 'Grape::API::Instance', '::Grape::API::Instance'].each do |offense| + %w[Grape::API ::Grape::API Grape::API::Instance ::Grape::API::Instance].each do |offense| it "adds an offense when inheriting from #{offense}" do expect_offense(<<~CODE) class SomeAPI < #{offense} diff --git a/spec/rubocop/cop/api/grape_array_missing_coerce_spec.rb b/spec/rubocop/cop/api/grape_array_missing_coerce_spec.rb index c7bb8255398..b50866b54b3 100644 --- a/spec/rubocop/cop/api/grape_array_missing_coerce_spec.rb +++ b/spec/rubocop/cop/api/grape_array_missing_coerce_spec.rb @@ -5,36 +5,38 @@ require 'rubocop' require_relative '../../../../rubocop/cop/api/grape_array_missing_coerce' RSpec.describe RuboCop::Cop::API::GrapeArrayMissingCoerce do - include CopHelper + let(:msg) do + "This Grape parameter defines an Array but is missing a coerce_with definition. " \ + "For more details, see " \ + "https://github.com/ruby-grape/grape/blob/master/UPGRADING.md#ensure-that-array-types-have-explicit-coercions" + end subject(:cop) { described_class.new } it 'adds an offense with a required parameter' do - inspect_source(<<~CODE) + expect_offense(<<~TYPE) class SomeAPI < Grape::API::Instance params do requires :values, type: Array[String] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg} end end - CODE - - expect(cop.offenses.size).to eq(1) + TYPE end it 'adds an offense with an optional parameter' do - inspect_source(<<~CODE) + expect_offense(<<~TYPE) class SomeAPI < Grape::API::Instance params do optional :values, type: Array[String] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg} end end - CODE - - expect(cop.offenses.size).to eq(1) + TYPE end it 'does not add an offense' do - inspect_source(<<~CODE) + expect_no_offenses(<<~CODE) class SomeAPI < Grape::API::Instance params do requires :values, type: Array[String], coerce_with: ->(val) { val.split(',').map(&:strip) } @@ -44,19 +46,15 @@ RSpec.describe RuboCop::Cop::API::GrapeArrayMissingCoerce do end end CODE - - expect(cop.offenses.size).to be_zero end it 'does not add an offense for unrelated classes' do - inspect_source(<<~CODE) + expect_no_offenses(<<~CODE) class SomeClass params do requires :values, type: Array[String] end end CODE - - expect(cop.offenses.size).to be_zero end end diff --git a/spec/rubocop/cop/avoid_becomes_spec.rb b/spec/rubocop/cop/avoid_becomes_spec.rb index 07cf374faf5..401c694f373 100644 --- a/spec/rubocop/cop/avoid_becomes_spec.rb +++ b/spec/rubocop/cop/avoid_becomes_spec.rb @@ -2,33 +2,31 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/avoid_becomes' RSpec.describe RuboCop::Cop::AvoidBecomes do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of becomes with a constant parameter' do - inspect_source('foo.becomes(Project)') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + foo.becomes(Project) + ^^^^^^^^^^^^^^^^^^^^ Avoid the use of becomes(SomeConstant), [...] + CODE end it 'flags the use of becomes with a namespaced constant parameter' do - inspect_source('foo.becomes(Namespace::Group)') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + foo.becomes(Namespace::Group) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid the use of becomes(SomeConstant), [...] + CODE end it 'flags the use of becomes with a dynamic parameter' do - inspect_source(<<~RUBY) - model = Namespace - project = Project.first - project.becomes(model) - RUBY - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + model = Namespace + project = Project.first + project.becomes(model) + ^^^^^^^^^^^^^^^^^^^^^^ Avoid the use of becomes(SomeConstant), [...] + CODE end end diff --git a/spec/rubocop/cop/avoid_break_from_strong_memoize_spec.rb b/spec/rubocop/cop/avoid_break_from_strong_memoize_spec.rb index 3c3aa5b7b5c..ac59d36db3f 100644 --- a/spec/rubocop/cop/avoid_break_from_strong_memoize_spec.rb +++ b/spec/rubocop/cop/avoid_break_from_strong_memoize_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../rubocop/cop/avoid_break_from_strong_memoize' RSpec.describe RuboCop::Cop::AvoidBreakFromStrongMemoize do - include CopHelper - subject(:cop) { described_class.new } it 'flags violation for break inside strong_memoize' do @@ -56,7 +54,7 @@ RSpec.describe RuboCop::Cop::AvoidBreakFromStrongMemoize do call do strong_memoize(:result) do break if something - + ^^^^^ Do not use break inside strong_memoize, use next instead. do_an_heavy_calculation end end @@ -65,7 +63,7 @@ RSpec.describe RuboCop::Cop::AvoidBreakFromStrongMemoize do expect(instance).to receive(:add_offense).once end - inspect_source(source) + expect_offense(source) end it "doesn't check when block is empty" do diff --git a/spec/rubocop/cop/avoid_keyword_arguments_in_sidekiq_workers_spec.rb b/spec/rubocop/cop/avoid_keyword_arguments_in_sidekiq_workers_spec.rb index 1e1fe851840..460a0b13458 100644 --- a/spec/rubocop/cop/avoid_keyword_arguments_in_sidekiq_workers_spec.rb +++ b/spec/rubocop/cop/avoid_keyword_arguments_in_sidekiq_workers_spec.rb @@ -2,18 +2,15 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/avoid_keyword_arguments_in_sidekiq_workers' RSpec.describe RuboCop::Cop::AvoidKeywordArgumentsInSidekiqWorkers do - include CopHelper - subject(:cop) { described_class.new } it 'flags violation for keyword arguments usage in perform method signature' do expect_offense(<<~RUBY) def perform(id:) - ^^^^^^^^^^^^^^^^ Do not use keyword arguments in Sidekiq workers. For details, check https://github.com/mperham/sidekiq/issues/2372 + ^^^^^^^^^^^^^^^^ Do not use keyword arguments in Sidekiq workers. For details, [...] end RUBY end @@ -21,7 +18,7 @@ RSpec.describe RuboCop::Cop::AvoidKeywordArgumentsInSidekiqWorkers do it 'flags violation for optional keyword arguments usage in perform method signature' do expect_offense(<<~RUBY) def perform(id: nil) - ^^^^^^^^^^^^^^^^^^^^ Do not use keyword arguments in Sidekiq workers. For details, check https://github.com/mperham/sidekiq/issues/2372 + ^^^^^^^^^^^^^^^^^^^^ Do not use keyword arguments in Sidekiq workers. For details, [...] end RUBY end diff --git a/spec/rubocop/cop/ban_catch_throw_spec.rb b/spec/rubocop/cop/ban_catch_throw_spec.rb index 4f669bad4af..b3c4ad8688c 100644 --- a/spec/rubocop/cop/ban_catch_throw_spec.rb +++ b/spec/rubocop/cop/ban_catch_throw_spec.rb @@ -1,30 +1,28 @@ # frozen_string_literal: true require 'fast_spec_helper' - require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/ban_catch_throw' RSpec.describe RuboCop::Cop::BanCatchThrow do - include CopHelper - subject(:cop) { described_class.new } it 'registers an offense when `catch` or `throw` are used' do - inspect_source("catch(:foo) {\n throw(:foo)\n}") - - aggregate_failures do - expect(cop.offenses.size).to eq(2) - expect(cop.offenses.map(&:line)).to eq([1, 2]) - expect(cop.highlights).to eq(['catch(:foo)', 'throw(:foo)']) - end + expect_offense(<<~CODE) + catch(:foo) { + ^^^^^^^^^^^ Do not use catch or throw unless a gem's API demands it. + throw(:foo) + ^^^^^^^^^^^ Do not use catch or throw unless a gem's API demands it. + } + CODE end it 'does not register an offense for a method called catch or throw' do - inspect_source("foo.catch(:foo) {\n foo.throw(:foo)\n}") - - expect(cop.offenses).to be_empty + expect_no_offenses(<<~CODE) + foo.catch(:foo) { + foo.throw(:foo) + } + CODE end end diff --git a/spec/rubocop/cop/code_reuse/finder_spec.rb b/spec/rubocop/cop/code_reuse/finder_spec.rb index 6f04d5e0d60..484a1549a89 100644 --- a/spec/rubocop/cop/code_reuse/finder_spec.rb +++ b/spec/rubocop/cop/code_reuse/finder_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/code_reuse/finder' RSpec.describe RuboCop::Cop::CodeReuse::Finder do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of a Finder inside another Finder' do @@ -23,8 +20,6 @@ RSpec.describe RuboCop::Cop::CodeReuse::Finder do end end SOURCE - - expect(cop.offenses.size).to eq(1) end it 'flags the use of a Finder inside a model class method' do diff --git a/spec/rubocop/cop/code_reuse/presenter_spec.rb b/spec/rubocop/cop/code_reuse/presenter_spec.rb index 8efd4da8aa1..4639854588e 100644 --- a/spec/rubocop/cop/code_reuse/presenter_spec.rb +++ b/spec/rubocop/cop/code_reuse/presenter_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/code_reuse/presenter' RSpec.describe RuboCop::Cop::CodeReuse::Presenter do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of a Presenter in a Service class' do diff --git a/spec/rubocop/cop/code_reuse/serializer_spec.rb b/spec/rubocop/cop/code_reuse/serializer_spec.rb index 74999df5859..84db2e62b41 100644 --- a/spec/rubocop/cop/code_reuse/serializer_spec.rb +++ b/spec/rubocop/cop/code_reuse/serializer_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/code_reuse/serializer' RSpec.describe RuboCop::Cop::CodeReuse::Serializer do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of a Serializer in a Service class' do diff --git a/spec/rubocop/cop/code_reuse/service_class_spec.rb b/spec/rubocop/cop/code_reuse/service_class_spec.rb index 4870daf72dc..b6d94dd749f 100644 --- a/spec/rubocop/cop/code_reuse/service_class_spec.rb +++ b/spec/rubocop/cop/code_reuse/service_class_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/code_reuse/service_class' RSpec.describe RuboCop::Cop::CodeReuse::ServiceClass do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of a Service class in a Finder' do diff --git a/spec/rubocop/cop/code_reuse/worker_spec.rb b/spec/rubocop/cop/code_reuse/worker_spec.rb index 9e015f286d8..42c9303a93b 100644 --- a/spec/rubocop/cop/code_reuse/worker_spec.rb +++ b/spec/rubocop/cop/code_reuse/worker_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/code_reuse/worker' RSpec.describe RuboCop::Cop::CodeReuse::Worker do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of a worker in a controller' do diff --git a/spec/rubocop/cop/default_scope_spec.rb b/spec/rubocop/cop/default_scope_spec.rb index fee1895603c..506843e030e 100644 --- a/spec/rubocop/cop/default_scope_spec.rb +++ b/spec/rubocop/cop/default_scope_spec.rb @@ -2,47 +2,44 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/default_scope' RSpec.describe RuboCop::Cop::DefaultScope do - include CopHelper - subject(:cop) { described_class.new } it 'does not flag the use of default_scope with a send receiver' do - inspect_source('foo.default_scope') - - expect(cop.offenses.size).to eq(0) + expect_no_offenses('foo.default_scope') end it 'flags the use of default_scope with a constant receiver' do - inspect_source('User.default_scope') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~SOURCE) + User.default_scope + ^^^^^^^^^^^^^^^^^^ Do not use `default_scope`, [...] + SOURCE end it 'flags the use of default_scope with a nil receiver' do - inspect_source('class Foo ; default_scope ; end') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~SOURCE) + class Foo ; default_scope ; end + ^^^^^^^^^^^^^ Do not use `default_scope`, [...] + SOURCE end it 'flags the use of default_scope when passing arguments' do - inspect_source('class Foo ; default_scope(:foo) ; end') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~SOURCE) + class Foo ; default_scope(:foo) ; end + ^^^^^^^^^^^^^^^^^^^ Do not use `default_scope`, [...] + SOURCE end it 'flags the use of default_scope when passing a block' do - inspect_source('class Foo ; default_scope { :foo } ; end') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~SOURCE) + class Foo ; default_scope { :foo } ; end + ^^^^^^^^^^^^^ Do not use `default_scope`, [...] + SOURCE end it 'ignores the use of default_scope with a local variable receiver' do - inspect_source('users = User.all ; users.default_scope') - - expect(cop.offenses.size).to eq(0) + expect_no_offenses('users = User.all ; users.default_scope') end end diff --git a/spec/rubocop/cop/destroy_all_spec.rb b/spec/rubocop/cop/destroy_all_spec.rb index df664724a91..f6850a00238 100644 --- a/spec/rubocop/cop/destroy_all_spec.rb +++ b/spec/rubocop/cop/destroy_all_spec.rb @@ -2,44 +2,41 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/destroy_all' RSpec.describe RuboCop::Cop::DestroyAll do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of destroy_all with a send receiver' do - inspect_source('foo.destroy_all # rubocop: disable Cop/DestroyAll') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + foo.destroy_all # rubocop: disable Cop/DestroyAll + ^^^^^^^^^^^^^^^ Use `delete_all` instead of `destroy_all`. [...] + CODE end it 'flags the use of destroy_all with a constant receiver' do - inspect_source('User.destroy_all # rubocop: disable Cop/DestroyAll') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + User.destroy_all # rubocop: disable Cop/DestroyAll + ^^^^^^^^^^^^^^^^ Use `delete_all` instead of `destroy_all`. [...] + CODE end it 'flags the use of destroy_all when passing arguments' do - inspect_source('User.destroy_all([])') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + User.destroy_all([]) + ^^^^^^^^^^^^^^^^^^^^ Use `delete_all` instead of `destroy_all`. [...] + CODE end it 'flags the use of destroy_all with a local variable receiver' do - inspect_source(<<~RUBY) - users = User.all - users.destroy_all # rubocop: disable Cop/DestroyAll - RUBY - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + users = User.all + users.destroy_all # rubocop: disable Cop/DestroyAll + ^^^^^^^^^^^^^^^^^ Use `delete_all` instead of `destroy_all`. [...] + CODE end it 'does not flag the use of delete_all' do - inspect_source('foo.delete_all') - - expect(cop.offenses).to be_empty + expect_no_offenses('foo.delete_all') end end diff --git a/spec/rubocop/cop/gitlab/avoid_uploaded_file_from_params_spec.rb b/spec/rubocop/cop/gitlab/avoid_uploaded_file_from_params_spec.rb index 2db03898e01..f96e25c59e7 100644 --- a/spec/rubocop/cop/gitlab/avoid_uploaded_file_from_params_spec.rb +++ b/spec/rubocop/cop/gitlab/avoid_uploaded_file_from_params_spec.rb @@ -2,19 +2,16 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/avoid_uploaded_file_from_params' RSpec.describe RuboCop::Cop::Gitlab::AvoidUploadedFileFromParams do - include CopHelper - subject(:cop) { described_class.new } - context 'UploadedFile.from_params' do + context 'when using UploadedFile.from_params' do it 'flags its call' do expect_offense(<<~SOURCE) - UploadedFile.from_params(params) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the `UploadedFile` set by `multipart.rb` instead of calling `UploadedFile.from_params` directly. See https://docs.gitlab.com/ee/development/uploads.html#how-to-add-a-new-upload-route + UploadedFile.from_params(params) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the `UploadedFile` set by `multipart.rb` instead of calling [...] SOURCE end end diff --git a/spec/rubocop/cop/gitlab/bulk_insert_spec.rb b/spec/rubocop/cop/gitlab/bulk_insert_spec.rb index ad7e685e505..c280ab8fa8b 100644 --- a/spec/rubocop/cop/gitlab/bulk_insert_spec.rb +++ b/spec/rubocop/cop/gitlab/bulk_insert_spec.rb @@ -2,25 +2,22 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/bulk_insert' RSpec.describe RuboCop::Cop::Gitlab::BulkInsert do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of Gitlab::Database.bulk_insert' do expect_offense(<<~SOURCE) - Gitlab::Database.bulk_insert('merge_request_diff_files', rows) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{RuboCop::Cop::Gitlab::BulkInsert::MSG} + Gitlab::Database.bulk_insert('merge_request_diff_files', rows) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the `BulkInsertSafe` concern, [...] SOURCE end it 'flags the use of ::Gitlab::Database.bulk_insert' do expect_offense(<<~SOURCE) - ::Gitlab::Database.bulk_insert('merge_request_diff_files', rows) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{RuboCop::Cop::Gitlab::BulkInsert::MSG} + ::Gitlab::Database.bulk_insert('merge_request_diff_files', rows) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the `BulkInsertSafe` concern, [...] SOURCE end end diff --git a/spec/rubocop/cop/gitlab/change_timezone_spec.rb b/spec/rubocop/cop/gitlab/change_timezone_spec.rb index 6abbc06bb1a..9cb822ec4f2 100644 --- a/spec/rubocop/cop/gitlab/change_timezone_spec.rb +++ b/spec/rubocop/cop/gitlab/change_timezone_spec.rb @@ -2,19 +2,16 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/change_timzone' RSpec.describe RuboCop::Cop::Gitlab::ChangeTimezone do - include CopHelper - subject(:cop) { described_class.new } context 'Time.zone=' do it 'registers an offense with no 2nd argument' do expect_offense(<<~PATTERN) Time.zone = 'Awkland' - ^^^^^^^^^^^^^^^^^^^^^ Do not change timezone in the runtime (application or rspec), it could result in silently modifying other behavior. + ^^^^^^^^^^^^^^^^^^^^^ Do not change timezone in the runtime (application or rspec), it could result [...] PATTERN end end diff --git a/spec/rubocop/cop/gitlab/const_get_inherit_false_spec.rb b/spec/rubocop/cop/gitlab/const_get_inherit_false_spec.rb index bed06ab2b17..19e5fe946be 100644 --- a/spec/rubocop/cop/gitlab/const_get_inherit_false_spec.rb +++ b/spec/rubocop/cop/gitlab/const_get_inherit_false_spec.rb @@ -2,78 +2,75 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/const_get_inherit_false' RSpec.describe RuboCop::Cop::Gitlab::ConstGetInheritFalse do - include CopHelper - subject(:cop) { described_class.new } context 'Object.const_get' do - it 'registers an offense with no 2nd argument' do + it 'registers an offense with no 2nd argument and corrects' do expect_offense(<<~PATTERN) Object.const_get(:CONSTANT) ^^^^^^^^^ Use inherit=false when using const_get. PATTERN - end - it 'autocorrects' do - expect(autocorrect_source('Object.const_get(:CONSTANT)')).to eq('Object.const_get(:CONSTANT, false)') + expect_correction(<<~PATTERN) + Object.const_get(:CONSTANT, false) + PATTERN end context 'inherit=false' do it 'does not register an offense' do expect_no_offenses(<<~PATTERN) - Object.const_get(:CONSTANT, false) + Object.const_get(:CONSTANT, false) PATTERN end end context 'inherit=true' do - it 'registers an offense' do + it 'registers an offense and corrects' do expect_offense(<<~PATTERN) - Object.const_get(:CONSTANT, true) - ^^^^^^^^^ Use inherit=false when using const_get. + Object.const_get(:CONSTANT, true) + ^^^^^^^^^ Use inherit=false when using const_get. PATTERN - end - it 'autocorrects' do - expect(autocorrect_source('Object.const_get(:CONSTANT, true)')).to eq('Object.const_get(:CONSTANT, false)') + expect_correction(<<~PATTERN) + Object.const_get(:CONSTANT, false) + PATTERN end end end context 'const_get for a nested class' do - it 'registers an offense on reload usage' do + it 'registers an offense on reload usage and corrects' do expect_offense(<<~PATTERN) Nested::Blog.const_get(:CONSTANT) ^^^^^^^^^ Use inherit=false when using const_get. PATTERN - end - it 'autocorrects' do - expect(autocorrect_source('Nested::Blag.const_get(:CONSTANT)')).to eq('Nested::Blag.const_get(:CONSTANT, false)') + expect_correction(<<~PATTERN) + Nested::Blog.const_get(:CONSTANT, false) + PATTERN end context 'inherit=false' do it 'does not register an offense' do expect_no_offenses(<<~PATTERN) - Nested::Blog.const_get(:CONSTANT, false) + Nested::Blog.const_get(:CONSTANT, false) PATTERN end end context 'inherit=true' do - it 'registers an offense if inherit is true' do + it 'registers an offense if inherit is true and corrects' do expect_offense(<<~PATTERN) - Nested::Blog.const_get(:CONSTANT, true) - ^^^^^^^^^ Use inherit=false when using const_get. + Nested::Blog.const_get(:CONSTANT, true) + ^^^^^^^^^ Use inherit=false when using const_get. PATTERN - end - it 'autocorrects' do - expect(autocorrect_source('Nested::Blag.const_get(:CONSTANT, true)')).to eq('Nested::Blag.const_get(:CONSTANT, false)') + expect_correction(<<~PATTERN) + Nested::Blog.const_get(:CONSTANT, false) + PATTERN end end end diff --git a/spec/rubocop/cop/gitlab/duplicate_spec_location_spec.rb b/spec/rubocop/cop/gitlab/duplicate_spec_location_spec.rb index 5804b03b641..a207155f432 100644 --- a/spec/rubocop/cop/gitlab/duplicate_spec_location_spec.rb +++ b/spec/rubocop/cop/gitlab/duplicate_spec_location_spec.rb @@ -6,8 +6,6 @@ require 'rubocop' require_relative '../../../../rubocop/cop/gitlab/duplicate_spec_location' RSpec.describe RuboCop::Cop::Gitlab::DuplicateSpecLocation do - include CopHelper - subject(:cop) { described_class.new } let(:rails_root) { '../../../../' } diff --git a/spec/rubocop/cop/gitlab/except_spec.rb b/spec/rubocop/cop/gitlab/except_spec.rb index 173e5943da5..7a122e3cf53 100644 --- a/spec/rubocop/cop/gitlab/except_spec.rb +++ b/spec/rubocop/cop/gitlab/except_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/except' RSpec.describe RuboCop::Cop::Gitlab::Except do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of Gitlab::SQL::Except.new' do diff --git a/spec/rubocop/cop/gitlab/finder_with_find_by_spec.rb b/spec/rubocop/cop/gitlab/finder_with_find_by_spec.rb index db3bcf1dfdb..03d7fc5e8b1 100644 --- a/spec/rubocop/cop/gitlab/finder_with_find_by_spec.rb +++ b/spec/rubocop/cop/gitlab/finder_with_find_by_spec.rb @@ -1,46 +1,31 @@ # frozen_string_literal: true require 'fast_spec_helper' - require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/finder_with_find_by' RSpec.describe RuboCop::Cop::Gitlab::FinderWithFindBy do - include CopHelper - subject(:cop) { described_class.new } context 'when calling execute.find' do - let(:source) do - <<~SRC - DummyFinder.new(some_args) - .execute - .find_by!(1) - SRC - end - - let(:corrected_source) do - <<~SRC - DummyFinder.new(some_args) - .find_by!(1) - SRC - end - - it 'registers an offence' do - inspect_source(source) - - expect(cop.offenses.size).to eq(1) - end - - it 'can autocorrect the source' do - expect(autocorrect_source(source)).to eq(corrected_source) + it 'registers an offense and corrects' do + expect_offense(<<~CODE) + DummyFinder.new(some_args) + .execute + .find_by!(1) + ^^^^^^^^ Don't chain finders `#execute` method with [...] + CODE + + expect_correction(<<~CODE) + DummyFinder.new(some_args) + .find_by!(1) + CODE end context 'when called within the `FinderMethods` module' do - let(:source) do - <<~SRC + it 'does not register an offense' do + expect_no_offenses(<<~SRC) module FinderMethods def find_by!(*args) execute.find_by!(args) @@ -48,12 +33,6 @@ RSpec.describe RuboCop::Cop::Gitlab::FinderWithFindBy do end SRC end - - it 'does not register an offence' do - inspect_source(source) - - expect(cop.offenses).to be_empty - end end end end diff --git a/spec/rubocop/cop/gitlab/httparty_spec.rb b/spec/rubocop/cop/gitlab/httparty_spec.rb index b112ac84bff..fcd18b0eb9b 100644 --- a/spec/rubocop/cop/gitlab/httparty_spec.rb +++ b/spec/rubocop/cop/gitlab/httparty_spec.rb @@ -2,46 +2,30 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/httparty' RSpec.describe RuboCop::Cop::Gitlab::HTTParty do # rubocop:disable RSpec/FilePath - include CopHelper - subject(:cop) { described_class.new } - shared_examples('registering include offense') do |options| - let(:offending_lines) { options[:offending_lines] } - + shared_examples('registering include offense') do it 'registers an offense when the class includes HTTParty' do - inspect_source(source) - - aggregate_failures do - expect(cop.offenses.size).to eq(offending_lines.size) - expect(cop.offenses.map(&:line)).to eq(offending_lines) - end + expect_offense(source) end end - shared_examples('registering call offense') do |options| - let(:offending_lines) { options[:offending_lines] } - + shared_examples('registering call offense') do it 'registers an offense when the class calls HTTParty' do - inspect_source(source) - - aggregate_failures do - expect(cop.offenses.size).to eq(offending_lines.size) - expect(cop.offenses.map(&:line)).to eq(offending_lines) - end + expect_offense(source) end end context 'when source is a regular module' do - it_behaves_like 'registering include offense', offending_lines: [2] do + it_behaves_like 'registering include offense' do let(:source) do <<~RUBY module M include HTTParty + ^^^^^^^^^^^^^^^^ Avoid including `HTTParty` directly. [...] end RUBY end @@ -49,11 +33,12 @@ RSpec.describe RuboCop::Cop::Gitlab::HTTParty do # rubocop:disable RSpec/FilePat end context 'when source is a regular class' do - it_behaves_like 'registering include offense', offending_lines: [2] do + it_behaves_like 'registering include offense' do let(:source) do <<~RUBY class Foo include HTTParty + ^^^^^^^^^^^^^^^^ Avoid including `HTTParty` directly. [...] end RUBY end @@ -61,12 +46,13 @@ RSpec.describe RuboCop::Cop::Gitlab::HTTParty do # rubocop:disable RSpec/FilePat end context 'when HTTParty is called' do - it_behaves_like 'registering call offense', offending_lines: [3] do + it_behaves_like 'registering call offense' do let(:source) do <<~RUBY class Foo def bar HTTParty.get('http://example.com') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid calling `HTTParty` directly. [...] end end RUBY diff --git a/spec/rubocop/cop/gitlab/intersect_spec.rb b/spec/rubocop/cop/gitlab/intersect_spec.rb index e724f47029c..6f0367591cd 100644 --- a/spec/rubocop/cop/gitlab/intersect_spec.rb +++ b/spec/rubocop/cop/gitlab/intersect_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/intersect' RSpec.describe RuboCop::Cop::Gitlab::Intersect do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of Gitlab::SQL::Intersect.new' do diff --git a/spec/rubocop/cop/gitlab/json_spec.rb b/spec/rubocop/cop/gitlab/json_spec.rb index fc25f69a244..29c3b96cc1a 100644 --- a/spec/rubocop/cop/gitlab/json_spec.rb +++ b/spec/rubocop/cop/gitlab/json_spec.rb @@ -2,38 +2,21 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/json' RSpec.describe RuboCop::Cop::Gitlab::Json do - include CopHelper - subject(:cop) { described_class.new } - shared_examples('registering call offense') do |options| - let(:offending_lines) { options[:offending_lines] } - - it 'registers an offense when the class calls JSON' do - inspect_source(source) - - aggregate_failures do - expect(cop.offenses.size).to eq(offending_lines.size) - expect(cop.offenses.map(&:line)).to eq(offending_lines) - end - end - end - context 'when JSON is called' do - it_behaves_like 'registering call offense', offending_lines: [3] do - let(:source) do - <<~RUBY - class Foo - def bar - JSON.parse('{ "foo": "bar" }') - end + it 'registers an offense' do + expect_offense(<<~RUBY) + class Foo + def bar + JSON.parse('{ "foo": "bar" }') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid calling `JSON` directly. [...] end - RUBY - end + end + RUBY end end end diff --git a/spec/rubocop/cop/gitlab/module_with_instance_variables_spec.rb b/spec/rubocop/cop/gitlab/module_with_instance_variables_spec.rb index 1d09c720bf7..08634d5753a 100644 --- a/spec/rubocop/cop/gitlab/module_with_instance_variables_spec.rb +++ b/spec/rubocop/cop/gitlab/module_with_instance_variables_spec.rb @@ -2,42 +2,33 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/module_with_instance_variables' RSpec.describe RuboCop::Cop::Gitlab::ModuleWithInstanceVariables do - include CopHelper + let(:msg) { "Do not use instance variables in a module. [...]" } subject(:cop) { described_class.new } - shared_examples('registering offense') do |options| - let(:offending_lines) { options[:offending_lines] } - + shared_examples('registering offense') do it 'registers an offense when instance variable is used in a module' do - inspect_source(source) - - aggregate_failures do - expect(cop.offenses.size).to eq(offending_lines.size) - expect(cop.offenses.map(&:line)).to eq(offending_lines) - end + expect_offense(source) end end shared_examples('not registering offense') do it 'does not register offenses' do - inspect_source(source) - - expect(cop.offenses).to be_empty + expect_no_offenses(source) end end context 'when source is a regular module' do - it_behaves_like 'registering offense', offending_lines: [3] do + it_behaves_like 'registering offense' do let(:source) do <<~RUBY module M def f @f = true + ^^^^^^^^^ #{msg} end end RUBY @@ -46,13 +37,14 @@ RSpec.describe RuboCop::Cop::Gitlab::ModuleWithInstanceVariables do end context 'when source is a nested module' do - it_behaves_like 'registering offense', offending_lines: [4] do + it_behaves_like 'registering offense' do let(:source) do <<~RUBY module N module M def f @f = true + ^^^^^^^^^ #{msg} end end end @@ -62,13 +54,14 @@ RSpec.describe RuboCop::Cop::Gitlab::ModuleWithInstanceVariables do end context 'when source is a nested module with multiple offenses' do - it_behaves_like 'registering offense', offending_lines: [4, 12] do + it_behaves_like 'registering offense' do let(:source) do <<~RUBY module N module M def f @f = true + ^^^^^^^^^ #{msg} end def g @@ -77,6 +70,7 @@ RSpec.describe RuboCop::Cop::Gitlab::ModuleWithInstanceVariables do def h @h = true + ^^^^^^^^^ #{msg} end end end @@ -129,12 +123,13 @@ RSpec.describe RuboCop::Cop::Gitlab::ModuleWithInstanceVariables do end context 'when source is using simple or ivar assignment with other ivar' do - it_behaves_like 'registering offense', offending_lines: [3] do + it_behaves_like 'registering offense' do let(:source) do <<~RUBY module M def f @f ||= g(@g) + ^^ #{msg} end end RUBY @@ -143,13 +138,15 @@ RSpec.describe RuboCop::Cop::Gitlab::ModuleWithInstanceVariables do end context 'when source is using or ivar assignment with something else' do - it_behaves_like 'registering offense', offending_lines: [3, 4] do + it_behaves_like 'registering offense' do let(:source) do <<~RUBY module M def f @f ||= true + ^^ #{msg} @f.to_s + ^^ #{msg} end end RUBY diff --git a/spec/rubocop/cop/gitlab/namespaced_class_spec.rb b/spec/rubocop/cop/gitlab/namespaced_class_spec.rb new file mode 100644 index 00000000000..d1f61aa5afb --- /dev/null +++ b/spec/rubocop/cop/gitlab/namespaced_class_spec.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +require 'fast_spec_helper' +require 'rubocop' +require 'rubocop/rspec/support' +require_relative '../../../../rubocop/cop/gitlab/namespaced_class' + +RSpec.describe RuboCop::Cop::Gitlab::NamespacedClass do + subject(:cop) { described_class.new } + + it 'flags a class definition without namespace' do + expect_offense(<<~SOURCE) + class MyClass + ^^^^^^^^^^^^^ #{described_class::MSG} + end + SOURCE + end + + it 'flags a class definition with inheritance without namespace' do + expect_offense(<<~SOURCE) + class MyClass < ApplicationRecord + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{described_class::MSG} + def some_method + true + end + end + SOURCE + end + + it 'does not flag the class definition with namespace in separate lines' do + expect_no_offenses(<<~SOURCE) + module MyModule + class MyClass < ApplicationRecord + end + + class MyOtherClass + def other_method + 1 + 1 + end + end + end + SOURCE + end + + it 'does not flag the class definition with nested namespace in separate lines' do + expect_no_offenses(<<~SOURCE) + module TopLevelModule + module NestedModule + class MyClass + end + end + end + SOURCE + end + + it 'does not flag the class definition nested inside namespaced class' do + expect_no_offenses(<<~SOURCE) + module TopLevelModule + class TopLevelClass + class MyClass + end + end + end + SOURCE + end + + it 'does not flag a compact namespaced class definition' do + expect_no_offenses(<<~SOURCE) + class MyModule::MyClass < ApplicationRecord + end + SOURCE + end +end diff --git a/spec/rubocop/cop/gitlab/policy_rule_boolean_spec.rb b/spec/rubocop/cop/gitlab/policy_rule_boolean_spec.rb index e6fb9ab9d57..6dbbcdd8324 100644 --- a/spec/rubocop/cop/gitlab/policy_rule_boolean_spec.rb +++ b/spec/rubocop/cop/gitlab/policy_rule_boolean_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/policy_rule_boolean' RSpec.describe RuboCop::Cop::Gitlab::PolicyRuleBoolean do - include CopHelper - subject(:cop) { described_class.new } it 'registers offense for &&' do diff --git a/spec/rubocop/cop/gitlab/predicate_memoization_spec.rb b/spec/rubocop/cop/gitlab/predicate_memoization_spec.rb index 322c7c82968..071ddcf8b7d 100644 --- a/spec/rubocop/cop/gitlab/predicate_memoization_spec.rb +++ b/spec/rubocop/cop/gitlab/predicate_memoization_spec.rb @@ -2,55 +2,38 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/predicate_memoization' RSpec.describe RuboCop::Cop::Gitlab::PredicateMemoization do - include CopHelper - subject(:cop) { described_class.new } - shared_examples('registering offense') do |options| - let(:offending_lines) { options[:offending_lines] } - - it 'registers an offense when a predicate method is memoizing via ivar' do - inspect_source(source) - - aggregate_failures do - expect(cop.offenses.size).to eq(offending_lines.size) - expect(cop.offenses.map(&:line)).to eq(offending_lines) - end - end - end - shared_examples('not registering offense') do it 'does not register offenses' do - inspect_source(source) - - expect(cop.offenses).to be_empty + expect_no_offenses(source) end end - context 'when source is a predicate method memoizing via ivar' do - it_behaves_like 'registering offense', offending_lines: [3] do + context 'when source is a predicate method using ivar with assignment' do + it_behaves_like 'not registering offense' do let(:source) do <<~RUBY class C def really? - @really ||= true + @really = true end end RUBY end end + end - it_behaves_like 'registering offense', offending_lines: [4] do + context 'when source is a predicate method using local with ||=' do + it_behaves_like 'not registering offense' do let(:source) do <<~RUBY class C def really? - value = true - @really ||= value + really ||= true end end RUBY @@ -58,13 +41,13 @@ RSpec.describe RuboCop::Cop::Gitlab::PredicateMemoization do end end - context 'when source is a predicate method using ivar with assignment' do + context 'when source is a regular method memoizing via ivar' do it_behaves_like 'not registering offense' do let(:source) do <<~RUBY class C - def really? - @really = true + def really + @really ||= true end end RUBY @@ -72,30 +55,37 @@ RSpec.describe RuboCop::Cop::Gitlab::PredicateMemoization do end end - context 'when source is a predicate method using local with ||=' do - it_behaves_like 'not registering offense' do - let(:source) do - <<~RUBY + context 'when source is a predicate method memoizing via ivar' do + let(:msg) { "Avoid using `@value ||= query` [...]" } + + context 'when assigning to boolean' do + it 'registers an offense' do + node = "@really ||= true" + + expect_offense(<<~CODE, node: node, msg: msg) class C def really? - really ||= true + %{node} + ^{node} %{msg} end end - RUBY + CODE end end - end - context 'when source is a regular method memoizing via ivar' do - it_behaves_like 'not registering offense' do - let(:source) do - <<~RUBY + context 'when assigning to another variable that is a boolean' do + it 'registers an offense' do + node = "@really ||= value" + + expect_offense(<<~CODE, node: node, msg: msg) class C - def really - @really ||= true + def really? + value = true + %{node} + ^{node} %{msg} end end - RUBY + CODE end end end diff --git a/spec/rubocop/cop/gitlab/rails_logger_spec.rb b/spec/rubocop/cop/gitlab/rails_logger_spec.rb index 768da243b02..7258b047191 100644 --- a/spec/rubocop/cop/gitlab/rails_logger_spec.rb +++ b/spec/rubocop/cop/gitlab/rails_logger_spec.rb @@ -2,37 +2,31 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/rails_logger' RSpec.describe RuboCop::Cop::Gitlab::RailsLogger do - include CopHelper - subject(:cop) { described_class.new } described_class::LOG_METHODS.each do |method| it "flags the use of Rails.logger.#{method} with a constant receiver" do - inspect_source("Rails.logger.#{method}('some error')") + node = "Rails.logger.#{method}('some error')" - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE, node: node, msg: "Use a structured JSON logger instead of `Rails.logger`. [...]") + %{node} + ^{node} %{msg} + CODE end end it 'does not flag the use of Rails.logger with a constant that is not Rails' do - inspect_source("AppLogger.error('some error')") - - expect(cop.offenses.size).to eq(0) + expect_no_offenses("AppLogger.error('some error')") end it 'does not flag the use of logger with a send receiver' do - inspect_source("file_logger.info('important info')") - - expect(cop.offenses.size).to eq(0) + expect_no_offenses("file_logger.info('important info')") end it 'does not flag the use of Rails.logger.level' do - inspect_source("Rails.logger.level") - - expect(cop.offenses.size).to eq(0) + expect_no_offenses("Rails.logger.level") end end diff --git a/spec/rubocop/cop/gitlab/union_spec.rb b/spec/rubocop/cop/gitlab/union_spec.rb index 20364b1b901..04a3db8e7dd 100644 --- a/spec/rubocop/cop/gitlab/union_spec.rb +++ b/spec/rubocop/cop/gitlab/union_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/union' RSpec.describe RuboCop::Cop::Gitlab::Union do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of Gitlab::SQL::Union.new' do diff --git a/spec/rubocop/cop/graphql/authorize_types_spec.rb b/spec/rubocop/cop/graphql/authorize_types_spec.rb index a1b7a3f3a9b..9242b865b20 100644 --- a/spec/rubocop/cop/graphql/authorize_types_spec.rb +++ b/spec/rubocop/cop/graphql/authorize_types_spec.rb @@ -6,21 +6,18 @@ require 'rubocop' require_relative '../../../../rubocop/cop/graphql/authorize_types' RSpec.describe RuboCop::Cop::Graphql::AuthorizeTypes do - include CopHelper - subject(:cop) { described_class.new } it 'adds an offense when there is no authorize call' do - inspect_source(<<~TYPE) + expect_offense(<<~TYPE) module Types class AType < BaseObject + ^^^^^^^^^^^^^^^^^^^^^^^^ Add an `authorize :ability` call to the type: https://docs.gitlab.com/ee/development/api_graphql_styleguide.html#type-authorization field :a_thing field :another_thing end end TYPE - - expect(cop.offenses.size).to eq 1 end it 'does not add an offense for classes that have an authorize call' do diff --git a/spec/rubocop/cop/graphql/descriptions_spec.rb b/spec/rubocop/cop/graphql/descriptions_spec.rb index b44205b0920..9ad40fad83d 100644 --- a/spec/rubocop/cop/graphql/descriptions_spec.rb +++ b/spec/rubocop/cop/graphql/descriptions_spec.rb @@ -5,38 +5,34 @@ require 'rubocop' require_relative '../../../../rubocop/cop/graphql/descriptions' RSpec.describe RuboCop::Cop::Graphql::Descriptions do - include CopHelper - subject(:cop) { described_class.new } context 'fields' do it 'adds an offense when there is no description' do - inspect_source(<<~TYPE) + expect_offense(<<~TYPE) module Types class FakeType < BaseObject field :a_thing, + ^^^^^^^^^^^^^^^ Please add a `description` property. GraphQL::STRING_TYPE, null: false end end TYPE - - expect(cop.offenses.size).to eq 1 end it 'adds an offense when description does not end in a period' do - inspect_source(<<~TYPE) + expect_offense(<<~TYPE) module Types class FakeType < BaseObject field :a_thing, + ^^^^^^^^^^^^^^^ `description` strings must end with a `.`. GraphQL::STRING_TYPE, null: false, description: 'A descriptive description' end end TYPE - - expect(cop.offenses.size).to eq 1 end it 'does not add an offense when description is correct' do @@ -55,32 +51,30 @@ RSpec.describe RuboCop::Cop::Graphql::Descriptions do context 'arguments' do it 'adds an offense when there is no description' do - inspect_source(<<~TYPE) + expect_offense(<<~TYPE) module Types class FakeType < BaseObject argument :a_thing, + ^^^^^^^^^^^^^^^^^^ Please add a `description` property. GraphQL::STRING_TYPE, null: false end end TYPE - - expect(cop.offenses.size).to eq 1 end it 'adds an offense when description does not end in a period' do - inspect_source(<<~TYPE) + expect_offense(<<~TYPE) module Types class FakeType < BaseObject argument :a_thing, + ^^^^^^^^^^^^^^^^^^ `description` strings must end with a `.`. GraphQL::STRING_TYPE, null: false, description: 'Behold! A description' end end TYPE - - expect(cop.offenses.size).to eq 1 end it 'does not add an offense when description is correct' do diff --git a/spec/rubocop/cop/graphql/gid_expected_type_spec.rb b/spec/rubocop/cop/graphql/gid_expected_type_spec.rb index 8fd7ae03748..d9a129244d6 100644 --- a/spec/rubocop/cop/graphql/gid_expected_type_spec.rb +++ b/spec/rubocop/cop/graphql/gid_expected_type_spec.rb @@ -6,16 +6,13 @@ require 'rubocop' require_relative '../../../../rubocop/cop/graphql/gid_expected_type' RSpec.describe RuboCop::Cop::Graphql::GIDExpectedType do - include CopHelper - subject(:cop) { described_class.new } it 'adds an offense when there is no expected_type parameter' do - inspect_source(<<~TYPE) + expect_offense(<<~TYPE) GitlabSchema.object_from_id(received_id) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Add an expected_type parameter to #object_from_id calls if possible. TYPE - - expect(cop.offenses.size).to eq 1 end it 'does not add an offense for calls that have an expected_type parameter' do diff --git a/spec/rubocop/cop/graphql/id_type_spec.rb b/spec/rubocop/cop/graphql/id_type_spec.rb index 6135c9fef43..93c01cd7f06 100644 --- a/spec/rubocop/cop/graphql/id_type_spec.rb +++ b/spec/rubocop/cop/graphql/id_type_spec.rb @@ -6,16 +6,13 @@ require 'rubocop' require_relative '../../../../rubocop/cop/graphql/id_type' RSpec.describe RuboCop::Cop::Graphql::IDType do - include CopHelper - subject(:cop) { described_class.new } it 'adds an offense when GraphQL::ID_TYPE is used as a param to #argument' do - inspect_source(<<~TYPE) + expect_offense(<<~TYPE) argument :some_arg, GraphQL::ID_TYPE, some: other, params: do_not_matter + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use GraphQL::ID_TYPE, use a specific GlobalIDType instead TYPE - - expect(cop.offenses.size).to eq 1 end context 'whitelisted arguments' do diff --git a/spec/rubocop/cop/graphql/json_type_spec.rb b/spec/rubocop/cop/graphql/json_type_spec.rb index 6d9f86e44d2..91838c1708e 100644 --- a/spec/rubocop/cop/graphql/json_type_spec.rb +++ b/spec/rubocop/cop/graphql/json_type_spec.rb @@ -5,29 +5,29 @@ require 'rubocop' require_relative '../../../../rubocop/cop/graphql/json_type' RSpec.describe RuboCop::Cop::Graphql::JSONType do - include CopHelper + let(:msg) do + 'Avoid using GraphQL::Types::JSON. See: https://docs.gitlab.com/ee/development/api_graphql_styleguide.html#json' + end subject(:cop) { described_class.new } context 'fields' do it 'adds an offense when GraphQL::Types::JSON is used' do - inspect_source(<<~RUBY.strip) + expect_offense(<<~RUBY) class MyType field :some_field, GraphQL::Types::JSON + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg} end RUBY - - expect(cop.offenses.size).to eq(1) end it 'adds an offense when GraphQL::Types::JSON is used with other keywords' do - inspect_source(<<~RUBY.strip) + expect_offense(<<~RUBY) class MyType field :some_field, GraphQL::Types::JSON, null: true, description: 'My description' + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg} end RUBY - - expect(cop.offenses.size).to eq(1) end it 'does not add an offense for other types' do @@ -41,23 +41,21 @@ RSpec.describe RuboCop::Cop::Graphql::JSONType do context 'arguments' do it 'adds an offense when GraphQL::Types::JSON is used' do - inspect_source(<<~RUBY.strip) + expect_offense(<<~RUBY) class MyType argument :some_arg, GraphQL::Types::JSON + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg} end RUBY - - expect(cop.offenses.size).to eq(1) end it 'adds an offense when GraphQL::Types::JSON is used with other keywords' do - inspect_source(<<~RUBY.strip) + expect_offense(<<~RUBY) class MyType argument :some_arg, GraphQL::Types::JSON, null: true, description: 'My description' + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg} end RUBY - - expect(cop.offenses.size).to eq(1) end it 'does not add an offense for other types' do diff --git a/spec/rubocop/cop/graphql/resolver_type_spec.rb b/spec/rubocop/cop/graphql/resolver_type_spec.rb index 25213e30528..11c0ad284a9 100644 --- a/spec/rubocop/cop/graphql/resolver_type_spec.rb +++ b/spec/rubocop/cop/graphql/resolver_type_spec.rb @@ -6,24 +6,19 @@ require 'rubocop' require_relative '../../../../rubocop/cop/graphql/resolver_type' RSpec.describe RuboCop::Cop::Graphql::ResolverType do - include CopHelper - subject(:cop) { described_class.new } - it 'adds an offense when there is no type annotaion' do - lacks_type = <<-SRC + it 'adds an offense when there is no type annotation' do + expect_offense(<<~SRC) module Resolvers class FooResolver < BaseResolver + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing type annotation: Please add `type` DSL method call. e.g: type UserType.connection_type, null: true def resolve(**args) [:thing] end end end SRC - - inspect_source(lacks_type) - - expect(cop.offenses.size).to eq 1 end it 'does not add an offense for resolvers that have a type call' do @@ -41,9 +36,10 @@ RSpec.describe RuboCop::Cop::Graphql::ResolverType do end it 'ignores type calls on other objects' do - lacks_type = <<-SRC + expect_offense(<<~SRC) module Resolvers class FooResolver < BaseResolver + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Missing type annotation: Please add `type` DSL method call. e.g: type UserType.connection_type, null: true class FalsePositive < BaseObject type RedHerringType, null: true end @@ -54,10 +50,6 @@ RSpec.describe RuboCop::Cop::Graphql::ResolverType do end end SRC - - inspect_source(lacks_type) - - expect(cop.offenses.size).to eq 1 end it 'does not add an offense unless the class is named using the Resolver convention' do diff --git a/spec/rubocop/cop/group_public_or_visible_to_user_spec.rb b/spec/rubocop/cop/group_public_or_visible_to_user_spec.rb index ac6c481a7c3..b3ec426dc07 100644 --- a/spec/rubocop/cop/group_public_or_visible_to_user_spec.rb +++ b/spec/rubocop/cop/group_public_or_visible_to_user_spec.rb @@ -2,29 +2,28 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/group_public_or_visible_to_user' RSpec.describe RuboCop::Cop::GroupPublicOrVisibleToUser do - include CopHelper + let(:msg) do + "`Group.public_or_visible_to_user` should be used with extreme care. " \ + "Please ensure that you are not using it on its own and that the amount of rows being filtered is reasonable." + end subject(:cop) { described_class.new } it 'flags the use of Group.public_or_visible_to_user with a constant receiver' do - inspect_source('Group.public_or_visible_to_user') - - expect(cop.offenses.size).to eq(1) + expect_offense(<<~CODE) + Group.public_or_visible_to_user + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{msg} + CODE end - it 'does not flat the use of public_or_visible_to_user with a constant that is not Group' do - inspect_source('Project.public_or_visible_to_user') - - expect(cop.offenses.size).to eq(0) + it 'does not flag the use of public_or_visible_to_user with a constant that is not Group' do + expect_no_offenses('Project.public_or_visible_to_user') end it 'does not flag the use of Group.public_or_visible_to_user with a send receiver' do - inspect_source('foo.public_or_visible_to_user') - - expect(cop.offenses.size).to eq(0) + expect_no_offenses('foo.public_or_visible_to_user') end end diff --git a/spec/rubocop/cop/include_sidekiq_worker_spec.rb b/spec/rubocop/cop/include_sidekiq_worker_spec.rb index f12652a1a58..bdd622d4894 100644 --- a/spec/rubocop/cop/include_sidekiq_worker_spec.rb +++ b/spec/rubocop/cop/include_sidekiq_worker_spec.rb @@ -3,33 +3,21 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../rubocop/cop/include_sidekiq_worker' RSpec.describe RuboCop::Cop::IncludeSidekiqWorker do - include CopHelper - subject(:cop) { described_class.new } context 'when `Sidekiq::Worker` is included' do - let(:source) { 'include Sidekiq::Worker' } - let(:correct_source) { 'include ApplicationWorker' } - - it 'registers an offense' do - inspect_source(source) - - aggregate_failures do - expect(cop.offenses.size).to eq(1) - expect(cop.offenses.map(&:line)).to eq([1]) - expect(cop.highlights).to eq(['Sidekiq::Worker']) - end - end - - it 'autocorrects to the right version' do - autocorrected = autocorrect_source(source) - - expect(autocorrected).to eq(correct_source) + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(<<~CODE) + include Sidekiq::Worker + ^^^^^^^^^^^^^^^ Include `ApplicationWorker`, not `Sidekiq::Worker`. + CODE + + expect_correction(<<~CODE) + include ApplicationWorker + CODE end end end diff --git a/spec/rubocop/cop/inject_enterprise_edition_module_spec.rb b/spec/rubocop/cop/inject_enterprise_edition_module_spec.rb index 47247006e42..2d293fd0a05 100644 --- a/spec/rubocop/cop/inject_enterprise_edition_module_spec.rb +++ b/spec/rubocop/cop/inject_enterprise_edition_module_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/inject_enterprise_edition_module' RSpec.describe RuboCop::Cop::InjectEnterpriseEditionModule do - include CopHelper - subject(:cop) { described_class.new } it 'flags the use of `prepend_if_ee EE` in the middle of a file' do @@ -185,18 +182,19 @@ RSpec.describe RuboCop::Cop::InjectEnterpriseEditionModule do end it 'autocorrects offenses by just disabling the Cop' do - source = <<~SOURCE - class Foo - prepend_if_ee 'EE::Foo' - include_if_ee 'Bar' - end + expect_offense(<<~SOURCE) + class Foo + prepend_if_ee 'EE::Foo' + ^^^^^^^^^^^^^^^^^^^^^^^ Injecting EE modules must be done on the last line of this file, outside of any class or module definitions + include_if_ee 'Bar' + end SOURCE - expect(autocorrect_source(source)).to eq(<<~SOURCE) - class Foo - prepend_if_ee 'EE::Foo' # rubocop: disable Cop/InjectEnterpriseEditionModule - include_if_ee 'Bar' - end + expect_correction(<<~SOURCE) + class Foo + prepend_if_ee 'EE::Foo' # rubocop: disable Cop/InjectEnterpriseEditionModule + include_if_ee 'Bar' + end SOURCE end diff --git a/spec/rubocop/cop/lint/last_keyword_argument_spec.rb b/spec/rubocop/cop/lint/last_keyword_argument_spec.rb index 826c681a880..aac59f0db4c 100644 --- a/spec/rubocop/cop/lint/last_keyword_argument_spec.rb +++ b/spec/rubocop/cop/lint/last_keyword_argument_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../../rubocop/cop/lint/last_keyword_argument' RSpec.describe RuboCop::Cop::Lint::LastKeywordArgument do - include CopHelper - subject(:cop) { described_class.new } before do diff --git a/spec/rubocop/cop/migration/add_limit_to_text_columns_spec.rb b/spec/rubocop/cop/migration/add_limit_to_text_columns_spec.rb index 97b9d0d1ee2..149fb0a48eb 100644 --- a/spec/rubocop/cop/migration/add_limit_to_text_columns_spec.rb +++ b/spec/rubocop/cop/migration/add_limit_to_text_columns_spec.rb @@ -28,6 +28,15 @@ RSpec.describe RuboCop::Cop::Migration::AddLimitToTextColumns do ^^^^ #{described_class::MSG} end + create_table_with_constraints :test_text_limits_create do |t| + t.integer :test_id, null: false + t.text :title + t.text :description + ^^^^ #{described_class::MSG} + + t.text_limit :title, 100 + end + add_column :test_text_limits, :email, :text ^^^^^^^^^^ #{described_class::MSG} @@ -57,6 +66,15 @@ RSpec.describe RuboCop::Cop::Migration::AddLimitToTextColumns do t.text :name end + create_table_with_constraints :test_text_limits_create do |t| + t.integer :test_id, null: false + t.text :title + t.text :description + + t.text_limit :title, 100 + t.text_limit :description, 255 + end + add_column :test_text_limits, :email, :text add_column_with_default :test_text_limits, :role, :text, default: 'default' change_column_type_concurrently :test_text_limits, :test_id, :text diff --git a/spec/rubocop/cop/performance/ar_count_each_spec.rb b/spec/rubocop/cop/performance/ar_count_each_spec.rb index 6242c7a4c5e..402e3e93147 100644 --- a/spec/rubocop/cop/performance/ar_count_each_spec.rb +++ b/spec/rubocop/cop/performance/ar_count_each_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../../rubocop/cop/performance/ar_count_each.rb' RSpec.describe RuboCop::Cop::Performance::ARCountEach do - include CopHelper - subject(:cop) { described_class.new } context 'when it is not haml file' do @@ -32,8 +30,6 @@ RSpec.describe RuboCop::Cop::Performance::ARCountEach do ^^^^^^^^^^^^ If @users is AR relation, avoid `@users.count ...; @users.each... `, this will trigger two queries. Use `@users.load.size ...; @users.each... ` instead. If @users is an array, try to use @users.size. @users.each { |user| display(user) } SOURCE - - expect(cop.offenses.map(&:cop_name)).to contain_exactly('Performance/ARCountEach') end end diff --git a/spec/rubocop/cop/performance/ar_exists_and_present_blank_spec.rb b/spec/rubocop/cop/performance/ar_exists_and_present_blank_spec.rb index 3321d400ae1..8497ff0e909 100644 --- a/spec/rubocop/cop/performance/ar_exists_and_present_blank_spec.rb +++ b/spec/rubocop/cop/performance/ar_exists_and_present_blank_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../../rubocop/cop/performance/ar_exists_and_present_blank.rb' RSpec.describe RuboCop::Cop::Performance::ARExistsAndPresentBlank do - include CopHelper - subject(:cop) { described_class.new } context 'when it is not haml file' do @@ -32,8 +30,6 @@ RSpec.describe RuboCop::Cop::Performance::ARExistsAndPresentBlank do show @users if @users.present? ^^^^^^^^^^^^^^^ Avoid `@users.present?`, because it will generate database query 'Select TABLE.*' which is expensive. Suggest to use `@users.any?` to replace `@users.present?` SOURCE - - expect(cop.offenses.map(&:cop_name)).to contain_exactly('Performance/ARExistsAndPresentBlank') end end @@ -44,8 +40,6 @@ RSpec.describe RuboCop::Cop::Performance::ARExistsAndPresentBlank do show @users if @users.blank? ^^^^^^^^^^^^^ Avoid `@users.blank?`, because it will generate database query 'Select TABLE.*' which is expensive. Suggest to use `@users.empty?` to replace `@users.blank?` SOURCE - - expect(cop.offenses.map(&:cop_name)).to contain_exactly('Performance/ARExistsAndPresentBlank') end end @@ -58,8 +52,6 @@ RSpec.describe RuboCop::Cop::Performance::ARExistsAndPresentBlank do show @users if @users.present? ^^^^^^^^^^^^^^^ Avoid `@users.present?`, because it will generate database query 'Select TABLE.*' which is expensive. Suggest to use `@users.any?` to replace `@users.present?` SOURCE - - expect(cop.offenses.map(&:cop_name)).to contain_exactly('Performance/ARExistsAndPresentBlank', 'Performance/ARExistsAndPresentBlank') end end diff --git a/spec/rubocop/cop/performance/readlines_each_spec.rb b/spec/rubocop/cop/performance/readlines_each_spec.rb index c19426606f6..5a30107722a 100644 --- a/spec/rubocop/cop/performance/readlines_each_spec.rb +++ b/spec/rubocop/cop/performance/readlines_each_spec.rb @@ -5,19 +5,21 @@ require 'rubocop' require_relative '../../../../rubocop/cop/performance/readlines_each' RSpec.describe RuboCop::Cop::Performance::ReadlinesEach do - include CopHelper - subject(:cop) { described_class.new } let(:message) { 'Avoid `IO.readlines.each`, since it reads contents into memory in full. Use `IO.each_line` or `IO.each` instead.' } shared_examples_for(:class_read) do |klass| context "and it is called as a class method on #{klass}" do - # We can't use `expect_offense` here because indentation changes based on `klass` it 'flags it as an offense' do - inspect_source "#{klass}.readlines(file_path).each { |line| puts line }" + leading_readline = "#{klass}.readlines(file_path)." + padding = " " * leading_readline.length + node = "#{leading_readline}each { |line| puts line }" - expect(cop.offenses.map(&:cop_name)).to contain_exactly('Performance/ReadlinesEach') + expect_offense(<<~CODE, node: node) + %{node} + #{padding}^^^^ Avoid `IO.readlines.each`, since it reads contents into memory in full. [...] + CODE end end @@ -62,9 +64,14 @@ RSpec.describe RuboCop::Cop::Performance::ReadlinesEach do end it 'autocorrects `readlines.each` to `each_line`' do - expect(autocorrect_source('obj.readlines.each { |line| line }')).to( - eq('obj.each_line { |line| line }') - ) + expect_offense(<<~CODE) + obj.readlines.each { |line| line } + ^^^^ Avoid `IO.readlines.each`, since it reads contents into memory in full. [...] + CODE + + expect_correction(<<~CODE) + obj.each_line { |line| line } + CODE end end diff --git a/spec/rubocop/cop/project_path_helper_spec.rb b/spec/rubocop/cop/project_path_helper_spec.rb index 78a590b89f6..16782802a27 100644 --- a/spec/rubocop/cop/project_path_helper_spec.rb +++ b/spec/rubocop/cop/project_path_helper_spec.rb @@ -3,41 +3,30 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../rubocop/cop/project_path_helper' RSpec.describe RuboCop::Cop::ProjectPathHelper do - include CopHelper - subject(:cop) { described_class.new } context "when using namespace_project with the project's namespace" do let(:source) { 'edit_namespace_project_issue_path(@issue.project.namespace, @issue.project, @issue)' } let(:correct_source) { 'edit_project_issue_path(@issue.project, @issue)' } - it 'registers an offense' do - inspect_source(source) - - aggregate_failures do - expect(cop.offenses.size).to eq(1) - expect(cop.offenses.map(&:line)).to eq([1]) - expect(cop.highlights).to eq(['edit_namespace_project_issue_path']) - end - end - - it 'autocorrects to the right version' do - autocorrected = autocorrect_source(source) + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(<<~CODE) + #{source} + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use short project path helpers without explicitly passing the namespace[...] + CODE - expect(autocorrected).to eq(correct_source) + expect_correction(<<~CODE) + #{correct_source} + CODE end end context 'when using namespace_project with a different namespace' do it 'registers no offense' do - inspect_source('edit_namespace_project_issue_path(namespace, project)') - - expect(cop.offenses.size).to eq(0) + expect_no_offenses('edit_namespace_project_issue_path(namespace, project)') end end end diff --git a/spec/rubocop/cop/put_project_routes_under_scope_spec.rb b/spec/rubocop/cop/put_project_routes_under_scope_spec.rb index b0627af0e8b..eb783d22129 100644 --- a/spec/rubocop/cop/put_project_routes_under_scope_spec.rb +++ b/spec/rubocop/cop/put_project_routes_under_scope_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../rubocop/cop/put_project_routes_under_scope' RSpec.describe RuboCop::Cop::PutProjectRoutesUnderScope do - include CopHelper - subject(:cop) { described_class.new } %w[resource resources get post put patch delete].each do |route_method| diff --git a/spec/rubocop/cop/qa/ambiguous_page_object_name_spec.rb b/spec/rubocop/cop/qa/ambiguous_page_object_name_spec.rb index 4876fcd5050..9332ab4186e 100644 --- a/spec/rubocop/cop/qa/ambiguous_page_object_name_spec.rb +++ b/spec/rubocop/cop/qa/ambiguous_page_object_name_spec.rb @@ -1,15 +1,11 @@ # frozen_string_literal: true require 'fast_spec_helper' - require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/qa/ambiguous_page_object_name' RSpec.describe RuboCop::Cop::QA::AmbiguousPageObjectName do - include CopHelper - let(:source_file) { 'qa/page.rb' } subject(:cop) { described_class.new } diff --git a/spec/rubocop/cop/qa/element_with_pattern_spec.rb b/spec/rubocop/cop/qa/element_with_pattern_spec.rb index 6289b1a7c97..28c351ccf1e 100644 --- a/spec/rubocop/cop/qa/element_with_pattern_spec.rb +++ b/spec/rubocop/cop/qa/element_with_pattern_spec.rb @@ -1,15 +1,11 @@ # frozen_string_literal: true require 'fast_spec_helper' - require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/qa/element_with_pattern' RSpec.describe RuboCop::Cop::QA::ElementWithPattern do - include CopHelper - let(:source_file) { 'qa/page.rb' } subject(:cop) { described_class.new } diff --git a/spec/rubocop/cop/rspec/any_instance_of_spec.rb b/spec/rubocop/cop/rspec/any_instance_of_spec.rb index 42bb7d196a1..e7675ded25e 100644 --- a/spec/rubocop/cop/rspec/any_instance_of_spec.rb +++ b/spec/rubocop/cop/rspec/any_instance_of_spec.rb @@ -5,59 +5,51 @@ require 'fast_spec_helper' require_relative '../../../../rubocop/cop/rspec/any_instance_of' RSpec.describe RuboCop::Cop::RSpec::AnyInstanceOf do - include CopHelper - subject(:cop) { described_class.new } context 'when calling allow_any_instance_of' do let(:source) do <<~SRC - allow_any_instance_of(User).to receive(:invalidate_issue_cache_counts) + allow_any_instance_of(User).to receive(:invalidate_issue_cache_counts) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `allow_any_instance_of` [...] SRC end let(:corrected_source) do <<~SRC - allow_next_instance_of(User) do |instance| - allow(instance).to receive(:invalidate_issue_cache_counts) - end + allow_next_instance_of(User) do |instance| + allow(instance).to receive(:invalidate_issue_cache_counts) + end SRC end - it 'registers an offence' do - inspect_source(source) - - expect(cop.offenses.size).to eq(1) - end + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(source) - it 'can autocorrect the source' do - expect(autocorrect_source(source)).to eq(corrected_source) + expect_correction(corrected_source) end end context 'when calling expect_any_instance_of' do let(:source) do <<~SRC - expect_any_instance_of(User).to receive(:invalidate_issue_cache_counts).with(args).and_return(double) + expect_any_instance_of(User).to receive(:invalidate_issue_cache_counts).with(args).and_return(double) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `expect_any_instance_of` [...] SRC end let(:corrected_source) do <<~SRC - expect_next_instance_of(User) do |instance| - expect(instance).to receive(:invalidate_issue_cache_counts).with(args).and_return(double) - end + expect_next_instance_of(User) do |instance| + expect(instance).to receive(:invalidate_issue_cache_counts).with(args).and_return(double) + end SRC end - it 'registers an offence' do - inspect_source(source) - - expect(cop.offenses.size).to eq(1) - end + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(source) - it 'can autocorrect the source' do - expect(autocorrect_source(source)).to eq(corrected_source) + expect_correction(corrected_source) end end end diff --git a/spec/rubocop/cop/rspec/be_success_matcher_spec.rb b/spec/rubocop/cop/rspec/be_success_matcher_spec.rb index d49507c89b1..050f0396fac 100644 --- a/spec/rubocop/cop/rspec/be_success_matcher_spec.rb +++ b/spec/rubocop/cop/rspec/be_success_matcher_spec.rb @@ -5,34 +5,27 @@ require 'rubocop' require_relative '../../../../rubocop/cop/rspec/be_success_matcher' RSpec.describe RuboCop::Cop::RSpec::BeSuccessMatcher do - include CopHelper - let(:source_file) { 'spec/foo_spec.rb' } subject(:cop) { described_class.new } shared_examples 'cop' do |good:, bad:| context "using #{bad} call" do - it 'registers an offense' do - inspect_source(bad, source_file) - - expect(cop.offenses.size).to eq(1) - expect(cop.offenses.map(&:line)).to eq([1]) - expect(cop.highlights).to eq([bad]) - end - - it "autocorrects it to `#{good}`" do - autocorrected = autocorrect_source(bad, source_file) - - expect(autocorrected).to eql(good) + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(<<~CODE, node: bad) + %{node} + ^{node} Do not use deprecated `success?` method, use `successful?` instead. + CODE + + expect_correction(<<~CODE) + #{good} + CODE end end context "using #{good} call" do it 'does not register an offense' do - inspect_source(good) - - expect(cop.offenses).to be_empty + expect_no_offenses(good) end end end diff --git a/spec/rubocop/cop/rspec/env_assignment_spec.rb b/spec/rubocop/cop/rspec/env_assignment_spec.rb index 07afd30fc90..cc132d1532a 100644 --- a/spec/rubocop/cop/rspec/env_assignment_spec.rb +++ b/spec/rubocop/cop/rspec/env_assignment_spec.rb @@ -3,13 +3,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../../rubocop/cop/rspec/env_assignment' RSpec.describe RuboCop::Cop::RSpec::EnvAssignment do - include CopHelper - offense_call_single_quotes_key = %(ENV['FOO'] = 'bar').freeze offense_call_double_quotes_key = %(ENV["FOO"] = 'bar').freeze @@ -17,31 +13,24 @@ RSpec.describe RuboCop::Cop::RSpec::EnvAssignment do subject(:cop) { described_class.new } - shared_examples 'an offensive ENV#[]= call' do |content| - it "registers an offense for `#{content}`" do - inspect_source(content, source_file) - - expect(cop.offenses.size).to eq(1) - expect(cop.offenses.map(&:line)).to eq([1]) - expect(cop.highlights).to eq([content]) - end - end - - shared_examples 'an autocorrected ENV#[]= call' do |content, autocorrected_content| - it "registers an offense for `#{content}` and autocorrects it to `#{autocorrected_content}`" do - autocorrected = autocorrect_source(content, source_file) + shared_examples 'an offensive and correction ENV#[]= call' do |content, autocorrected_content| + it "registers an offense for `#{content}` and corrects", :aggregate_failures do + expect_offense(<<~CODE) + #{content} + ^^^^^^^^^^^^^^^^^^ Don't assign to ENV, use `stub_env` instead. + CODE - expect(autocorrected).to eql(autocorrected_content) + expect_correction(<<~CODE) + #{autocorrected_content} + CODE end end context 'with a key using single quotes' do - it_behaves_like 'an offensive ENV#[]= call', offense_call_single_quotes_key - it_behaves_like 'an autocorrected ENV#[]= call', offense_call_single_quotes_key, %(stub_env('FOO', 'bar')) + it_behaves_like 'an offensive and correction ENV#[]= call', offense_call_single_quotes_key, %(stub_env('FOO', 'bar')) end context 'with a key using double quotes' do - it_behaves_like 'an offensive ENV#[]= call', offense_call_double_quotes_key - it_behaves_like 'an autocorrected ENV#[]= call', offense_call_double_quotes_key, %(stub_env("FOO", 'bar')) + it_behaves_like 'an offensive and correction ENV#[]= call', offense_call_double_quotes_key, %(stub_env("FOO", 'bar')) end end diff --git a/spec/rubocop/cop/rspec/expect_gitlab_tracking_spec.rb b/spec/rubocop/cop/rspec/expect_gitlab_tracking_spec.rb index f7adc1373df..d1ce8d01e0b 100644 --- a/spec/rubocop/cop/rspec/expect_gitlab_tracking_spec.rb +++ b/spec/rubocop/cop/rspec/expect_gitlab_tracking_spec.rb @@ -2,13 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../../rubocop/cop/rspec/expect_gitlab_tracking' RSpec.describe RuboCop::Cop::RSpec::ExpectGitlabTracking do - include CopHelper - let(:source_file) { 'spec/foo_spec.rb' } subject(:cop) { described_class.new } @@ -36,29 +32,18 @@ RSpec.describe RuboCop::Cop::RSpec::ExpectGitlabTracking do good_samples.each do |good| context "good: #{good}" do it 'does not register an offense' do - inspect_source(good) - - expect(cop.offenses).to be_empty + expect_no_offenses(good) end end end bad_samples.each do |bad| context "bad: #{bad}" do - it 'registers an offense', :aggregate_failures do - inspect_source(bad, source_file) - - expect(cop.offenses.size).to eq(1) - expect(cop.offenses.map(&:line)).to eq([1]) - expect(cop.highlights).to eq([bad]) - - msg = cop.offenses.first.message - - expect(msg).to match( - /Do not expect directly on `Gitlab::Tracking#event`/ - ) - expect(msg).to match(/add the `snowplow` annotation/) - expect(msg).to match(/use `expect_snowplow_event` instead/) + it 'registers an offense' do + expect_offense(<<~CODE, node: bad) + %{node} + ^{node} Do not expect directly on `Gitlab::Tracking#event`[...] + CODE end end end diff --git a/spec/rubocop/cop/rspec/factories_in_migration_specs_spec.rb b/spec/rubocop/cop/rspec/factories_in_migration_specs_spec.rb index fe9cea47a43..8beec53375e 100644 --- a/spec/rubocop/cop/rspec/factories_in_migration_specs_spec.rb +++ b/spec/rubocop/cop/rspec/factories_in_migration_specs_spec.rb @@ -3,17 +3,13 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../../rubocop/cop/rspec/factories_in_migration_specs' RSpec.describe RuboCop::Cop::RSpec::FactoriesInMigrationSpecs do - include CopHelper - subject(:cop) { described_class.new } shared_examples 'an offensive factory call' do |namespace| - %i[build build_list create create_list].each do |forbidden_method| + %i[build build_list create create_list attributes_for].each do |forbidden_method| namespaced_forbidden_method = "#{namespace}#{forbidden_method}(:user)" it "registers an offense for #{namespaced_forbidden_method}" do diff --git a/spec/rubocop/cop/rspec/factory_bot/inline_association_spec.rb b/spec/rubocop/cop/rspec/factory_bot/inline_association_spec.rb index 33fdaaee3c7..0e6af71ea3e 100644 --- a/spec/rubocop/cop/rspec/factory_bot/inline_association_spec.rb +++ b/spec/rubocop/cop/rspec/factory_bot/inline_association_spec.rb @@ -7,8 +7,6 @@ require 'rubocop' require_relative '../../../../../rubocop/cop/rspec/factory_bot/inline_association' RSpec.describe RuboCop::Cop::RSpec::FactoryBot::InlineAssociation do - include CopHelper - subject(:cop) { described_class.new } shared_examples 'offense' do |code_snippet, autocorrected| @@ -17,27 +15,31 @@ RSpec.describe RuboCop::Cop::RSpec::FactoryBot::InlineAssociation do let(:offense_marker) { '^' * code_snippet.size } let(:offense_msg) { msg(type) } let(:offense) { "#{offense_marker} #{offense_msg}" } - let(:pristine_source) { source.sub(offense, '') } let(:source) do <<~RUBY - FactoryBot.define do - factory :project do - attribute { #{code_snippet} } - #{offense} - end + FactoryBot.define do + factory :project do + attribute { #{code_snippet} } + #{offense} end + end RUBY end - it 'registers an offense' do - expect_offense(source) + let(:corrected_source) do + <<~RUBY + FactoryBot.define do + factory :project do + attribute { #{autocorrected} } + end + end + RUBY end - it 'autocorrects the source' do - corrected = autocorrect_source(pristine_source) + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(source) - expect(corrected).not_to include(code_snippet) - expect(corrected).to include(autocorrected) + expect_correction(corrected_source) end end diff --git a/spec/rubocop/cop/rspec/have_gitlab_http_status_spec.rb b/spec/rubocop/cop/rspec/have_gitlab_http_status_spec.rb index f6040350dc0..c2d97c8992a 100644 --- a/spec/rubocop/cop/rspec/have_gitlab_http_status_spec.rb +++ b/spec/rubocop/cop/rspec/have_gitlab_http_status_spec.rb @@ -4,50 +4,42 @@ require 'fast_spec_helper' require 'rspec-parameterized' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../../rubocop/cop/rspec/have_gitlab_http_status' RSpec.describe RuboCop::Cop::RSpec::HaveGitlabHttpStatus do - include CopHelper - using RSpec::Parameterized::TableSyntax let(:source_file) { 'spec/foo_spec.rb' } subject(:cop) { described_class.new } - shared_examples 'offense' do |code| - it 'registers an offense' do - inspect_source(code, source_file) + shared_examples 'offense' do |bad, good| + it 'registers an offense', :aggregate_failures do + expect_offense(<<~CODE, node: bad) + %{node} + ^{node} [...] + CODE - expect(cop.offenses.size).to eq(1) - expect(cop.offenses.map(&:line)).to eq([1]) - expect(cop.highlights).to eq([code]) + expect_correction(<<~CODE) + #{good} + CODE end end shared_examples 'no offense' do |code| it 'does not register an offense' do - inspect_source(code) - - expect(cop.offenses).to be_empty - end - end - - shared_examples 'autocorrect' do |bad, good| - it 'autocorrects' do - autocorrected = autocorrect_source(bad, source_file) - - expect(autocorrected).to eql(good) + expect_no_offenses(code) end end - shared_examples 'no autocorrect' do |code| + shared_examples 'offense with no autocorrect' do |code| it 'does not autocorrect' do - autocorrected = autocorrect_source(code, source_file) + expect_offense(<<~CODE, node: code) + %{node} + ^{node} [...] + CODE - expect(autocorrected).to eql(code) + expect_no_corrections end end @@ -64,10 +56,8 @@ RSpec.describe RuboCop::Cop::RSpec::HaveGitlabHttpStatus do end with_them do - include_examples 'offense', params[:bad] + include_examples 'offense', params[:bad], params[:good] include_examples 'no offense', params[:good] - include_examples 'autocorrect', params[:bad], params[:good] - include_examples 'no autocorrect', params[:good] end end @@ -77,10 +67,8 @@ RSpec.describe RuboCop::Cop::RSpec::HaveGitlabHttpStatus do end with_them do - include_examples 'offense', params[:bad] - include_examples 'offense', params[:good] - include_examples 'autocorrect', params[:bad], params[:good] - include_examples 'no autocorrect', params[:good] + include_examples 'offense', params[:bad], params[:good] + include_examples 'offense with no autocorrect', params[:good] end end @@ -114,7 +102,6 @@ RSpec.describe RuboCop::Cop::RSpec::HaveGitlabHttpStatus do with_them do include_examples 'no offense', params[:code] - include_examples 'no autocorrect', params[:code] end end end diff --git a/spec/rubocop/cop/rspec/htt_party_basic_auth_spec.rb b/spec/rubocop/cop/rspec/htt_party_basic_auth_spec.rb index 6e9e436602c..eac6ceb3ddf 100644 --- a/spec/rubocop/cop/rspec/htt_party_basic_auth_spec.rb +++ b/spec/rubocop/cop/rspec/htt_party_basic_auth_spec.rb @@ -5,12 +5,10 @@ require 'fast_spec_helper' require_relative '../../../../rubocop/cop/rspec/httparty_basic_auth' RSpec.describe RuboCop::Cop::RSpec::HTTPartyBasicAuth do - include CopHelper - subject(:cop) { described_class.new } context 'when passing `basic_auth: { user: ... }`' do - it 'registers an offence' do + it 'registers an offense and corrects', :aggregate_failures do expect_offense(<<~SOURCE, 'spec/foo.rb') HTTParty.put( url, @@ -19,17 +17,19 @@ RSpec.describe RuboCop::Cop::RSpec::HTTPartyBasicAuth do body: body ) SOURCE - end - it 'can autocorrect the source' do - bad = 'HTTParty.put(url, basic_auth: { user: user, password: token })' - good = 'HTTParty.put(url, basic_auth: { username: user, password: token })' - expect(autocorrect_source(bad)).to eq(good) + expect_correction(<<~SOURCE) + HTTParty.put( + url, + basic_auth: { username: user, password: token }, + body: body + ) + SOURCE end end context 'when passing `basic_auth: { username: ... }`' do - it 'does not register an offence' do + it 'does not register an offense' do expect_no_offenses(<<~SOURCE, 'spec/frontend/fixtures/foo.rb') HTTParty.put( url, diff --git a/spec/rubocop/cop/rspec/modify_sidekiq_middleware_spec.rb b/spec/rubocop/cop/rspec/modify_sidekiq_middleware_spec.rb index d9e3ca5741c..ffabbae90dc 100644 --- a/spec/rubocop/cop/rspec/modify_sidekiq_middleware_spec.rb +++ b/spec/rubocop/cop/rspec/modify_sidekiq_middleware_spec.rb @@ -5,33 +5,20 @@ require 'rubocop' require_relative '../../../../rubocop/cop/rspec/modify_sidekiq_middleware' RSpec.describe RuboCop::Cop::RSpec::ModifySidekiqMiddleware do - include CopHelper - subject(:cop) { described_class.new } - let(:source) do - <<~SRC - Sidekiq::Testing.server_middleware do |chain| - chain.add(MyCustomMiddleware) - end - SRC - end - - let(:corrected) do - <<~SRC - with_sidekiq_server_middleware do |chain| - chain.add(MyCustomMiddleware) - end - SRC - end - - it 'registers an offence' do - inspect_source(source) - - expect(cop.offenses.size).to eq(1) - end - - it 'can autocorrect the source' do - expect(autocorrect_source(source)).to eq(corrected) + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(<<~CODE) + Sidekiq::Testing.server_middleware do |chain| + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't modify global sidekiq middleware, [...] + chain.add(MyCustomMiddleware) + end + CODE + + expect_correction(<<~CODE) + with_sidekiq_server_middleware do |chain| + chain.add(MyCustomMiddleware) + end + CODE end end diff --git a/spec/rubocop/cop/rspec/timecop_freeze_spec.rb b/spec/rubocop/cop/rspec/timecop_freeze_spec.rb index b1cf82492e4..939623f8299 100644 --- a/spec/rubocop/cop/rspec/timecop_freeze_spec.rb +++ b/spec/rubocop/cop/rspec/timecop_freeze_spec.rb @@ -3,50 +3,29 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../../rubocop/cop/rspec/timecop_freeze' RSpec.describe RuboCop::Cop::RSpec::TimecopFreeze do - include CopHelper - subject(:cop) { described_class.new } context 'when calling Timecop.freeze' do - let(:source) do - <<~SRC - Timecop.freeze(Time.current) { example.run } - SRC - end - - let(:corrected_source) do - <<~SRC - freeze_time(Time.current) { example.run } - SRC - end - - it 'registers an offence' do - inspect_source(source) - - expect(cop.offenses.size).to eq(1) - end - - it 'can autocorrect the source' do - expect(autocorrect_source(source)).to eq(corrected_source) + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(<<~CODE) + Timecop.freeze(Time.current) { example.run } + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `Timecop.freeze`, use `freeze_time` instead. [...] + CODE + + expect_correction(<<~CODE) + freeze_time(Time.current) { example.run } + CODE end end context 'when calling a different method on Timecop' do - let(:source) do - <<~SRC - Timecop.travel(Time.current) - SRC - end - - it 'does not register an offence' do - inspect_source(source) - - expect(cop.offenses).to be_empty + it 'does not register an offense' do + expect_no_offenses(<<~CODE) + Timecop.travel(Time.current) + CODE end end end diff --git a/spec/rubocop/cop/rspec/timecop_travel_spec.rb b/spec/rubocop/cop/rspec/timecop_travel_spec.rb index 2ee8bfe9ad7..476e45e69a6 100644 --- a/spec/rubocop/cop/rspec/timecop_travel_spec.rb +++ b/spec/rubocop/cop/rspec/timecop_travel_spec.rb @@ -3,50 +3,29 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' - require_relative '../../../../rubocop/cop/rspec/timecop_travel' RSpec.describe RuboCop::Cop::RSpec::TimecopTravel do - include CopHelper - subject(:cop) { described_class.new } context 'when calling Timecop.travel' do - let(:source) do - <<~SRC - Timecop.travel(1.day.ago) { create(:issue) } - SRC - end - - let(:corrected_source) do - <<~SRC - travel_to(1.day.ago) { create(:issue) } - SRC - end - - it 'registers an offence' do - inspect_source(source) - - expect(cop.offenses.size).to eq(1) - end - - it 'can autocorrect the source' do - expect(autocorrect_source(source)).to eq(corrected_source) + it 'registers an offense and corrects', :aggregate_failures do + expect_offense(<<~CODE) + Timecop.travel(1.day.ago) { create(:issue) } + ^^^^^^^^^^^^^^^^^^^^^^^^^ Do not use `Timecop.travel`, use `travel_to` instead. [...] + CODE + + expect_correction(<<~CODE) + travel_to(1.day.ago) { create(:issue) } + CODE end end context 'when calling a different method on Timecop' do - let(:source) do - <<~SRC - Timecop.freeze { create(:issue) } - SRC - end - - it 'does not register an offence' do - inspect_source(source) - - expect(cop.offenses).to be_empty + it 'does not register an offense' do + expect_no_offenses(<<~CODE) + Timecop.freeze { create(:issue) } + CODE end end end diff --git a/spec/rubocop/cop/rspec/top_level_describe_path_spec.rb b/spec/rubocop/cop/rspec/top_level_describe_path_spec.rb index 4936936836d..23531cd0201 100644 --- a/spec/rubocop/cop/rspec/top_level_describe_path_spec.rb +++ b/spec/rubocop/cop/rspec/top_level_describe_path_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../../rubocop/cop/rspec/top_level_describe_path' RSpec.describe RuboCop::Cop::RSpec::TopLevelDescribePath do - include CopHelper - subject(:cop) { described_class.new } context 'when the file ends in _spec.rb' do diff --git a/spec/rubocop/cop/ruby_interpolation_in_translation_spec.rb b/spec/rubocop/cop/ruby_interpolation_in_translation_spec.rb index a6a44b3fa68..cacf0a1b67d 100644 --- a/spec/rubocop/cop/ruby_interpolation_in_translation_spec.rb +++ b/spec/rubocop/cop/ruby_interpolation_in_translation_spec.rb @@ -1,68 +1,51 @@ # frozen_string_literal: true require 'fast_spec_helper' - require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/ruby_interpolation_in_translation' # Disabling interpolation check as we deliberately want to have #{} in strings. # rubocop:disable Lint/InterpolationCheck RSpec.describe RuboCop::Cop::RubyInterpolationInTranslation do - subject(:cop) { described_class.new } + let(:msg) { "Don't use ruby interpolation \#{} inside translated strings, instead use %{}" } - it 'does not add an offence for a regular messages' do - inspect_source('_("Hello world")') + subject(:cop) { described_class.new } - expect(cop.offenses).to be_empty + it 'does not add an offense for a regular messages' do + expect_no_offenses('_("Hello world")') end - it 'adds the correct offence when using interpolation in a string' do - inspect_source('_("Hello #{world}")') - - offense = cop.offenses.first - - expect(offense.location.source).to eq('#{world}') - expect(offense.message).to eq('Don\'t use ruby interpolation #{} inside translated strings, instead use %{}') + it 'adds the correct offense when using interpolation in a string' do + expect_offense(<<~CODE) + _("Hello \#{world}") + ^^^^^ #{msg} + ^^^^^^^^ #{msg} + CODE end it 'detects when using a ruby interpolation in the first argument of a pluralized string' do - inspect_source('n_("Hello #{world}", "Hello world")') - - expect(cop.offenses).not_to be_empty + expect_offense(<<~CODE) + n_("Hello \#{world}", "Hello world") + ^^^^^ #{msg} + ^^^^^^^^ #{msg} + CODE end it 'detects when using a ruby interpolation in the second argument of a pluralized string' do - inspect_source('n_("Hello world", "Hello #{world}")') - - expect(cop.offenses).not_to be_empty + expect_offense(<<~CODE) + n_("Hello world", "Hello \#{world}") + ^^^^^ #{msg} + ^^^^^^^^ #{msg} + CODE end it 'detects when using interpolation in a namespaced translation' do - inspect_source('s_("Hello|#{world}")') - - expect(cop.offenses).not_to be_empty - end - - it 'does not add an offence for messages defined over multiple lines' do - source = <<~SRC - _("Hello "\ - "world ") - SRC - - inspect_source(source) - expect(cop.offenses).to be_empty - end - - it 'adds an offence for violations in a message defined over multiple lines' do - source = <<~SRC - _("Hello "\ - "\#{world} ") - SRC - - inspect_source(source) - expect(cop.offenses).not_to be_empty + expect_offense(<<~CODE) + s_("Hello|\#{world}") + ^^^^^ #{msg} + ^^^^^^^^ #{msg} + CODE end end # rubocop:enable Lint/InterpolationCheck diff --git a/spec/rubocop/cop/safe_params_spec.rb b/spec/rubocop/cop/safe_params_spec.rb index c8f6768c4bb..62f8e542d86 100644 --- a/spec/rubocop/cop/safe_params_spec.rb +++ b/spec/rubocop/cop/safe_params_spec.rb @@ -2,12 +2,9 @@ require 'fast_spec_helper' require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../rubocop/cop/safe_params' RSpec.describe RuboCop::Cop::SafeParams do - include CopHelper - subject(:cop) { described_class.new } it 'flags the params as an argument of url_for' do diff --git a/spec/rubocop/cop/scalability/bulk_perform_with_context_spec.rb b/spec/rubocop/cop/scalability/bulk_perform_with_context_spec.rb index 6e526f7ad8f..a19ddf9dbe6 100644 --- a/spec/rubocop/cop/scalability/bulk_perform_with_context_spec.rb +++ b/spec/rubocop/cop/scalability/bulk_perform_with_context_spec.rb @@ -5,54 +5,44 @@ require 'rubocop' require_relative '../../../../rubocop/cop/scalability/bulk_perform_with_context' RSpec.describe RuboCop::Cop::Scalability::BulkPerformWithContext do - include CopHelper - subject(:cop) { described_class.new } it "adds an offense when calling bulk_perform_async" do - inspect_source(<<~CODE) + expect_offense(<<~CODE) Worker.bulk_perform_async(args) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer using `Worker.bulk_perform_async_with_contexts` [...] CODE - - expect(cop.offenses.size).to eq(1) end it "adds an offense when calling bulk_perform_in" do - inspect_source(<<~CODE) + expect_offense(<<~CODE) diffs.each_batch(of: BATCH_SIZE) do |relation, index| ids = relation.pluck_primary_key.map { |id| [id] } DeleteDiffFilesWorker.bulk_perform_in(index * 5.minutes, ids) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer using `Worker.bulk_perform_async_with_contexts` [...] end CODE - - expect(cop.offenses.size).to eq(1) end it "does not add an offense for migrations" do allow(cop).to receive(:in_migration?).and_return(true) - inspect_source(<<~CODE) + expect_no_offenses(<<~CODE) Worker.bulk_perform_in(args) CODE - - expect(cop.offenses.size).to eq(0) end it "does not add an offence for specs" do allow(cop).to receive(:in_spec?).and_return(true) - inspect_source(<<~CODE) + expect_no_offenses(<<~CODE) Worker.bulk_perform_in(args) CODE - - expect(cop.offenses.size).to eq(0) end it "does not add an offense for scheduling BackgroundMigrations" do - inspect_source(<<~CODE) + expect_no_offenses(<<~CODE) BackgroundMigrationWorker.bulk_perform_in(args) CODE - - expect(cop.offenses.size).to eq(0) end end diff --git a/spec/rubocop/cop/scalability/cron_worker_context_spec.rb b/spec/rubocop/cop/scalability/cron_worker_context_spec.rb index 4699e06e9cf..11b2b82d2f5 100644 --- a/spec/rubocop/cop/scalability/cron_worker_context_spec.rb +++ b/spec/rubocop/cop/scalability/cron_worker_context_spec.rb @@ -5,18 +5,15 @@ require 'rubocop' require_relative '../../../../rubocop/cop/scalability/cron_worker_context' RSpec.describe RuboCop::Cop::Scalability::CronWorkerContext do - include CopHelper - subject(:cop) { described_class.new } it 'adds an offense when including CronjobQueue' do - inspect_source(<<~CODE) + expect_offense(<<~CODE) class SomeWorker include CronjobQueue + ^^^^^^^^^^^^ Manually define an ApplicationContext for cronjob-workers.[...] end CODE - - expect(cop.offenses.size).to eq(1) end it 'does not add offenses for other workers' do diff --git a/spec/rubocop/cop/scalability/file_uploads_spec.rb b/spec/rubocop/cop/scalability/file_uploads_spec.rb index 78ff7fea55c..bda5c056b03 100644 --- a/spec/rubocop/cop/scalability/file_uploads_spec.rb +++ b/spec/rubocop/cop/scalability/file_uploads_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../../rubocop/cop/scalability/file_uploads' RSpec.describe RuboCop::Cop::Scalability::FileUploads do - include CopHelper - subject(:cop) { described_class.new } let(:message) { 'Do not upload files without workhorse acceleration. Please refer to https://docs.gitlab.com/ee/development/uploads.html' } diff --git a/spec/rubocop/cop/scalability/idempotent_worker_spec.rb b/spec/rubocop/cop/scalability/idempotent_worker_spec.rb index 666122a9de4..729f2613697 100644 --- a/spec/rubocop/cop/scalability/idempotent_worker_spec.rb +++ b/spec/rubocop/cop/scalability/idempotent_worker_spec.rb @@ -5,8 +5,6 @@ require 'rubocop' require_relative '../../../../rubocop/cop/scalability/idempotent_worker' RSpec.describe RuboCop::Cop::Scalability::IdempotentWorker do - include CopHelper - subject(:cop) { described_class.new } before do @@ -16,21 +14,18 @@ RSpec.describe RuboCop::Cop::Scalability::IdempotentWorker do end it 'adds an offense when not defining idempotent method' do - inspect_source(<<~CODE) + expect_offense(<<~CODE) class SomeWorker + ^^^^^^^^^^^^^^^^ Avoid adding not idempotent workers.[...] end CODE - - expect(cop.offenses.size).to eq(1) end it 'adds an offense when not defining idempotent method' do - inspect_source(<<~CODE) + expect_no_offenses(<<~CODE) class SomeWorker idempotent! end CODE - - expect(cop.offenses.size).to be_zero end end diff --git a/spec/rubocop/cop/static_translation_definition_spec.rb b/spec/rubocop/cop/static_translation_definition_spec.rb index 8a38a318999..8656b07a6e4 100644 --- a/spec/rubocop/cop/static_translation_definition_spec.rb +++ b/spec/rubocop/cop/static_translation_definition_spec.rb @@ -8,78 +8,76 @@ require 'rspec-parameterized' require_relative '../../../rubocop/cop/static_translation_definition' RSpec.describe RuboCop::Cop::StaticTranslationDefinition do - include CopHelper - using RSpec::Parameterized::TableSyntax + let(:msg) do + "The text you're translating will be already in the translated form when it's assigned to the constant. " \ + "When a users changes the locale, these texts won't be translated again. " \ + "Consider moving the translation logic to a method." + end + subject(:cop) { described_class.new } - shared_examples 'offense' do |code, highlight, line| + shared_examples 'offense' do |code| it 'registers an offense' do - inspect_source(code) - - expect(cop.offenses.size).to eq(1) - expect(cop.offenses.map(&:line)).to eq([line]) - expect(cop.highlights).to eq([highlight]) + expect_offense(code) end end shared_examples 'no offense' do |code| it 'does not register an offense' do - inspect_source(code) - - expect(cop.offenses).to be_empty + expect_no_offenses(code) end end describe 'offenses' do - where(:code, :highlight, :line) do + where(:code) do [ - ['A = _("a")', '_("a")', 1], - ['B = s_("b")', 's_("b")', 1], - ['C = n_("c")', 'n_("c")', 1], - [ - <<~CODE, - class MyClass - def self.translations - @cache ||= { hello: _("hello") } - end + <<~CODE, + A = _("a") + ^^^^^^ #{msg} + CODE + <<~CODE, + B = s_("b") + ^^^^^^^ #{msg} + CODE + <<~CODE, + C = n_("c") + ^^^^^^^ #{msg} + CODE + <<~CODE, + class MyClass + def self.translations + @cache ||= { hello: _("hello") } + ^^^^^^^^^^ #{msg} end - CODE - '_("hello")', - 3 - ], - [ - <<~CODE, - module MyModule - A = { - b: { - c: _("a") - } + end + CODE + <<~CODE, + module MyModule + A = { + b: { + c: _("a") + ^^^^^^ #{msg} } - end - CODE - '_("a")', - 4 - ], - [ - <<~CODE, - class MyClass - B = [ - [ - s_("a") - ] + } + end + CODE + <<~CODE + class MyClass + B = [ + [ + s_("a") + ^^^^^^^ #{msg} ] - end - CODE - 's_("a")', - 4 - ] + ] + end + CODE ] end with_them do - include_examples 'offense', params[:code], params[:highlight], params[:line] + include_examples 'offense', params[:code] end end diff --git a/spec/rubocop/cop/usage_data/distinct_count_by_large_foreign_key_spec.rb b/spec/rubocop/cop/usage_data/distinct_count_by_large_foreign_key_spec.rb index 1c90df798a5..b6711effe9e 100644 --- a/spec/rubocop/cop/usage_data/distinct_count_by_large_foreign_key_spec.rb +++ b/spec/rubocop/cop/usage_data/distinct_count_by_large_foreign_key_spec.rb @@ -1,17 +1,13 @@ # frozen_string_literal: true require 'fast_spec_helper' - require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/usage_data/distinct_count_by_large_foreign_key' RSpec.describe RuboCop::Cop::UsageData::DistinctCountByLargeForeignKey do - include CopHelper - let(:allowed_foreign_keys) { [:author_id, :user_id, :'merge_requests.target_project_id'] } - + let(:msg) { 'Avoid doing `distinct_count` on foreign keys for large tables having above 100 million rows.' } let(:config) do RuboCop::Config.new('UsageData/DistinctCountByLargeForeignKey' => { 'AllowedForeignKeys' => allowed_foreign_keys @@ -21,36 +17,32 @@ RSpec.describe RuboCop::Cop::UsageData::DistinctCountByLargeForeignKey do subject(:cop) { described_class.new(config) } context 'when counting by disallowed key' do - it 'registers an offence' do - inspect_source('distinct_count(Issue, :creator_id)') - - expect(cop.offenses.size).to eq(1) + it 'registers an offense' do + expect_offense(<<~CODE) + distinct_count(Issue, :creator_id) + ^^^^^^^^^^^^^^ #{msg} + CODE end - it 'does not register an offence when batch is false' do - inspect_source('distinct_count(Issue, :creator_id, batch: false)') - - expect(cop.offenses).to be_empty + it 'does not register an offense when batch is false' do + expect_no_offenses('distinct_count(Issue, :creator_id, batch: false)') end - it 'register an offence when batch is true' do - inspect_source('distinct_count(Issue, :creator_id, batch: true)') - - expect(cop.offenses.size).to eq(1) + it 'registers an offense when batch is true' do + expect_offense(<<~CODE) + distinct_count(Issue, :creator_id, batch: true) + ^^^^^^^^^^^^^^ #{msg} + CODE end end context 'when calling by allowed key' do - it 'does not register an offence with symbol' do - inspect_source('distinct_count(Issue, :author_id)') - - expect(cop.offenses).to be_empty + it 'does not register an offense with symbol' do + expect_no_offenses('distinct_count(Issue, :author_id)') end - it 'does not register an offence with string' do - inspect_source("distinct_count(Issue, 'merge_requests.target_project_id')") - - expect(cop.offenses).to be_empty + it 'does not register an offense with string' do + expect_no_offenses("distinct_count(Issue, 'merge_requests.target_project_id')") end end end diff --git a/spec/rubocop/cop/usage_data/large_table_spec.rb b/spec/rubocop/cop/usage_data/large_table_spec.rb index 638e8c67dc8..26bd4e61625 100644 --- a/spec/rubocop/cop/usage_data/large_table_spec.rb +++ b/spec/rubocop/cop/usage_data/large_table_spec.rb @@ -1,18 +1,15 @@ # frozen_string_literal: true require 'fast_spec_helper' - require 'rubocop' -require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/usage_data/large_table' RSpec.describe RuboCop::Cop::UsageData::LargeTable do - include CopHelper - let(:large_tables) { %i[Rails Time] } let(:count_methods) { %i[count distinct_count] } let(:allowed_methods) { %i[minimum maximum] } + let(:msg) { 'Use one of the count, distinct_count methods for counting on' } let(:config) do RuboCop::Config.new('UsageData/LargeTable' => { @@ -31,59 +28,54 @@ RSpec.describe RuboCop::Cop::UsageData::LargeTable do context 'with large tables' do context 'when calling Issue.count' do - it 'register an offence' do - inspect_source('Issue.count') - - expect(cop.offenses.size).to eq(1) + it 'registers an offense' do + expect_offense(<<~CODE) + Issue.count + ^^^^^^^^^^^ #{msg} Issue + CODE end end context 'when calling Issue.active.count' do - it 'register an offence' do - inspect_source('Issue.active.count') - - expect(cop.offenses.size).to eq(1) + it 'registers an offense' do + expect_offense(<<~CODE) + Issue.active.count + ^^^^^^^^^^^^ #{msg} Issue + CODE end end context 'when calling count(Issue)' do - it 'does not register an offence' do - inspect_source('count(Issue)') - - expect(cop.offenses).to be_empty + it 'does not register an offense' do + expect_no_offenses('count(Issue)') end end context 'when calling count(Ci::Build.active)' do - it 'does not register an offence' do - inspect_source('count(Ci::Build.active)') - - expect(cop.offenses).to be_empty + it 'does not register an offense' do + expect_no_offenses('count(Ci::Build.active)') end end context 'when calling Ci::Build.active.count' do - it 'register an offence' do - inspect_source('Ci::Build.active.count') - - expect(cop.offenses.size).to eq(1) + it 'registers an offense' do + expect_offense(<<~CODE) + Ci::Build.active.count + ^^^^^^^^^^^^^^^^ #{msg} Ci::Build + CODE end end context 'when using allowed methods' do - it 'does not register an offence' do - inspect_source('Issue.minimum') - - expect(cop.offenses).to be_empty + it 'does not register an offense' do + expect_no_offenses('Issue.minimum') end end end context 'with non related class' do - it 'does not register an offence' do - inspect_source('Rails.count') - - expect(cop.offenses).to be_empty + it 'does not register an offense' do + expect_no_offenses('Rails.count') end end end |