diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2022-11-23 15:07:42 +0000 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2022-11-23 15:07:42 +0000 |
commit | bc0f141f2f073a971aad1eb5349bb718747df028 (patch) | |
tree | 72fcc48dfac8e3f3560e22014eacdd2eaae8bc89 /spec | |
parent | 2c29837ce1692790dedccbc9b36b44dc8aaacbee (diff) | |
download | gitlab-ce-bc0f141f2f073a971aad1eb5349bb718747df028.tar.gz |
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'spec')
90 files changed, 708 insertions, 294 deletions
diff --git a/spec/contracts/provider/helpers/contract_source_helper.rb b/spec/contracts/provider/helpers/contract_source_helper.rb new file mode 100644 index 00000000000..02591f41b07 --- /dev/null +++ b/spec/contracts/provider/helpers/contract_source_helper.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true +require_relative "contract_sources" + +module Provider + module ContractSourceHelper + def self.contract_location(provider, requester) + provider_name = Provider::ContractSources::CONTRACT_SOURCES[provider] + + if ENV["PACT_BROKER"] + provider_name[:broker] + else + paths = Provider::ContractSources::RELATIVE_PATHS + prefix_path = requester == :rake ? File.expand_path(paths[requester], __dir__) : paths[requester] + "#{prefix_path}#{provider_name[:local]}" + end + end + end +end diff --git a/spec/contracts/provider/helpers/contract_sources.rb b/spec/contracts/provider/helpers/contract_sources.rb new file mode 100644 index 00000000000..6680ea7665c --- /dev/null +++ b/spec/contracts/provider/helpers/contract_sources.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +module Provider + module ContractSources + PACT_BROKER_HOST = "http://localhost:9292/pacts/provider" + + RELATIVE_PATHS = { + rake: "../../../contracts/contracts/project", + spec: "../contracts/project" + }.freeze + + CONTRACT_SOURCES = { + # MergeRequest#show + GET_DIFFS_BATCH: { + broker: "#{PACT_BROKER_HOST}/Merge%20Request%20Diffs%20Batch%20Endpoint/consumer/MergeRequest%23show/latest", + local: "/merge_request/show/mergerequest#show-merge_request_diffs_batch_endpoint.json" + }, + GET_DIFFS_METADATA: { + broker: "#{PACT_BROKER_HOST}/Merge%20Request%20Diffs%20Metadata%20Endpoint/consumer/MergeRequest%23show/latest", + local: "/merge_request/show/mergerequest#show-merge_request_diffs_metadata_endpoint.json" + }, + GET_DISCUSSIONS: { + broker: "#{PACT_BROKER_HOST}/Merge%20Request%20Discussions%20Endpoint/consumer/MergeRequest%23show/latest", + local: "/merge_request/show/mergerequest#show-merge_request_discussions_endpoint.json" + }, + # Pipeline#index + CREATE_A_NEW_PIPELINE: { + broker: "#{PACT_BROKER_HOST}/POST%20Create%20a%20new%20pipeline/consumer/Pipelines%23new/latest", + local: "/pipeline/new/pipelines#new-post_create_a_new_pipeline.json" + }, + GET_LIST_PROJECT_PIPELINE: { + broker: "#{PACT_BROKER_HOST}/GET%20List%20project%20pipelines/consumer/Pipelines%23index/latest", + local: "/pipeline/index/pipelines#index-get_list_project_pipelines.json" + }, + # Pipelines#show + DELETE_PIPELINE: { + broker: "#{PACT_BROKER_HOST}/DELETE%20pipeline/consumer/Pipelines%23show/latest", + local: "/pipeline/show/pipelines#show-delete_pipeline.json" + }, + GET_PIPELINE_HEADER_DATA: { + broker: "#{PACT_BROKER_HOST}/GET%20pipeline%20header%20data/consumer/Pipelines%23show/latest", + local: "/pipeline/show/pipelines#show-get_pipeline_header_data.json" + }, + # PipelineSchedule#edit + UPDATE_PIPELINE_SCHEDULE: { + broker: "#{PACT_BROKER_HOST}/PUT%20Edit%20a%20pipeline%20schedule/consumer/PipelineSchedules%23edit/latest", + local: "/pipeline_schedule/edit/pipelineschedules#edit-put_edit_a_pipeline_schedule.json" + } + }.freeze + end +end diff --git a/spec/contracts/provider/helpers/publish_contract_helper.rb b/spec/contracts/provider/helpers/publish_contract_helper.rb index 102a73d87ee..feb8a2af23c 100644 --- a/spec/contracts/provider/helpers/publish_contract_helper.rb +++ b/spec/contracts/provider/helpers/publish_contract_helper.rb @@ -2,12 +2,12 @@ module Provider module PublishContractHelper - PROVIDER_VERSION = ENV['GIT_COMMIT'] || `git rev-parse --verify HEAD`.strip - PROVIDER_BRANCH = ENV['GIT_BRANCH'] || `git name-rev --name-only HEAD`.strip + PROVIDER_VERSION = ENV["GIT_COMMIT"] || `git rev-parse --verify HEAD`.strip + PROVIDER_BRANCH = ENV["GIT_BRANCH"] || `git name-rev --name-only HEAD`.strip PUBLISH_FLAG = true - def self.publish_contract_setup - @setup ||= -> { + def publish_contract_setup + -> { app_version PROVIDER_VERSION app_version_branch PROVIDER_BRANCH publish_verification_results PUBLISH_FLAG diff --git a/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_batch_helper.rb b/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_batch_helper.rb index 71f302f2c44..ed1cacc1315 100644 --- a/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_batch_helper.rb +++ b/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_batch_helper.rb @@ -1,18 +1,24 @@ # frozen_string_literal: true -require_relative '../../../../spec_helper' -require_relative '../../../../states/project/merge_request/show_state' +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/merge_request/show_state" module Provider module DiffsBatchHelper Pact.service_provider "Merge Request Diffs Batch Endpoint" do app { Environments::Test.app } - honours_pact_with 'MergeRequest#show' do - pact_uri '../contracts/project/merge_request/show/mergerequest#show-merge_request_diffs_batch_endpoint.json' + honours_pact_with "MergeRequest#show" do + pact_uri Provider::ContractSourceHelper.contract_location(:GET_DIFFS_BATCH, :spec) end - Provider::PublishContractHelper.publish_contract_setup.call + Provider::PublishContractHelper.publish_contract_setup.call( + method(:app_version), + method(:app_version_branch), + method(:publish_verification_results) + ) end end end diff --git a/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_metadata_helper.rb b/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_metadata_helper.rb index 60a3abea5ae..e282cf4be79 100644 --- a/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_metadata_helper.rb +++ b/spec/contracts/provider/pact_helpers/project/merge_request/show/diffs_metadata_helper.rb @@ -1,20 +1,24 @@ # frozen_string_literal: true -require_relative '../../../../spec_helper' -require_relative '../../../../states/project/merge_request/show_state' +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/merge_request/show_state" module Provider module DiffsMetadataHelper Pact.service_provider "Merge Request Diffs Metadata Endpoint" do app { Environments::Test.app } - honours_pact_with 'MergeRequest#show' do - pact_uri '../contracts/project/merge_request/show/mergerequest#show-merge_request_diffs_metadata_endpoint.json' + honours_pact_with "MergeRequest#show" do + pact_uri Provider::ContractSourceHelper.contract_location(:GET_DIFFS_METADATA, :spec) end - app_version Provider::PublishContractHelper::PROVIDER_VERSION - app_version_branch Provider::PublishContractHelper::PROVIDER_BRANCH - publish_verification_results Provider::PublishContractHelper::PUBLISH_FLAG + Provider::PublishContractHelper.publish_contract_setup.call( + method(:app_version), + method(:app_version_branch), + method(:publish_verification_results) + ) end end end diff --git a/spec/contracts/provider/pact_helpers/project/merge_request/show/discussions_helper.rb b/spec/contracts/provider/pact_helpers/project/merge_request/show/discussions_helper.rb index b9308af0a1a..e3ccbe859d4 100644 --- a/spec/contracts/provider/pact_helpers/project/merge_request/show/discussions_helper.rb +++ b/spec/contracts/provider/pact_helpers/project/merge_request/show/discussions_helper.rb @@ -1,20 +1,24 @@ # frozen_string_literal: true -require_relative '../../../../spec_helper' -require_relative '../../../../states/project/merge_request/show_state' +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/merge_request/show_state" module Provider module DiscussionsHelper Pact.service_provider "Merge Request Discussions Endpoint" do app { Environments::Test.app } - honours_pact_with 'MergeRequest#show' do - pact_uri '../contracts/project/merge_request/show/mergerequest#show-merge_request_discussions_endpoint.json' + honours_pact_with "MergeRequest#show" do + pact_uri Provider::ContractSourceHelper.contract_location(:GET_DISCUSSIONS, :spec) end - app_version Provider::PublishContractHelper::PROVIDER_VERSION - app_version_branch Provider::PublishContractHelper::PROVIDER_BRANCH - publish_verification_results Provider::PublishContractHelper::PUBLISH_FLAG + Provider::PublishContractHelper.publish_contract_setup.call( + method(:app_version), + method(:app_version_branch), + method(:publish_verification_results) + ) end end end diff --git a/spec/contracts/provider/pact_helpers/project/pipeline/index/create_a_new_pipeline_helper.rb b/spec/contracts/provider/pact_helpers/project/pipeline/index/create_a_new_pipeline_helper.rb index 2af960bc9fd..31cd5d3d505 100644 --- a/spec/contracts/provider/pact_helpers/project/pipeline/index/create_a_new_pipeline_helper.rb +++ b/spec/contracts/provider/pact_helpers/project/pipeline/index/create_a_new_pipeline_helper.rb @@ -1,20 +1,24 @@ # frozen_string_literal: true -require_relative '../../../../spec_helper' -require_relative '../../../../states/project/pipeline/new_state' +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/pipeline/new_state" module Provider module CreateNewPipelineHelper Pact.service_provider "POST Create a new pipeline" do app { Environments::Test.app } - honours_pact_with 'Pipelines#new' do - pact_uri '../contracts/project/pipeline/new/pipelines#new-post_create_a_new_pipeline.json' + honours_pact_with "Pipelines#new" do + pact_uri Provider::ContractSourceHelper.contract_location(:CREATE_A_NEW_PIPELINE, :spec) end - app_version Provider::PublishContractHelper::PROVIDER_VERSION - app_version_branch Provider::PublishContractHelper::PROVIDER_BRANCH - publish_verification_results Provider::PublishContractHelper::PUBLISH_FLAG + Provider::PublishContractHelper.publish_contract_setup.call( + method(:app_version), + method(:app_version_branch), + method(:publish_verification_results) + ) end end end diff --git a/spec/contracts/provider/pact_helpers/project/pipeline/index/get_list_project_pipelines_helper.rb b/spec/contracts/provider/pact_helpers/project/pipeline/index/get_list_project_pipelines_helper.rb index 37cddd1b80e..90951142a2a 100644 --- a/spec/contracts/provider/pact_helpers/project/pipeline/index/get_list_project_pipelines_helper.rb +++ b/spec/contracts/provider/pact_helpers/project/pipeline/index/get_list_project_pipelines_helper.rb @@ -1,20 +1,24 @@ # frozen_string_literal: true -require_relative '../../../../spec_helper' -require_relative '../../../../states/project/pipeline/index_state' +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/pipeline/index_state" module Provider module GetListProjectPipelinesHelper Pact.service_provider "GET List project pipelines" do app { Environments::Test.app } - honours_pact_with 'Pipelines#index' do - pact_uri '../contracts/project/project/pipeline/index/pipelines#index-get_list_project_pipelines.json' + honours_pact_with "Pipelines#index" do + pact_uri Provider::ContractSourceHelper.contract_location(:GET_LIST_PROJECT_PIPELINE, :spec) end - app_version Provider::PublishContractHelper::PROVIDER_VERSION - app_version_branch Provider::PublishContractHelper::PROVIDER_BRANCH - publish_verification_results Provider::PublishContractHelper::PUBLISH_FLAG + Provider::PublishContractHelper.publish_contract_setup.call( + method(:app_version), + method(:app_version_branch), + method(:publish_verification_results) + ) end end end diff --git a/spec/contracts/provider/pact_helpers/project/pipeline/show/delete_pipeline_helper.rb b/spec/contracts/provider/pact_helpers/project/pipeline/show/delete_pipeline_helper.rb index 0455281fcd7..48f5a277d1f 100644 --- a/spec/contracts/provider/pact_helpers/project/pipeline/show/delete_pipeline_helper.rb +++ b/spec/contracts/provider/pact_helpers/project/pipeline/show/delete_pipeline_helper.rb @@ -1,21 +1,24 @@ # frozen_string_literal: true -require_relative '../../../../spec_helper' -require_relative '../../../../helpers/publish_contract_helper' -require_relative '../../../../states/project/pipeline/show_state' +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/pipeline/show_state" module Provider module DeletePipelineHelper Pact.service_provider "DELETE pipeline" do app { Environments::Test.app } - honours_pact_with 'Pipelines#show' do - pact_uri '../contracts/project/pipeline/show/pipelines#show-delete_pipeline.json' + honours_pact_with "Pipelines#show" do + pact_uri Provider::ContractSourceHelper.contract_location(:DELETE_PIPELINE, :spec) end - app_version Provider::PublishContractHelper::PROVIDER_VERSION - app_version_branch Provider::PublishContractHelper::PROVIDER_BRANCH - publish_verification_results Provider::PublishContractHelper::PUBLISH_FLAG + Provider::PublishContractHelper.publish_contract_setup.call( + method(:app_version), + method(:app_version_branch), + method(:publish_verification_results) + ) end end end diff --git a/spec/contracts/provider/pact_helpers/project/pipeline/show/get_pipeline_header_data_helper.rb b/spec/contracts/provider/pact_helpers/project/pipeline/show/get_pipeline_header_data_helper.rb index bce1c4ab3f4..29f1e51273e 100644 --- a/spec/contracts/provider/pact_helpers/project/pipeline/show/get_pipeline_header_data_helper.rb +++ b/spec/contracts/provider/pact_helpers/project/pipeline/show/get_pipeline_header_data_helper.rb @@ -1,22 +1,22 @@ # frozen_string_literal: true -require_relative '../../../../spec_helper' -require_relative '../../../../helpers/publish_contract_helper' -require_relative '../../../../states/project/pipeline/show_state' +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/pipeline/show_state" module Provider module GetPipelinesHeaderDataHelper + include PublishContractHelper + Pact.service_provider "GET pipeline header data" do app { Environments::Test.app } - honours_pact_with 'Pipelines#show' do - pact_uri '../contracts/project/pipeline/show/pipelines#show-get_project_pipeline_header_data.json' - # pact_uri 'http://localhost:9292/pacts/provider/GET%20pipeline%20header%20data/consumer/Pipelines%23show/latest' + honours_pact_with "Pipelines#show" do + pact_uri Provider::ContractSourceHelper.contract_location(:GET_PIPELINE_HEADER_DATA, :spec) end - app_version Provider::PublishContractHelper::PROVIDER_VERSION - app_version_branch Provider::PublishContractHelper::PROVIDER_BRANCH - publish_verification_results Provider::PublishContractHelper::PUBLISH_FLAG + publish_contract_setup.call end end end diff --git a/spec/contracts/provider/pact_helpers/project/pipeline_schedule/edit/update_pipeline_schedule_helper.rb b/spec/contracts/provider/pact_helpers/project/pipeline_schedule/edit/update_pipeline_schedule_helper.rb new file mode 100644 index 00000000000..54bbeb775a9 --- /dev/null +++ b/spec/contracts/provider/pact_helpers/project/pipeline_schedule/edit/update_pipeline_schedule_helper.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require_relative "../../../../spec_helper" +require_relative "../../../../helpers/contract_source_helper" +require_relative "../../../../helpers/publish_contract_helper" +require_relative "../../../../states/project/pipeline_schedule/edit_state" + +module Provider + module CreateNewPipelineHelper + Pact.service_provider "PUT Edit a pipeline schedule" do + app { Environments::Test.app } + + honours_pact_with "PipelineSchedule#edit" do + pact_uri Provider::ContractSourceHelper.contract_location(:UPDATE_PIPELINE_SCHEDULE, :spec) + end + + Provider::PublishContractHelper.publish_contract_setup.call( + method(:app_version), + method(:app_version_branch), + method(:publish_verification_results) + ) + end + end +end diff --git a/spec/contracts/provider/pact_helpers/project/pipeline_schedule/update_pipeline_schedule_helper.rb b/spec/contracts/provider/pact_helpers/project/pipeline_schedule/update_pipeline_schedule_helper.rb deleted file mode 100644 index d95a09abd8d..00000000000 --- a/spec/contracts/provider/pact_helpers/project/pipeline_schedule/update_pipeline_schedule_helper.rb +++ /dev/null @@ -1,20 +0,0 @@ -# frozen_string_literal: true - -require_relative '../../../spec_helper' -require_relative '../../../states/project/pipeline_schedule/edit_state' - -module Provider - module CreateNewPipelineHelper - Pact.service_provider "PUT Edit a pipeline schedule" do - app { Environments::Test.app } - - honours_pact_with 'PipelineSchedule#edit' do - pact_uri '../contracts/project/pipeline_schedule/edit/pipelineschedules#edit-put_edit_a_pipeline_schedule.json' - end - - app_version Provider::PublishContractHelper::PROVIDER_VERSION - app_version_branch Provider::PublishContractHelper::PROVIDER_BRANCH - publish_verification_results Provider::PublishContractHelper::PUBLISH_FLAG - end - end -end diff --git a/spec/controllers/sessions_controller_spec.rb b/spec/controllers/sessions_controller_spec.rb index 69282f951f9..78b3cc63b08 100644 --- a/spec/controllers/sessions_controller_spec.rb +++ b/spec/controllers/sessions_controller_spec.rb @@ -477,6 +477,22 @@ RSpec.describe SessionsController do expect { authenticate_2fa(login: user.username, otp_attempt: user.current_otp) }.to change { AuthenticationEvent.count }.by(1) expect(AuthenticationEvent.last.provider).to eq("two-factor") end + + context 'when rendering devise two factor' do + render_views + + before do + Gon.clear + end + + it "adds gon variables" do + authenticate_2fa(login: user.username, password: user.password) + + expect(response).to render_template('devise/sessions/two_factor') + expect(Gon.all_variables).not_to be_empty + expect(response.body).to match('gon.api_version') + end + end end context 'when using two-factor authentication via U2F device' do diff --git a/spec/factories/ci/unit_test_failure.rb b/spec/factories/ci/unit_test_failures.rb index 07cd3419754..07cd3419754 100644 --- a/spec/factories/ci/unit_test_failure.rb +++ b/spec/factories/ci/unit_test_failures.rb diff --git a/spec/factories/ci/unit_test.rb b/spec/factories/ci/unit_tests.rb index 480724f260a..480724f260a 100644 --- a/spec/factories/ci/unit_test.rb +++ b/spec/factories/ci/unit_tests.rb diff --git a/spec/features/projects/members/manage_members_spec.rb b/spec/features/projects/members/manage_members_spec.rb index 1f317c55256..9b895dae576 100644 --- a/spec/features/projects/members/manage_members_spec.rb +++ b/spec/features/projects/members/manage_members_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -RSpec.describe 'Projects > Members > Manage members', :js, product_group: :onboarding do +RSpec.describe 'Projects > Members > Manage members', :js, feature_category: :onboarding do include Spec::Support::Helpers::Features::MembersHelpers include Spec::Support::Helpers::Features::InviteMembersModalHelper include Spec::Support::Helpers::ModalHelpers diff --git a/spec/frontend/deploy_tokens/components/new_deploy_token_spec.js b/spec/frontend/deploy_tokens/components/new_deploy_token_spec.js index 990f18d64c1..0bf69acd251 100644 --- a/spec/frontend/deploy_tokens/components/new_deploy_token_spec.js +++ b/spec/frontend/deploy_tokens/components/new_deploy_token_spec.js @@ -6,9 +6,21 @@ import axios from '~/lib/utils/axios_utils'; import { TEST_HOST } from 'helpers/test_constants'; import NewDeployToken from '~/deploy_tokens/components/new_deploy_token.vue'; import waitForPromises from 'helpers/wait_for_promises'; +import { createAlert, VARIANT_INFO } from '~/flash'; const createNewTokenPath = `${TEST_HOST}/create`; const deployTokensHelpUrl = `${TEST_HOST}/help`; + +jest.mock('~/flash', () => { + const original = jest.requireActual('~/flash'); + + return { + __esModule: true, + ...original, + createAlert: jest.fn(), + }; +}); + describe('New Deploy Token', () => { let wrapper; @@ -69,9 +81,69 @@ describe('New Deploy Token', () => { expect(tokenUsername.props('value')).toBe('test token username'); expect(tokenValue.props('value')).toBe('test token'); + + expect(createAlert).toHaveBeenCalledWith( + expect.objectContaining({ + variant: VARIANT_INFO, + }), + ); }); } + it('should flash error message if token creation fails', async () => { + const mockAxios = new MockAdapter(axios); + + const date = new Date(); + const formInputs = wrapper.findAllComponents(GlFormInput); + const name = formInputs.at(0); + const username = formInputs.at(2); + name.vm.$emit('input', 'test name'); + username.vm.$emit('input', 'test username'); + + const datepicker = wrapper.findAllComponents(GlDatepicker).at(0); + datepicker.vm.$emit('input', date); + + const [ + readRepo, + readRegistry, + writeRegistry, + readPackageRegistry, + writePackageRegistry, + ] = wrapper.findAllComponents(GlFormCheckbox).wrappers; + readRepo.vm.$emit('input', true); + readRegistry.vm.$emit('input', true); + writeRegistry.vm.$emit('input', true); + readPackageRegistry.vm.$emit('input', true); + writePackageRegistry.vm.$emit('input', true); + + const expectedErrorMessage = 'Server error while creating a token'; + + mockAxios + .onPost(createNewTokenPath, { + deploy_token: { + name: 'test name', + expires_at: date.toISOString(), + username: 'test username', + read_repository: true, + read_registry: true, + write_registry: true, + read_package_registry: true, + write_package_registry: true, + }, + }) + .replyOnce(500, { message: expectedErrorMessage }); + + wrapper.findAllComponents(GlButton).at(0).vm.$emit('click'); + + await waitForPromises().then(() => nextTick()); + + expect(createAlert).toHaveBeenCalledWith( + expect.objectContaining({ + message: expectedErrorMessage, + }), + ); + }); + it('should make a request to create a token on submit', () => { const mockAxios = new MockAdapter(axios); diff --git a/spec/frontend/monitoring/components/__snapshots__/dashboard_template_spec.js.snap b/spec/frontend/monitoring/components/__snapshots__/dashboard_template_spec.js.snap index 263d6225a9f..3b4554700b4 100644 --- a/spec/frontend/monitoring/components/__snapshots__/dashboard_template_spec.js.snap +++ b/spec/frontend/monitoring/components/__snapshots__/dashboard_template_spec.js.snap @@ -3,7 +3,6 @@ exports[`Dashboard template matches the default snapshot 1`] = ` <div class="prometheus-graphs" - data-qa-selector="prometheus_graphs_content" data-testid="prometheus-graphs" environmentstate="available" metricsdashboardbasepath="/monitoring/monitor-project/-/metrics?environment=1" @@ -40,7 +39,6 @@ exports[`Dashboard template matches the default snapshot 1`] = ` > <dashboards-dropdown-stub class="flex-grow-1" - data-qa-selector="dashboards_filter_dropdown" defaultbranch="master" id="monitor-dashboards-dropdown" toggle-class="dropdown-menu-toggle" @@ -60,7 +58,6 @@ exports[`Dashboard template matches the default snapshot 1`] = ` class="flex-grow-1" clearalltext="Clear all" clearalltextclass="gl-px-5" - data-qa-selector="environments_dropdown" data-testid="environments-dropdown" headertext="" hideheaderborder="true" @@ -106,7 +103,6 @@ exports[`Dashboard template matches the default snapshot 1`] = ` <date-time-picker-stub class="flex-grow-1 show-last-dropdown" customenabled="true" - data-qa-selector="range_picker_dropdown" options="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]" value="[object Object]" /> diff --git a/spec/frontend/projects/settings/mock_data.js b/spec/frontend/projects/settings/mock_data.js new file mode 100644 index 00000000000..0262c0e3e43 --- /dev/null +++ b/spec/frontend/projects/settings/mock_data.js @@ -0,0 +1,57 @@ +const accessLevelsMockResponse = [ + { + __typename: 'PushAccessLevelEdge', + node: { + __typename: 'PushAccessLevel', + accessLevel: 40, + accessLevelDescription: 'Jona Langworth', + group: null, + user: { + __typename: 'UserCore', + id: '123', + webUrl: 'test.com', + name: 'peter', + avatarUrl: 'test.com/user.png', + }, + }, + }, + { + __typename: 'PushAccessLevelEdge', + node: { + __typename: 'PushAccessLevel', + accessLevel: 40, + accessLevelDescription: 'Maintainers', + group: null, + user: null, + }, + }, +]; + +export const pushAccessLevelsMockResponse = { + __typename: 'PushAccessLevelConnection', + edges: accessLevelsMockResponse, +}; + +export const pushAccessLevelsMockResult = { + total: 2, + users: [ + { + src: 'test.com/user.png', + __typename: 'UserCore', + id: '123', + webUrl: 'test.com', + name: 'peter', + avatarUrl: 'test.com/user.png', + }, + ], + groups: [], + roles: [ + { + __typename: 'PushAccessLevel', + accessLevel: 40, + accessLevelDescription: 'Maintainers', + group: null, + user: null, + }, + ], +}; diff --git a/spec/frontend/projects/settings/repository/branch_rules/components/branch_rule_spec.js b/spec/frontend/projects/settings/repository/branch_rules/components/branch_rule_spec.js index 2aa93fd0e28..ee12fd4ee42 100644 --- a/spec/frontend/projects/settings/repository/branch_rules/components/branch_rule_spec.js +++ b/spec/frontend/projects/settings/repository/branch_rules/components/branch_rule_spec.js @@ -63,6 +63,17 @@ describe('Branch rule', () => { subject: n__('rule', 'rules', branchRulePropsMock.approvalRulesTotal), }), ); + expect(findProtectionDetailsListItems().at(4).text()).toBe(wrapper.vm.pushAccessLevelsText); + }); + + it('renders branches count for wildcards', () => { + createComponent({ name: 'test-*' }); + expect(findProtectionDetailsListItems().at(0).text()).toMatchInterpolatedText( + sprintf(i18n.matchingBranches, { + total: branchRulePropsMock.matchingBranchesCount, + subject: n__('branch', 'branches', branchRulePropsMock.matchingBranchesCount), + }), + ); }); it('renders a detail button with the correct href', () => { diff --git a/spec/frontend/projects/settings/repository/branch_rules/mock_data.js b/spec/frontend/projects/settings/repository/branch_rules/mock_data.js index 8aa03a12996..c105999dce6 100644 --- a/spec/frontend/projects/settings/repository/branch_rules/mock_data.js +++ b/spec/frontend/projects/settings/repository/branch_rules/mock_data.js @@ -1,3 +1,29 @@ +export const accessLevelsMockResponse = [ + { + __typename: 'PushAccessLevelEdge', + node: { + __typename: 'PushAccessLevel', + accessLevel: 40, + accessLevelDescription: 'Jona Langworth', + group: null, + user: { + __typename: 'UserCore', + id: '123', + }, + }, + }, + { + __typename: 'PushAccessLevelEdge', + node: { + __typename: 'PushAccessLevel', + accessLevel: 40, + accessLevelDescription: 'Maintainers', + group: null, + user: null, + }, + }, +]; + export const branchRulesMockResponse = { data: { project: { @@ -9,9 +35,18 @@ export const branchRulesMockResponse = { { name: 'main', isDefault: true, + matchingBranchesCount: 1, branchProtection: { allowForcePush: true, codeOwnerApprovalRequired: true, + mergeAccessLevels: { + edges: [], + __typename: 'MergeAccessLevelConnection', + }, + pushAccessLevels: { + edges: accessLevelsMockResponse, + __typename: 'PushAccessLevelConnection', + }, }, approvalRules: { nodes: [{ id: 1 }], @@ -19,16 +54,25 @@ export const branchRulesMockResponse = { }, externalStatusChecks: { nodes: [{ id: 1 }, { id: 2 }], - __typename: 'BranchRule', + __typename: 'ExternalStatusCheckConnection', }, __typename: 'BranchRule', }, { name: 'test-*', isDefault: false, + matchingBranchesCount: 2, branchProtection: { allowForcePush: false, codeOwnerApprovalRequired: false, + mergeAccessLevels: { + edges: [], + __typename: 'MergeAccessLevelConnection', + }, + pushAccessLevels: { + edges: [], + __typename: 'PushAccessLevelConnection', + }, }, approvalRules: { nodes: [], @@ -36,7 +80,7 @@ export const branchRulesMockResponse = { }, externalStatusChecks: { nodes: [], - __typename: 'BranchRule', + __typename: 'ExternalStatusCheckConnection', }, __typename: 'BranchRule', }, @@ -57,17 +101,22 @@ export const branchRuleProvideMock = { export const branchRulePropsMock = { name: 'main', isDefault: true, + matchingBranchesCount: 1, branchProtection: { allowForcePush: true, codeOwnerApprovalRequired: true, + pushAccessLevels: { + edges: accessLevelsMockResponse, + }, }, approvalRulesTotal: 1, statusChecksTotal: 2, }; export const branchRuleWithoutDetailsPropsMock = { - name: 'main', + name: 'branch-1', isDefault: false, + matchingBranchesCount: 1, branchProtection: { allowForcePush: false, codeOwnerApprovalRequired: false, diff --git a/spec/frontend/projects/settings/utils_spec.js b/spec/frontend/projects/settings/utils_spec.js new file mode 100644 index 00000000000..319aa4000b5 --- /dev/null +++ b/spec/frontend/projects/settings/utils_spec.js @@ -0,0 +1,11 @@ +import { getAccessLevels } from '~/projects/settings/utils'; +import { pushAccessLevelsMockResponse, pushAccessLevelsMockResult } from './mock_data'; + +describe('Utils', () => { + describe('getAccessLevels', () => { + it('takes accessLevels response data and returns acecssLevels object', () => { + const pushAccessLevels = getAccessLevels(pushAccessLevelsMockResponse); + expect(pushAccessLevels).toEqual(pushAccessLevelsMockResult); + }); + }); +}); diff --git a/spec/frontend/sidebar/sidebar_mediator_spec.js b/spec/frontend/sidebar/sidebar_mediator_spec.js index bb5e7f7ff16..254489e49a5 100644 --- a/spec/frontend/sidebar/sidebar_mediator_spec.js +++ b/spec/frontend/sidebar/sidebar_mediator_spec.js @@ -24,7 +24,8 @@ describe('Sidebar mediator', () => { SidebarService.singleton = null; SidebarStore.singleton = null; SidebarMediator.singleton = null; - mock.restore(); + + jest.clearAllMocks(); }); it('assigns yourself', () => { @@ -42,6 +43,45 @@ describe('Sidebar mediator', () => { }); }); + describe('saves reviewers', () => { + const mockUpdateResponseData = { + reviewers: [1, 2], + assignees: [3, 4], + }; + const field = 'merge_request[reviewers_ids]'; + const reviewers = [ + { id: 1, suggested: true }, + { id: 2, suggested: false }, + ]; + + let serviceSpy; + + beforeEach(() => { + mediator.store.reviewers = reviewers; + serviceSpy = jest + .spyOn(mediator.service, 'update') + .mockReturnValue(Promise.resolve({ data: mockUpdateResponseData })); + }); + + it('sends correct data to service', () => { + const data = { + reviewer_ids: [1, 2], + suggested_reviewer_ids: [1], + }; + + mediator.saveReviewers(field); + + expect(serviceSpy).toHaveBeenCalledWith(field, data); + }); + + it('saves reviewers', () => { + return mediator.saveReviewers(field).then(() => { + expect(mediator.store.assignees).toEqual(mockUpdateResponseData.assignees); + expect(mediator.store.reviewers).toEqual(mockUpdateResponseData.reviewers); + }); + }); + }); + it('fetches the data', async () => { const mockData = Mock.responseMap.GET[mediatorMockData.endpoint]; mock.onGet(mediatorMockData.endpoint).reply(200, mockData); @@ -49,7 +89,6 @@ describe('Sidebar mediator', () => { await mediator.fetch(); expect(spy).toHaveBeenCalledWith(mockData); - spy.mockRestore(); }); it('processes fetched data', () => { @@ -70,8 +109,6 @@ describe('Sidebar mediator', () => { mediator.setMoveToProjectId(projectId); expect(spy).toHaveBeenCalledWith(projectId); - - spy.mockRestore(); }); it('fetches autocomplete projects', () => { @@ -87,9 +124,6 @@ describe('Sidebar mediator', () => { return mediator.fetchAutocompleteProjects(searchTerm).then(() => { expect(getterSpy).toHaveBeenCalledWith(searchTerm); expect(setterSpy).toHaveBeenCalled(); - - getterSpy.mockRestore(); - setterSpy.mockRestore(); }); }); @@ -106,9 +140,6 @@ describe('Sidebar mediator', () => { return mediator.moveIssue().then(() => { expect(moveIssueSpy).toHaveBeenCalledWith(moveToProjectId); expect(urlSpy).toHaveBeenCalledWith(mockData.web_url); - - moveIssueSpy.mockRestore(); - urlSpy.mockRestore(); }); }); }); diff --git a/spec/frontend/vue_shared/components/source_viewer/components/chunk_spec.js b/spec/frontend/vue_shared/components/source_viewer/components/chunk_spec.js index d720574ce6d..657bd59dac6 100644 --- a/spec/frontend/vue_shared/components/source_viewer/components/chunk_spec.js +++ b/spec/frontend/vue_shared/components/source_viewer/components/chunk_spec.js @@ -1,10 +1,16 @@ +import { nextTick } from 'vue'; import { GlIntersectionObserver } from '@gitlab/ui'; import { shallowMountExtended } from 'helpers/vue_test_utils_helper'; import Chunk from '~/vue_shared/components/source_viewer/components/chunk.vue'; import ChunkLine from '~/vue_shared/components/source_viewer/components/chunk_line.vue'; -import { scrollToElement } from '~/lib/utils/common_utils'; +import LineHighlighter from '~/blob/line_highlighter'; -jest.mock('~/lib/utils/common_utils'); +const lineHighlighter = new LineHighlighter(); +jest.mock('~/blob/line_highlighter', () => + jest.fn().mockReturnValue({ + highlightHash: jest.fn(), + }), +); const DEFAULT_PROPS = { chunkIndex: 2, @@ -104,12 +110,14 @@ describe('Chunk component', () => { }); it('does not scroll to route hash if last chunk is not loaded', () => { - expect(scrollToElement).not.toHaveBeenCalled(); + expect(LineHighlighter).not.toHaveBeenCalled(); }); - it('scrolls to route hash if last chunk is loaded', () => { + it('scrolls to route hash if last chunk is loaded', async () => { createComponent({ totalChunks: DEFAULT_PROPS.chunkIndex + 1 }); - expect(scrollToElement).toHaveBeenCalledWith(hash, { behavior: 'auto' }); + await nextTick(); + expect(LineHighlighter).toHaveBeenCalledWith({ scrollBehavior: 'auto' }); + expect(lineHighlighter.highlightHash).toHaveBeenCalledWith(hash); }); }); }); diff --git a/spec/graphql/resolvers/ci/group_runners_resolver_spec.rb b/spec/graphql/resolvers/ci/group_runners_resolver_spec.rb index 57b2fcbea63..eb613457555 100644 --- a/spec/graphql/resolvers/ci/group_runners_resolver_spec.rb +++ b/spec/graphql/resolvers/ci/group_runners_resolver_spec.rb @@ -78,7 +78,7 @@ RSpec.describe Resolvers::Ci::GroupRunnersResolver do status_status: 'active', type_type: :group_type, tag_name: ['active_runner'], - preload: { tag_name: nil }, + preload: { tag_name: false }, search: 'abc', sort: 'contacted_asc', membership: :descendants, diff --git a/spec/graphql/resolvers/ci/runners_resolver_spec.rb b/spec/graphql/resolvers/ci/runners_resolver_spec.rb index 4038192a68a..a7eb93da297 100644 --- a/spec/graphql/resolvers/ci/runners_resolver_spec.rb +++ b/spec/graphql/resolvers/ci/runners_resolver_spec.rb @@ -67,7 +67,7 @@ RSpec.describe Resolvers::Ci::RunnersResolver do upgrade_status: 'recommended', type_type: :instance_type, tag_name: ['active_runner'], - preload: { tag_name: nil }, + preload: { tag_name: false }, search: 'abc', sort: 'contacted_asc' } @@ -92,7 +92,7 @@ RSpec.describe Resolvers::Ci::RunnersResolver do let(:expected_params) do { active: false, - preload: { tag_name: nil } + preload: { tag_name: false } } end @@ -112,7 +112,7 @@ RSpec.describe Resolvers::Ci::RunnersResolver do let(:expected_params) do { active: false, - preload: { tag_name: nil } + preload: { tag_name: false } } end @@ -131,7 +131,7 @@ RSpec.describe Resolvers::Ci::RunnersResolver do let(:expected_params) do { - preload: { tag_name: nil } + preload: { tag_name: false } } end diff --git a/spec/lib/gitlab/ci/lint_spec.rb b/spec/lib/gitlab/ci/lint_spec.rb index cf07e952f26..cd3d4ee07bb 100644 --- a/spec/lib/gitlab/ci/lint_spec.rb +++ b/spec/lib/gitlab/ci/lint_spec.rb @@ -341,10 +341,8 @@ RSpec.describe Gitlab::Ci::Lint do let(:counters) do { 'count' => a_kind_of(Numeric), - 'avg' => a_kind_of(Numeric), - 'sum' => a_kind_of(Numeric), 'max' => a_kind_of(Numeric), - 'min' => a_kind_of(Numeric) + 'sum' => a_kind_of(Numeric) } end diff --git a/spec/lib/gitlab/ci/pipeline/logger_spec.rb b/spec/lib/gitlab/ci/pipeline/logger_spec.rb index 3af0ebe7484..049a9a416a0 100644 --- a/spec/lib/gitlab/ci/pipeline/logger_spec.rb +++ b/spec/lib/gitlab/ci/pipeline/logger_spec.rb @@ -25,10 +25,8 @@ RSpec.describe ::Gitlab::Ci::Pipeline::Logger do loggable_data = { 'expensive_operation_duration_s' => { 'count' => 1, - 'sum' => a_kind_of(Numeric), - 'avg' => a_kind_of(Numeric), 'max' => a_kind_of(Numeric), - 'min' => a_kind_of(Numeric) + 'sum' => a_kind_of(Numeric) } } @@ -62,17 +60,13 @@ RSpec.describe ::Gitlab::Ci::Pipeline::Logger do data = keys.each.with_object({}) do |key, accumulator| accumulator[key] = { 'count' => count, - 'avg' => a_kind_of(Numeric), - 'sum' => a_kind_of(Numeric), 'max' => a_kind_of(Numeric), - 'min' => a_kind_of(Numeric) + 'sum' => a_kind_of(Numeric) } end if db_count data['expensive_operation_db_count']['max'] = db_count - data['expensive_operation_db_count']['min'] = db_count - data['expensive_operation_db_count']['avg'] = db_count data['expensive_operation_db_count']['sum'] = count * db_count end @@ -134,7 +128,7 @@ RSpec.describe ::Gitlab::Ci::Pipeline::Logger do it 'records durations of observed operations' do loggable_data = { 'pipeline_creation_duration_s' => { - 'avg' => 30, 'sum' => 30, 'count' => 1, 'max' => 30, 'min' => 30 + 'sum' => 30, 'count' => 1, 'max' => 30 } } @@ -168,10 +162,10 @@ RSpec.describe ::Gitlab::Ci::Pipeline::Logger do 'pipeline_creation_caller' => 'source', 'pipeline_source' => pipeline.source, 'pipeline_save_duration_s' => { - 'avg' => 60, 'sum' => 60, 'count' => 1, 'max' => 60, 'min' => 60 + 'sum' => 60, 'count' => 1, 'max' => 60 }, 'pipeline_creation_duration_s' => { - 'avg' => 20, 'sum' => 40, 'count' => 2, 'max' => 30, 'min' => 10 + 'sum' => 40, 'count' => 2, 'max' => 30 } } end @@ -218,10 +212,10 @@ RSpec.describe ::Gitlab::Ci::Pipeline::Logger do 'pipeline_creation_service_duration_s' => a_kind_of(Numeric), 'pipeline_creation_caller' => 'source', 'pipeline_save_duration_s' => { - 'avg' => 60, 'sum' => 60, 'count' => 1, 'max' => 60, 'min' => 60 + 'sum' => 60, 'count' => 1, 'max' => 60 }, 'pipeline_creation_duration_s' => { - 'avg' => 20, 'sum' => 40, 'count' => 2, 'max' => 30, 'min' => 10 + 'sum' => 40, 'count' => 2, 'max' => 30 } } end diff --git a/spec/lib/gitlab/gitaly_client/operation_service_spec.rb b/spec/lib/gitlab/gitaly_client/operation_service_spec.rb index 604feeea325..82d5d0f292b 100644 --- a/spec/lib/gitlab/gitaly_client/operation_service_spec.rb +++ b/spec/lib/gitlab/gitaly_client/operation_service_spec.rb @@ -898,7 +898,7 @@ RSpec.describe Gitlab::GitalyClient::OperationService do end shared_examples '#user_commit_files failure' do - it 'raises a PreReceiveError' do + it 'raises an IndexError' do expect_any_instance_of(Gitaly::OperationService::Stub) .to receive(:user_commit_files).with(kind_of(Enumerator), kind_of(Hash)) .and_raise(structured_error) @@ -912,7 +912,7 @@ RSpec.describe Gitlab::GitalyClient::OperationService do context 'with missing file' do let(:status_code) { GRPC::Core::StatusCodes::NOT_FOUND } - let(:expected_message) { "File not found: README.md" } + let(:expected_message) { "A file with this name doesn't exist" } let(:expected_error) do Gitaly::UserCommitFilesError.new( index_update: Gitaly::IndexError.new( @@ -926,7 +926,7 @@ RSpec.describe Gitlab::GitalyClient::OperationService do context 'with existing directory' do let(:status_code) { GRPC::Core::StatusCodes::ALREADY_EXISTS } - let(:expected_message) { "Directory already exists: dir1" } + let(:expected_message) { "A directory with this name already exists" } let(:expected_error) do Gitaly::UserCommitFilesError.new( index_update: Gitaly::IndexError.new( @@ -940,7 +940,7 @@ RSpec.describe Gitlab::GitalyClient::OperationService do context 'with existing file' do let(:status_code) { GRPC::Core::StatusCodes::ALREADY_EXISTS } - let(:expected_message) { "File already exists: README.md" } + let(:expected_message) { "A file with this name already exists" } let(:expected_error) do Gitaly::UserCommitFilesError.new( index_update: Gitaly::IndexError.new( @@ -954,7 +954,7 @@ RSpec.describe Gitlab::GitalyClient::OperationService do context 'with invalid path' do let(:status_code) { GRPC::Core::StatusCodes::INVALID_ARGUMENT } - let(:expected_message) { "Invalid path: invalid://file/name" } + let(:expected_message) { "invalid path: 'invalid://file/name'" } let(:expected_error) do Gitaly::UserCommitFilesError.new( index_update: Gitaly::IndexError.new( @@ -968,7 +968,7 @@ RSpec.describe Gitlab::GitalyClient::OperationService do context 'with directory traversal' do let(:status_code) { GRPC::Core::StatusCodes::INVALID_ARGUMENT } - let(:expected_message) { "Directory traversal in path escapes repository: ../../../../etc/shadow" } + let(:expected_message) { "Path cannot include directory traversal" } let(:expected_error) do Gitaly::UserCommitFilesError.new( index_update: Gitaly::IndexError.new( @@ -982,7 +982,7 @@ RSpec.describe Gitlab::GitalyClient::OperationService do context 'with empty path' do let(:status_code) { GRPC::Core::StatusCodes::INVALID_ARGUMENT } - let(:expected_message) { "Received empty path" } + let(:expected_message) { "You must provide a file path" } let(:expected_error) do Gitaly::UserCommitFilesError.new( index_update: Gitaly::IndexError.new( @@ -1009,16 +1009,33 @@ RSpec.describe Gitlab::GitalyClient::OperationService do end context 'with an exception without the detailed error' do - let(:permission_error) do - GRPC::PermissionDenied.new - end - - it 'raises PermissionDenied' do + before do expect_any_instance_of(Gitaly::OperationService::Stub) .to receive(:user_commit_files).with(kind_of(Enumerator), kind_of(Hash)) - .and_raise(permission_error) + .and_raise(raised_error) + end - expect { subject }.to raise_error(GRPC::PermissionDenied) + context 'with an index error from libgit2' do + let(:raised_error) do + GRPC::Internal.new('invalid path: .git/foo') + end + + it 'raises IndexError' do + expect { subject }.to raise_error do |error| + expect(error).to be_a(Gitlab::Git::Index::IndexError) + expect(error.message).to eq('invalid path: .git/foo') + end + end + end + + context 'with a generic error' do + let(:raised_error) do + GRPC::PermissionDenied.new + end + + it 'raises PermissionDenied' do + expect { subject }.to raise_error(GRPC::PermissionDenied) + end end end end diff --git a/spec/lib/gitlab/usage/metrics/instrumentations/database_metric_spec.rb b/spec/lib/gitlab/usage/metrics/instrumentations/database_metric_spec.rb index f1ecc8c8ab5..8ca42a6f007 100644 --- a/spec/lib/gitlab/usage/metrics/instrumentations/database_metric_spec.rb +++ b/spec/lib/gitlab/usage/metrics/instrumentations/database_metric_spec.rb @@ -196,6 +196,22 @@ RSpec.describe Gitlab::Usage::Metrics::Instrumentations::DatabaseMetric do end end + context 'with 7 days time frame' do + subject do + database_metric_class.tap do |metric_class| + metric_class.relation { Issue } + metric_class.operation :count + end.new(time_frame: '7d') + end + + it 'calculates a correct result' do + create(:issue, created_at: 10.days.ago) + create(:issue, created_at: 5.days.ago) + + expect(subject.value).to eq(1) + end + end + context 'with additional parameters passed via options' do subject do database_metric_class.tap do |metric_class| diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb index 50b90253e39..d7fc5486ad6 100644 --- a/spec/models/group_spec.rb +++ b/spec/models/group_spec.rb @@ -3366,6 +3366,13 @@ RSpec.describe Group do end end + describe '#work_items_mvc_feature_flag_enabled?' do + it_behaves_like 'checks self and root ancestor feature flag' do + let(:feature_flag) { :work_items_mvc } + let(:feature_flag_method) { :work_items_mvc_feature_flag_enabled? } + end + end + describe '#work_items_mvc_2_feature_flag_enabled?' do it_behaves_like 'checks self and root ancestor feature flag' do let(:feature_flag) { :work_items_mvc_2 } diff --git a/spec/models/project_spec.rb b/spec/models/project_spec.rb index 8cccc9ad83e..9373556a37e 100644 --- a/spec/models/project_spec.rb +++ b/spec/models/project_spec.rb @@ -8156,6 +8156,16 @@ RSpec.describe Project, factory_default: :keep do end end + describe '#work_items_mvc_feature_flag_enabled?' do + let_it_be(:group_project) { create(:project, :in_subgroup) } + + it_behaves_like 'checks parent group feature flag' do + let(:feature_flag_method) { :work_items_mvc_feature_flag_enabled? } + let(:feature_flag) { :work_items_mvc } + let(:subject_project) { group_project } + end + end + describe '#work_items_mvc_2_feature_flag_enabled?' do let_it_be(:group_project) { create(:project, :in_subgroup) } diff --git a/spec/requests/api/graphql/project/branch_protections/merge_access_levels_spec.rb b/spec/requests/api/graphql/project/branch_protections/merge_access_levels_spec.rb index a80f683ea93..74bf5217906 100644 --- a/spec/requests/api/graphql/project/branch_protections/merge_access_levels_spec.rb +++ b/spec/requests/api/graphql/project/branch_protections/merge_access_levels_spec.rb @@ -3,5 +3,5 @@ require 'spec_helper' RSpec.describe 'getting merge access levels for a branch protection' do - include_examples 'perform graphql requests for AccessLevel type objects', :merge + it_behaves_like 'a GraphQL query for access levels', :merge end diff --git a/spec/requests/api/graphql/project/branch_protections/push_access_levels_spec.rb b/spec/requests/api/graphql/project/branch_protections/push_access_levels_spec.rb index cfdaf1096c3..b6c6967fd18 100644 --- a/spec/requests/api/graphql/project/branch_protections/push_access_levels_spec.rb +++ b/spec/requests/api/graphql/project/branch_protections/push_access_levels_spec.rb @@ -3,5 +3,5 @@ require 'spec_helper' RSpec.describe 'getting push access levels for a branch protection' do - include_examples 'perform graphql requests for AccessLevel type objects', :push + it_behaves_like 'a GraphQL query for access levels', :push end diff --git a/spec/requests/api/graphql/project/branch_rules_spec.rb b/spec/requests/api/graphql/project/branch_rules_spec.rb index ed866305445..957bf7001b3 100644 --- a/spec/requests/api/graphql/project/branch_rules_spec.rb +++ b/spec/requests/api/graphql/project/branch_rules_spec.rb @@ -7,16 +7,6 @@ RSpec.describe 'getting list of branch rules for a project' do let_it_be(:project) { create(:project, :repository, :public) } let_it_be(:current_user) { create(:user) } - let_it_be(:branch_name_a) { TestEnv::BRANCH_SHA.each_key.first } - let_it_be(:branch_name_b) { 'diff-*' } - let_it_be(:branch_rules) { [branch_rule_a, branch_rule_b] } - let_it_be(:branch_rule_a) do - create(:protected_branch, project: project, name: branch_name_a) - end - - let_it_be(:branch_rule_b) do - create(:protected_branch, project: project, name: branch_name_b) - end let(:branch_rules_data) { graphql_data_at('project', 'branchRules', 'edges') } let(:variables) { { path: project.full_path } } @@ -61,11 +51,24 @@ RSpec.describe 'getting list of branch rules for a project' do end describe 'queries' do + include_context 'when user tracking is disabled' + + let(:query) do + <<~GQL + query($path: ID!) { + project(fullPath: $path) { + branchRules { + nodes { + matchingBranchesCount + } + } + } + } + GQL + end + before do - # rubocop:disable RSpec/AnyInstanceOf - allow_any_instance_of(User).to receive(:update_tracked_fields!) - allow_any_instance_of(Users::ActivityService).to receive(:execute) - # rubocop:enable RSpec/AnyInstanceOf + create(:protected_branch, project: project) allow_next_instance_of(Resolvers::ProjectResolver) do |resolver| allow(resolver).to receive(:resolve) .with(full_path: project.full_path) @@ -75,25 +78,13 @@ RSpec.describe 'getting list of branch rules for a project' do allow(project.repository.gitaly_ref_client).to receive(:branch_names).and_call_original end - it 'matching_branches_count avoids N+1 queries' do - query = <<~GQL - query($path: ID!) { - project(fullPath: $path) { - branchRules { - nodes { - matchingBranchesCount - } - } - } - } - GQL - - control = ActiveRecord::QueryRecorder.new do + it 'avoids N+1 queries', :use_sql_query_cache, :aggregate_failures do + control = ActiveRecord::QueryRecorder.new(skip_cached: false) do post_graphql(query, current_user: current_user, variables: variables) end # Verify the response includes the field - expect_n_matching_branches_count_fields(2) + expect_n_matching_branches_count_fields(1) create(:protected_branch, project: project) create(:protected_branch, name: '*', project: project) @@ -102,10 +93,9 @@ RSpec.describe 'getting list of branch rules for a project' do post_graphql(query, current_user: current_user, variables: variables) end.not_to exceed_all_query_limit(control) + expect_n_matching_branches_count_fields(3) expect(project.repository).to have_received(:branch_names).at_least(2).times expect(project.repository.gitaly_ref_client).to have_received(:branch_names).once - - expect_n_matching_branches_count_fields(4) end def expect_n_matching_branches_count_fields(count) @@ -118,21 +108,28 @@ RSpec.describe 'getting list of branch rules for a project' do end describe 'response' do + let_it_be(:branch_name_a) { TestEnv::BRANCH_SHA.each_key.first } + let_it_be(:branch_name_b) { 'diff-*' } + let_it_be(:branch_rules) { [branch_rule_a, branch_rule_b] } + let_it_be(:branch_rule_a) do + create(:protected_branch, project: project, name: branch_name_a, id: 9999) + end + + let_it_be(:branch_rule_b) do + create(:protected_branch, project: project, name: branch_name_b, id: 10000) + end + + # branchRules are returned in reverse order, newest first, sorted by primary_key. + let(:branch_rule_b_data) { branch_rules_data.dig(0, 'node') } + let(:branch_rule_a_data) { branch_rules_data.dig(1, 'node') } + before do post_graphql(query, current_user: current_user, variables: variables) end it_behaves_like 'a working graphql query' - it 'includes all fields', :aggregate_failures do - # Responses will be sorted alphabetically. Branch names for this spec - # come from an external constant so we check which is first - br_a_idx = branch_name_a < branch_name_b ? 0 : 1 - br_b_idx = 1 - br_a_idx - - branch_rule_a_data = branch_rules_data.dig(br_a_idx, 'node') - branch_rule_b_data = branch_rules_data.dig(br_b_idx, 'node') - + it 'includes all fields', :use_sql_query_cache, :aggregate_failures do expect(branch_rule_a_data['name']).to eq(branch_name_a) expect(branch_rule_a_data['isDefault']).to be(true).or be(false) expect(branch_rule_a_data['branchProtection']).to be_present diff --git a/spec/services/ci/create_pipeline_service/logger_spec.rb b/spec/services/ci/create_pipeline_service/logger_spec.rb index 3045f8e92b1..9cd5d48a439 100644 --- a/spec/services/ci/create_pipeline_service/logger_spec.rb +++ b/spec/services/ci/create_pipeline_service/logger_spec.rb @@ -19,10 +19,8 @@ RSpec.describe Ci::CreatePipelineService, :yaml_processor_feature_flag_corectnes let(:counters) do { 'count' => a_kind_of(Numeric), - 'avg' => a_kind_of(Numeric), - 'sum' => a_kind_of(Numeric), 'max' => a_kind_of(Numeric), - 'min' => a_kind_of(Numeric) + 'sum' => a_kind_of(Numeric) } end diff --git a/spec/support/helpers/graphql_helpers.rb b/spec/support/helpers/graphql_helpers.rb index bd0efc96bd8..2176a477371 100644 --- a/spec/support/helpers/graphql_helpers.rb +++ b/spec/support/helpers/graphql_helpers.rb @@ -859,7 +859,7 @@ module GraphqlHelpers # A lookahead that selects everything def positive_lookahead - double(selects?: true).tap do |selection| + double(selected?: true, selects?: true).tap do |selection| allow(selection).to receive(:selection).and_return(selection) allow(selection).to receive(:selections).and_return(selection) allow(selection).to receive(:map).and_return(double(include?: true)) @@ -868,7 +868,7 @@ module GraphqlHelpers # A lookahead that selects nothing def negative_lookahead - double(selects?: false).tap do |selection| + double(selected?: false, selects?: false, selections: []).tap do |selection| allow(selection).to receive(:selection).and_return(selection) end end diff --git a/spec/support/shared_contexts/disable_user_tracking.rb b/spec/support/shared_contexts/disable_user_tracking.rb new file mode 100644 index 00000000000..e6689c41d4a --- /dev/null +++ b/spec/support/shared_contexts/disable_user_tracking.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +RSpec.shared_context 'when user tracking is disabled' do + before do + # rubocop:disable RSpec/AnyInstanceOf + allow_any_instance_of(User).to receive(:update_tracked_fields!) + allow_any_instance_of(Users::ActivityService).to receive(:execute) + # rubocop:enable RSpec/AnyInstanceOf + end +end diff --git a/spec/support/shared_examples/boards/destroy_service_shared_examples.rb b/spec/support/shared_examples/boards/destroy_service_shared_examples.rb index b1cb58a736f..578ed0e6260 100644 --- a/spec/support/shared_examples/boards/destroy_service_shared_examples.rb +++ b/spec/support/shared_examples/boards/destroy_service_shared_examples.rb @@ -15,7 +15,7 @@ RSpec.shared_examples 'board destroy service' do expect do expect(service.execute(board)).to be_success - end.to change(boards, :count).by(-1) + end.to change { boards.count }.by(-1) end end @@ -23,7 +23,7 @@ RSpec.shared_examples 'board destroy service' do it 'does remove board' do expect do service.execute(board) - end.to change(boards, :count).by(-1) + end.to change { boards.count }.by(-1) end end end diff --git a/spec/support/shared_examples/ci/retryable_shared_examples.rb b/spec/support/shared_examples/ci/retryable_shared_examples.rb index 4622dbe4e31..dc34ea8bb3c 100644 --- a/spec/support/shared_examples/ci/retryable_shared_examples.rb +++ b/spec/support/shared_examples/ci/retryable_shared_examples.rb @@ -10,7 +10,7 @@ RSpec.shared_examples 'a retryable job' do describe '#set_enqueue_immediately!' do it 'changes #enqueue_immediately? to true' do expect { subject.set_enqueue_immediately! } - .to change(subject, :enqueue_immediately?).from(false).to(true) + .to change { subject.enqueue_immediately? }.from(false).to(true) end end end diff --git a/spec/support/shared_examples/ci/stuck_builds_shared_examples.rb b/spec/support/shared_examples/ci/stuck_builds_shared_examples.rb index 4fcea18393c..dd0a57c6b6d 100644 --- a/spec/support/shared_examples/ci/stuck_builds_shared_examples.rb +++ b/spec/support/shared_examples/ci/stuck_builds_shared_examples.rb @@ -30,6 +30,6 @@ end RSpec.shared_examples 'job is unchanged' do it 'does not change status' do - expect { service.execute }.not_to change(job, :status) + expect { service.execute }.not_to change { job.status } end end diff --git a/spec/support/shared_examples/controllers/githubish_import_controller_shared_examples.rb b/spec/support/shared_examples/controllers/githubish_import_controller_shared_examples.rb index bbbe93a644f..5506b05ca55 100644 --- a/spec/support/shared_examples/controllers/githubish_import_controller_shared_examples.rb +++ b/spec/support/shared_examples/controllers/githubish_import_controller_shared_examples.rb @@ -356,7 +356,7 @@ RSpec.shared_examples 'a GitHub-ish import controller: POST create' do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).and_return(double(execute: project)) - expect { post :create, params: { target_namespace: provider_repo[:name] }, format: :json }.to change(Namespace, :count).by(1) + expect { post :create, params: { target_namespace: provider_repo[:name] }, format: :json }.to change { Namespace.count }.by(1) end it "takes the new namespace" do @@ -377,7 +377,7 @@ RSpec.shared_examples 'a GitHub-ish import controller: POST create' do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).and_return(double(execute: project)) - expect { post :create, format: :json }.not_to change(Namespace, :count) + expect { post :create, format: :json }.not_to change { Namespace.count } end it "takes the current user's namespace" do diff --git a/spec/support/shared_examples/graphql/mutations/incident_management_timeline_events_shared_examples.rb b/spec/support/shared_examples/graphql/mutations/incident_management_timeline_events_shared_examples.rb index cd591248ff6..030aca5bd1c 100644 --- a/spec/support/shared_examples/graphql/mutations/incident_management_timeline_events_shared_examples.rb +++ b/spec/support/shared_examples/graphql/mutations/incident_management_timeline_events_shared_examples.rb @@ -7,7 +7,7 @@ require 'spec_helper' # * Defined expected timeline event via `let(:expected_timeline_event) { instance_double(...) }` RSpec.shared_examples 'creating an incident timeline event' do it 'creates a timeline event' do - expect { resolve }.to change(IncidentManagement::TimelineEvent, :count).by(1) + expect { resolve }.to change { IncidentManagement::TimelineEvent.count }.by(1) end it 'responds with a timeline event', :aggregate_failures do diff --git a/spec/support/shared_examples/graphql/mutations/timelogs/create_shared_examples.rb b/spec/support/shared_examples/graphql/mutations/timelogs/create_shared_examples.rb index f28348fb945..9e8478d7638 100644 --- a/spec/support/shared_examples/graphql/mutations/timelogs/create_shared_examples.rb +++ b/spec/support/shared_examples/graphql/mutations/timelogs/create_shared_examples.rb @@ -32,7 +32,7 @@ RSpec.shared_examples 'issuable supports timelog creation mutation' do it 'creates the timelog' do expect do post_graphql_mutation(mutation, current_user: current_user) - end.to change(Timelog, :count).by(1) + end.to change { Timelog.count }.by(1) expect(response).to have_gitlab_http_status(:success) expect(mutation_response['errors']).to be_empty @@ -50,7 +50,7 @@ RSpec.shared_examples 'issuable supports timelog creation mutation' do it 'returns an error' do expect do post_graphql_mutation(mutation, current_user: current_user) - end.to change(Timelog, :count).by(0) + end.to change { Timelog.count }.by(0) expect(response).to have_gitlab_http_status(:success) expect(mutation_response['errors']).to match_array(['Time spent can\'t be blank']) diff --git a/spec/support/shared_examples/graphql/mutations/work_items/update_description_widget_shared_examples.rb b/spec/support/shared_examples/graphql/mutations/work_items/update_description_widget_shared_examples.rb index 56c2ca22e15..f672ec7f5ac 100644 --- a/spec/support/shared_examples/graphql/mutations/work_items/update_description_widget_shared_examples.rb +++ b/spec/support/shared_examples/graphql/mutations/work_items/update_description_widget_shared_examples.rb @@ -5,7 +5,7 @@ RSpec.shared_examples 'update work item description widget' do expect do post_graphql_mutation(mutation, current_user: current_user) work_item.reload - end.to change(work_item, :description).from(nil).to(new_description) + end.to change { work_item.description }.from(nil).to(new_description) expect(response).to have_gitlab_http_status(:success) expect(mutation_response['workItem']['widgets']).to include( diff --git a/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_shared_examples.rb b/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_shared_examples.rb index 459d4f5cd3e..7141492bd49 100644 --- a/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_shared_examples.rb +++ b/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_shared_examples.rb @@ -16,20 +16,20 @@ RSpec.shared_examples 'backfill migration for project repositories' do |storage| projects.create!(name: "foo-#{index}", path: "foo-#{index}", namespace_id: group.id, storage_version: storage_version) end - expect { described_class.new.perform(1, projects.last.id) }.to change(project_repositories, :count).by(2) + expect { described_class.new.perform(1, projects.last.id) }.to change { project_repositories.count }.by(2) end it "does nothing for projects on #{storage} storage that have already a project_repository row" do projects.create!(id: 1, name: 'foo', path: 'foo', namespace_id: group.id, storage_version: storage_version) project_repositories.create!(project_id: 1, disk_path: 'phony/foo/bar', shard_id: shard.id) - expect { described_class.new.perform(1, projects.last.id) }.not_to change(project_repositories, :count) + expect { described_class.new.perform(1, projects.last.id) }.not_to change { project_repositories.count } end it "does nothing for projects on #{storage == :legacy ? 'hashed' : 'legacy'} storage" do projects.create!(name: 'foo', path: 'foo', namespace_id: group.id, storage_version: storage == :legacy ? 1 : nil) - expect { described_class.new.perform(1, projects.last.id) }.not_to change(project_repositories, :count) + expect { described_class.new.perform(1, projects.last.id) }.not_to change { project_repositories.count } end it 'inserts rows in a single query' do diff --git a/spec/support/shared_examples/models/integrations/has_web_hook_shared_examples.rb b/spec/support/shared_examples/models/integrations/has_web_hook_shared_examples.rb index a764d47d7c0..a1269b158a2 100644 --- a/spec/support/shared_examples/models/integrations/has_web_hook_shared_examples.rb +++ b/spec/support/shared_examples/models/integrations/has_web_hook_shared_examples.rb @@ -65,7 +65,7 @@ RSpec.shared_examples Integrations::HasWebHook do end it 'creates or updates a service hook' do - expect { call }.to change(ServiceHook, :count).by(1) + expect { call }.to change { ServiceHook.count }.by(1) expect(integration.service_hook.url).to eq(hook_url) integration.service_hook.update!(url: 'http://other.com') @@ -98,10 +98,10 @@ RSpec.shared_examples Integrations::HasWebHook do it 'creates the webhook if necessary and executes it' do expect_next(ServiceHook).to receive(:execute).with(*args) - expect { call }.to change(ServiceHook, :count).by(1) + expect { call }.to change { ServiceHook.count }.by(1) expect(integration.service_hook).to receive(:execute).with(*args) - expect { call }.not_to change(ServiceHook, :count) + expect { call }.not_to change { ServiceHook.count } end it 'raises an error if the service hook could not be saved' do diff --git a/spec/support/shared_examples/models/member_shared_examples.rb b/spec/support/shared_examples/models/member_shared_examples.rb index 287b046cbec..f8cff5c5558 100644 --- a/spec/support/shared_examples/models/member_shared_examples.rb +++ b/spec/support/shared_examples/models/member_shared_examples.rb @@ -491,7 +491,7 @@ RSpec.shared_examples_for "bulk member creation" do :developer, tasks_to_be_done: %w(issues), tasks_project_id: task_project.id) - end.not_to change(MemberTask, :count) + end.not_to change { MemberTask.count } member.reset expect(member.tasks_to_be_done).to match_array([:code, :ci]) @@ -505,7 +505,7 @@ RSpec.shared_examples_for "bulk member creation" do :developer, tasks_to_be_done: %w(issues), tasks_project_id: task_project.id) - end.to change(MemberTask, :count).by(1) + end.to change { MemberTask.count }.by(1) member = source.members.find_by(user_id: user1.id) expect(member.tasks_to_be_done).to match_array([:issues]) diff --git a/spec/support/shared_examples/models/update_highest_role_shared_examples.rb b/spec/support/shared_examples/models/update_highest_role_shared_examples.rb index 34c4ada1718..1fdd0962fbb 100644 --- a/spec/support/shared_examples/models/update_highest_role_shared_examples.rb +++ b/spec/support/shared_examples/models/update_highest_role_shared_examples.rb @@ -25,7 +25,7 @@ RSpec.shared_examples 'update highest role with exclusive lease' do expect(UpdateHighestRoleWorker).to receive(:perform_in).with(described_class::HIGHEST_ROLE_JOB_DELAY, user_id).and_call_original - expect { subject }.to change(UpdateHighestRoleWorker.jobs, :size).by(1) + expect { subject }.to change { UpdateHighestRoleWorker.jobs.size }.by(1) end end @@ -33,7 +33,7 @@ RSpec.shared_examples 'update highest role with exclusive lease' do it 'only schedules one job' do stub_exclusive_lease_taken(lease_key, timeout: described_class::HIGHEST_ROLE_LEASE_TIMEOUT) - expect { subject }.not_to change(UpdateHighestRoleWorker.jobs, :size) + expect { subject }.not_to change { UpdateHighestRoleWorker.jobs.size } end end end diff --git a/spec/support/shared_examples/requests/api/graphql/projects/branch_protections/access_level_request_examples.rb b/spec/support/shared_examples/requests/api/graphql/projects/branch_protections/access_level_request_examples.rb index 54cc13fac94..6b4d8cae2ce 100644 --- a/spec/support/shared_examples/requests/api/graphql/projects/branch_protections/access_level_request_examples.rb +++ b/spec/support/shared_examples/requests/api/graphql/projects/branch_protections/access_level_request_examples.rb @@ -1,13 +1,13 @@ # frozen_string_literal: true -RSpec.shared_examples 'perform graphql requests for AccessLevel type objects' do |access_level_kind| +RSpec.shared_examples 'a GraphQL query for access levels' do |access_level_kind| include GraphqlHelpers let_it_be(:project) { create(:project) } let_it_be(:current_user) { create(:user, maintainer_projects: [project]) } let_it_be(:variables) { { path: project.full_path } } - let(:fields) { all_graphql_fields_for("#{access_level_kind.to_s.classify}AccessLevel", max_depth: 2) } + let(:fields) { all_graphql_fields_for("#{access_level_kind.to_s.classify}AccessLevel") } let(:access_levels) { protected_branch.public_send("#{access_level_kind}_access_levels") } let(:access_levels_count) { access_levels.size } let(:maintainer_access_level) { access_levels.for_role.first } @@ -61,17 +61,35 @@ RSpec.shared_examples 'perform graphql requests for AccessLevel type objects' do create(:protected_branch, "maintainers_can_#{access_level_kind}", project: project) end - before do - post_graphql(query, current_user: current_user, variables: variables) + describe 'query' do + it 'avoids N+1 queries' do + control = ActiveRecord::QueryRecorder.new do + post_graphql(query, current_user: current_user, variables: variables) + end + expect_graphql_errors_to_be_empty + + create("protected_branch_#{access_level_kind}_access_level", protected_branch: protected_branch) + + expect do + post_graphql(query, current_user: current_user, variables: variables) + end.not_to exceed_all_query_limit(control) + expect_graphql_errors_to_be_empty + end end - it_behaves_like 'a working graphql query' + describe 'response' do + before do + post_graphql(query, current_user: current_user, variables: variables) + end + + it_behaves_like 'a working graphql query' - it 'returns all the access level attributes' do - expect(maintainer_access_level_data['accessLevel']).to eq(maintainer_access_level.access_level) - expect(maintainer_access_level_data['accessLevelDescription']).to eq(maintainer_access_level.humanize) - expect(maintainer_access_level_data.dig('group', 'name')).to be_nil - expect(maintainer_access_level_data.dig('user', 'name')).to be_nil + it 'returns all the access level attributes' do + expect(maintainer_access_level_data['accessLevel']).to eq(maintainer_access_level.access_level) + expect(maintainer_access_level_data['accessLevelDescription']).to eq(maintainer_access_level.humanize) + expect(maintainer_access_level_data.dig('group', 'name')).to be_nil + expect(maintainer_access_level_data.dig('user', 'name')).to be_nil + end end end end diff --git a/spec/support/shared_examples/requests/api/notes_shared_examples.rb b/spec/support/shared_examples/requests/api/notes_shared_examples.rb index 11f9565989f..efe5ed3bcf9 100644 --- a/spec/support/shared_examples/requests/api/notes_shared_examples.rb +++ b/spec/support/shared_examples/requests/api/notes_shared_examples.rb @@ -159,7 +159,7 @@ RSpec.shared_examples 'noteable API' do |parent_type, noteable_type, id_name| expect do post api(uri, user), params: { body: 'hi!' } - end.to change(Event, :count).by(1) + end.to change { Event.count }.by(1) end context 'setting created_at' do diff --git a/spec/support/shared_examples/security_training_providers_importer.rb b/spec/support/shared_examples/security_training_providers_importer.rb index 568e3e1a4f2..69d92964270 100644 --- a/spec/support/shared_examples/security_training_providers_importer.rb +++ b/spec/support/shared_examples/security_training_providers_importer.rb @@ -8,7 +8,7 @@ RSpec.shared_examples 'security training providers importer' do end it 'upserts security training providers' do - expect { 2.times { subject } }.to change(security_training_providers, :count).from(0).to(2) + expect { 2.times { subject } }.to change { security_training_providers.count }.from(0).to(2) expect(security_training_providers.all.map(&:name)).to match_array(['Kontra', 'Secure Code Warrior']) end end diff --git a/spec/support/shared_examples/services/alert_management/alert_processing/alert_firing_shared_examples.rb b/spec/support/shared_examples/services/alert_management/alert_processing/alert_firing_shared_examples.rb index 0db9519f760..6a9da91eaa7 100644 --- a/spec/support/shared_examples/services/alert_management/alert_processing/alert_firing_shared_examples.rb +++ b/spec/support/shared_examples/services/alert_management/alert_processing/alert_firing_shared_examples.rb @@ -11,7 +11,7 @@ RSpec.shared_examples 'creates an alert management alert or errors' do it 'creates AlertManagement::Alert' do expect(Gitlab::AppLogger).not_to receive(:warn) - expect { subject }.to change(AlertManagement::Alert, :count).by(1) + expect { subject }.to change { AlertManagement::Alert.count }.by(1) end it 'executes the alert service hooks' do @@ -118,7 +118,7 @@ end RSpec.shared_examples 'does not create an alert management alert' do specify do - expect { subject }.not_to change(AlertManagement::Alert, :count) + expect { subject }.not_to change { AlertManagement::Alert.count } end end diff --git a/spec/support/shared_examples/services/alert_management/alert_processing/incident_resolution_shared_examples.rb b/spec/support/shared_examples/services/alert_management/alert_processing/incident_resolution_shared_examples.rb index 1973577d742..2740b6bf59d 100644 --- a/spec/support/shared_examples/services/alert_management/alert_processing/incident_resolution_shared_examples.rb +++ b/spec/support/shared_examples/services/alert_management/alert_processing/incident_resolution_shared_examples.rb @@ -14,7 +14,7 @@ RSpec.shared_examples 'closes related incident if enabled' do specify do expect { Sidekiq::Testing.inline! { subject } } .to change { alert.issue.reload.closed? }.from(false).to(true) - .and change(ResourceStateEvent, :count).by(1) + .and change { ResourceStateEvent.count }.by(1) end end diff --git a/spec/support/shared_examples/services/alert_management/alert_processing/system_notes_shared_examples.rb b/spec/support/shared_examples/services/alert_management/alert_processing/system_notes_shared_examples.rb index 57d598c0259..2d0815ba27c 100644 --- a/spec/support/shared_examples/services/alert_management/alert_processing/system_notes_shared_examples.rb +++ b/spec/support/shared_examples/services/alert_management/alert_processing/system_notes_shared_examples.rb @@ -19,7 +19,7 @@ RSpec.shared_examples 'creates expected system notes for alert' do |*notes| end it "for #{notes.join(', ')}" do - expect { subject }.to change(Note, :count).by(expected_note_count) + expect { subject }.to change { Note.count }.by(expected_note_count) expected_notes.each_value.with_index do |value, index| expect(new_notes[index]).to include(value) @@ -29,6 +29,6 @@ end RSpec.shared_examples 'does not create a system note for alert' do specify do - expect { subject }.not_to change(Note, :count) + expect { subject }.not_to change { Note.count } end end diff --git a/spec/support/shared_examples/services/alert_management_shared_examples.rb b/spec/support/shared_examples/services/alert_management_shared_examples.rb index b46ace1824a..b8fc2eb5475 100644 --- a/spec/support/shared_examples/services/alert_management_shared_examples.rb +++ b/spec/support/shared_examples/services/alert_management_shared_examples.rb @@ -68,8 +68,8 @@ RSpec.shared_examples 'processes one firing and one resolved prometheus alerts' expect(Gitlab::AppLogger).not_to receive(:warn) expect { subject } - .to change(AlertManagement::Alert, :count).by(1) - .and change(Note, :count).by(1) + .to change { AlertManagement::Alert.count }.by(1) + .and change { Note.count }.by(1) expect(subject).to be_success expect(subject.payload).to eq({}) diff --git a/spec/support/shared_examples/services/boards/boards_create_service_shared_examples.rb b/spec/support/shared_examples/services/boards/boards_create_service_shared_examples.rb index f28c78aec97..67a5af587e9 100644 --- a/spec/support/shared_examples/services/boards/boards_create_service_shared_examples.rb +++ b/spec/support/shared_examples/services/boards/boards_create_service_shared_examples.rb @@ -3,7 +3,7 @@ RSpec.shared_examples 'boards create service' do context 'when parent does not have a board' do it 'creates a new board' do - expect { service.execute }.to change(Board, :count).by(1) + expect { service.execute }.to change { Board.count }.by(1) end it 'creates the default lists' do @@ -23,7 +23,7 @@ RSpec.shared_examples 'boards create service' do it 'does not create a new board' do expect(service).to receive(:can_create_board?) { false } - expect { service.execute }.not_to change(parent.boards, :count) + expect { service.execute }.not_to change { parent.boards.count } end end end diff --git a/spec/support/shared_examples/services/boards/boards_list_service_shared_examples.rb b/spec/support/shared_examples/services/boards/boards_list_service_shared_examples.rb index fd832d4484d..80d5c771abd 100644 --- a/spec/support/shared_examples/services/boards/boards_list_service_shared_examples.rb +++ b/spec/support/shared_examples/services/boards/boards_list_service_shared_examples.rb @@ -2,7 +2,7 @@ RSpec.shared_examples 'boards list service' do it 'does not create a new board' do - expect { service.execute }.not_to change(parent.boards, :count) + expect { service.execute }.not_to change { parent.boards.count } end it 'returns parent boards' do diff --git a/spec/support/shared_examples/services/boards/boards_recent_visit_shared_examples.rb b/spec/support/shared_examples/services/boards/boards_recent_visit_shared_examples.rb index 68ea460dabc..8bf01ad84ff 100644 --- a/spec/support/shared_examples/services/boards/boards_recent_visit_shared_examples.rb +++ b/spec/support/shared_examples/services/boards/boards_recent_visit_shared_examples.rb @@ -5,7 +5,7 @@ RSpec.shared_examples 'boards recent visit' do describe '#visited' do it 'creates a visit if one does not exists' do - expect { described_class.visited!(user, board) }.to change(described_class, :count).by(1) + expect { described_class.visited!(user, board) }.to change { described_class.count }.by(1) end shared_examples 'was visited previously' do diff --git a/spec/support/shared_examples/services/boards/lists_destroy_service_shared_examples.rb b/spec/support/shared_examples/services/boards/lists_destroy_service_shared_examples.rb index af88644ced7..52d427d6684 100644 --- a/spec/support/shared_examples/services/boards/lists_destroy_service_shared_examples.rb +++ b/spec/support/shared_examples/services/boards/lists_destroy_service_shared_examples.rb @@ -5,7 +5,7 @@ RSpec.shared_examples 'lists destroy service' do it 'removes list from board' do service = described_class.new(parent, user) - expect { service.execute(list) }.to change(board.lists, :count).by(-1) + expect { service.execute(list) }.to change { board.lists.count }.by(-1) end it 'decrements position of higher lists' do @@ -24,6 +24,6 @@ RSpec.shared_examples 'lists destroy service' do it 'does not remove list from board when list type is closed' do service = described_class.new(parent, user) - expect { service.execute(closed_list) }.not_to change(board.lists, :count) + expect { service.execute(closed_list) }.not_to change { board.lists.count } end end diff --git a/spec/support/shared_examples/services/boards/lists_list_service_shared_examples.rb b/spec/support/shared_examples/services/boards/lists_list_service_shared_examples.rb index e1143562661..b9f28fab558 100644 --- a/spec/support/shared_examples/services/boards/lists_list_service_shared_examples.rb +++ b/spec/support/shared_examples/services/boards/lists_list_service_shared_examples.rb @@ -5,7 +5,7 @@ RSpec.shared_examples 'lists list service' do let!(:backlog_list) { create_backlog_list(board) } it 'does not create a backlog list' do - expect { service.execute(board) }.not_to change(board.lists, :count) + expect { service.execute(board) }.not_to change { board.lists.count } end it "returns board's lists" do @@ -35,11 +35,11 @@ RSpec.shared_examples 'lists list service' do context 'when the board does not have a backlog list' do it 'creates a backlog list' do - expect { service.execute(board) }.to change(board.lists, :count).by(1) + expect { service.execute(board) }.to change { board.lists.count }.by(1) end it 'does not create a backlog list when create_default_lists is false' do - expect { service.execute(board, create_default_lists: false) }.not_to change(board.lists, :count) + expect { service.execute(board, create_default_lists: false) }.not_to change { board.lists.count } end it "returns board's lists" do diff --git a/spec/support/shared_examples/services/incident_shared_examples.rb b/spec/support/shared_examples/services/incident_shared_examples.rb index b533b095aac..a87e7c1f801 100644 --- a/spec/support/shared_examples/services/incident_shared_examples.rb +++ b/spec/support/shared_examples/services/incident_shared_examples.rb @@ -55,7 +55,7 @@ RSpec.shared_examples 'incident management label service' do shared_examples 'existing label' do it 'returns the existing label' do - expect { execute }.not_to change(Label, :count) + expect { execute }.not_to change { Label.count } expect(execute).to be_success expect(execute.payload).to eq(label: label) @@ -64,7 +64,7 @@ RSpec.shared_examples 'incident management label service' do shared_examples 'new label' do it 'creates a new label' do - expect { execute }.to change(Label, :count).by(1) + expect { execute }.to change { Label.count }.by(1) label = project.reload.labels.last expect(execute).to be_success diff --git a/spec/support/shared_examples/services/issuable/update_service_shared_examples.rb b/spec/support/shared_examples/services/issuable/update_service_shared_examples.rb index 3d90885dd6f..ff7acc7e907 100644 --- a/spec/support/shared_examples/services/issuable/update_service_shared_examples.rb +++ b/spec/support/shared_examples/services/issuable/update_service_shared_examples.rb @@ -5,7 +5,7 @@ RSpec.shared_examples_for 'issuable update service updating last_edited_at value let(:update_params) { { title: 'updated title' } } it 'does not update last_edited values' do - expect { update_issuable }.to change(issuable, :title).from(issuable.title).to('updated title').and( + expect { update_issuable }.to change { issuable.title }.from(issuable.title).to('updated title').and( not_change(issuable, :last_edited_at) ).and( not_change(issuable, :last_edited_by) @@ -19,10 +19,10 @@ RSpec.shared_examples_for 'issuable update service updating last_edited_at value it 'updates last_edited values' do expect do update_issuable - end.to change(issuable, :description).from(issuable.description).to('updated description').and( - change(issuable, :last_edited_at) + end.to change { issuable.description }.from(issuable.description).to('updated description').and( + change { issuable.last_edited_at } ).and( - change(issuable, :last_edited_by) + change { issuable.last_edited_by } ) end end diff --git a/spec/support/shared_examples/services/issuable_links/create_links_shared_examples.rb b/spec/support/shared_examples/services/issuable_links/create_links_shared_examples.rb index 65351ac94ab..12f2b5d78a5 100644 --- a/spec/support/shared_examples/services/issuable_links/create_links_shared_examples.rb +++ b/spec/support/shared_examples/services/issuable_links/create_links_shared_examples.rb @@ -24,7 +24,7 @@ RSpec.shared_examples 'issuable link creation' do end it 'no relationship is created' do - expect { subject }.not_to change(issuable_link_class, :count) + expect { subject }.not_to change { issuable_link_class.count } end end @@ -38,7 +38,7 @@ RSpec.shared_examples 'issuable link creation' do end it 'no relationship is created' do - expect { subject }.not_to change(issuable_link_class, :count) + expect { subject }.not_to change { issuable_link_class.count } end end @@ -54,7 +54,7 @@ RSpec.shared_examples 'issuable link creation' do end it 'no relationship is created' do - expect { subject }.not_to change(issuable_link_class, :count) + expect { subject }.not_to change { issuable_link_class.count } end end @@ -64,7 +64,7 @@ RSpec.shared_examples 'issuable link creation' do end it 'creates relationships' do - expect { subject }.to change(issuable_link_class, :count).by(2) + expect { subject }.to change { issuable_link_class.count }.by(2) expect(issuable_link_class.find_by!(target: issuable2)).to have_attributes(source: issuable, link_type: 'relates_to') expect(issuable_link_class.find_by!(target: issuable3)).to have_attributes(source: issuable, link_type: 'relates_to') diff --git a/spec/support/shared_examples/services/issuable_links/destroyable_issuable_links_shared_examples.rb b/spec/support/shared_examples/services/issuable_links/destroyable_issuable_links_shared_examples.rb index 5e80014da1d..cc170c6544d 100644 --- a/spec/support/shared_examples/services/issuable_links/destroyable_issuable_links_shared_examples.rb +++ b/spec/support/shared_examples/services/issuable_links/destroyable_issuable_links_shared_examples.rb @@ -8,7 +8,7 @@ RSpec.shared_examples 'a destroyable issuable link' do end it 'removes related issue' do - expect { subject }.to change(issuable_link.class, :count).by(-1) + expect { subject }.to change { issuable_link.class.count }.by(-1) end it 'creates notes' do @@ -28,7 +28,7 @@ RSpec.shared_examples 'a destroyable issuable link' do context 'when failing to remove an issuable link' do it 'does not remove relation' do - expect { subject }.not_to change(issuable_link.class, :count).from(1) + expect { subject }.not_to change { issuable_link.class.count }.from(1) end it 'does not create notes' do diff --git a/spec/support/shared_examples/services/projects/update_repository_storage_service_shared_examples.rb b/spec/support/shared_examples/services/projects/update_repository_storage_service_shared_examples.rb index 14af35e58b7..9f940d27341 100644 --- a/spec/support/shared_examples/services/projects/update_repository_storage_service_shared_examples.rb +++ b/spec/support/shared_examples/services/projects/update_repository_storage_service_shared_examples.rb @@ -71,7 +71,7 @@ RSpec.shared_examples 'moves repository to another storage' do |repository_type| it 'does not enqueue a GC run' do expect { subject.execute } - .not_to change(Projects::GitGarbageCollectWorker.jobs, :count) + .not_to change { Projects::GitGarbageCollectWorker.jobs.count } end end @@ -84,12 +84,12 @@ RSpec.shared_examples 'moves repository to another storage' do |repository_type| stub_application_setting(housekeeping_enabled: false) expect { subject.execute } - .not_to change(Projects::GitGarbageCollectWorker.jobs, :count) + .not_to change { Projects::GitGarbageCollectWorker.jobs.count } end it 'enqueues a GC run' do expect { subject.execute } - .to change(Projects::GitGarbageCollectWorker.jobs, :count).by(1) + .to change { Projects::GitGarbageCollectWorker.jobs.count }.by(1) end end end diff --git a/spec/support/shared_examples/services/repositories/housekeeping_shared_examples.rb b/spec/support/shared_examples/services/repositories/housekeeping_shared_examples.rb index 4c00faee56b..e390ae23c6d 100644 --- a/spec/support/shared_examples/services/repositories/housekeeping_shared_examples.rb +++ b/spec/support/shared_examples/services/repositories/housekeeping_shared_examples.rb @@ -12,7 +12,7 @@ RSpec.shared_examples 'housekeeps repository' do expect(resource.git_garbage_collect_worker_klass).to receive(:perform_async).with(resource.id, :incremental_repack, :the_lease_key, :the_uuid).and_call_original Sidekiq::Testing.fake! do - expect { subject.execute }.to change(resource.git_garbage_collect_worker_klass.jobs, :size).by(1) + expect { subject.execute }.to change { resource.git_garbage_collect_worker_klass.jobs.size }.by(1) end end diff --git a/spec/support/shared_examples/services/schedule_bulk_repository_shard_moves_shared_examples.rb b/spec/support/shared_examples/services/schedule_bulk_repository_shard_moves_shared_examples.rb index 97304680316..acf15730180 100644 --- a/spec/support/shared_examples/services/schedule_bulk_repository_shard_moves_shared_examples.rb +++ b/spec/support/shared_examples/services/schedule_bulk_repository_shard_moves_shared_examples.rb @@ -11,7 +11,7 @@ RSpec.shared_examples 'moves repository shard in bulk' do describe '#execute' do it 'schedules container repository storage moves' do expect { subject.execute(source_storage_name, destination_storage_name) } - .to change(move_service_klass, :count).by(1) + .to change { move_service_klass.count }.by(1) storage_move = container.repository_storage_moves.last! @@ -29,7 +29,7 @@ RSpec.shared_examples 'moves repository shard in bulk' do expect(subject).to receive(:log_info) .with(/Container #{container.full_path} \(#{container.id}\) was skipped: #{container.class} is read-only/) expect { subject.execute(source_storage_name, destination_storage_name) } - .to change(move_service_klass, :count).by(0) + .to change { move_service_klass.count }.by(0) end end end diff --git a/spec/support/shared_examples/services/wiki_pages/create_service_shared_examples.rb b/spec/support/shared_examples/services/wiki_pages/create_service_shared_examples.rb index 980a752cf86..ced49b3e481 100644 --- a/spec/support/shared_examples/services/wiki_pages/create_service_shared_examples.rb +++ b/spec/support/shared_examples/services/wiki_pages/create_service_shared_examples.rb @@ -75,7 +75,7 @@ RSpec.shared_examples 'WikiPages::CreateService#execute' do |container_type| end it 'does not record the activity' do - expect { service.execute }.not_to change(Event, :count) + expect { service.execute }.not_to change { Event.count } end it 'reports the error' do diff --git a/spec/support/shared_examples/services/wiki_pages/update_service_shared_examples.rb b/spec/support/shared_examples/services/wiki_pages/update_service_shared_examples.rb index fd10dd4367e..5511843e681 100644 --- a/spec/support/shared_examples/services/wiki_pages/update_service_shared_examples.rb +++ b/spec/support/shared_examples/services/wiki_pages/update_service_shared_examples.rb @@ -79,7 +79,7 @@ RSpec.shared_examples 'WikiPages::UpdateService#execute' do |container_type| end it 'does not record the activity' do - expect { service.execute page }.not_to change(Event, :count) + expect { service.execute page }.not_to change { Event.count } end it 'reports the error' do diff --git a/spec/support/shared_examples/services/work_items/widgets/milestone_service_shared_examples.rb b/spec/support/shared_examples/services/work_items/widgets/milestone_service_shared_examples.rb index ac17915c15a..ac064ed4c33 100644 --- a/spec/support/shared_examples/services/work_items/widgets/milestone_service_shared_examples.rb +++ b/spec/support/shared_examples/services/work_items/widgets/milestone_service_shared_examples.rb @@ -23,7 +23,7 @@ RSpec.shared_examples "setting work item's milestone" do it "sets the work item's milestone" do expect { execute_callback } - .to change(work_item, :milestone) + .to change { work_item.milestone } .from(nil) .to(group_milestone) end @@ -34,7 +34,7 @@ RSpec.shared_examples "setting work item's milestone" do it "sets the work item's milestone" do expect { execute_callback } - .to change(work_item, :milestone) + .to change { work_item.milestone } .from(nil) .to(project_milestone) end diff --git a/spec/support/shared_examples/work_item_base_types_importer.rb b/spec/support/shared_examples/work_item_base_types_importer.rb index 593670ac4b8..b1011037584 100644 --- a/spec/support/shared_examples/work_item_base_types_importer.rb +++ b/spec/support/shared_examples/work_item_base_types_importer.rb @@ -4,7 +4,7 @@ RSpec.shared_examples 'work item base types importer' do it "creates all base work item types if they don't exist" do WorkItems::Type.delete_all - expect { subject }.to change(WorkItems::Type, :count).from(0).to(WorkItems::Type::BASE_TYPES.count) + expect { subject }.to change { WorkItems::Type.count }.from(0).to(WorkItems::Type::BASE_TYPES.count) types_in_db = WorkItems::Type.all.map { |type| type.slice(:base_type, :icon_name, :name).symbolize_keys } expected_types = WorkItems::Type::BASE_TYPES.map do |type, attributes| @@ -25,7 +25,7 @@ RSpec.shared_examples 'work item base types importer' do subject first_type.reload end.to not_change(WorkItems::Type, :count).and( - change(first_type, :name).from(original_name.upcase).to(original_name) + change { first_type.name }.from(original_name.upcase).to(original_name) ) end @@ -40,7 +40,7 @@ RSpec.shared_examples 'work item base types importer' do it 'inserts all types and does nothing if some already existed' do expect { subject }.to make_queries_matching(/INSERT/, 1).and( - change(WorkItems::Type, :count).by(1) + change { WorkItems::Type.count }.by(1) ) expect(WorkItems::Type.count).to eq(WorkItems::Type::BASE_TYPES.count) end diff --git a/spec/support/shared_examples/workers/schedule_bulk_repository_shard_moves_shared_examples.rb b/spec/support/shared_examples/workers/schedule_bulk_repository_shard_moves_shared_examples.rb index 465aca63148..6707f65eb69 100644 --- a/spec/support/shared_examples/workers/schedule_bulk_repository_shard_moves_shared_examples.rb +++ b/spec/support/shared_examples/workers/schedule_bulk_repository_shard_moves_shared_examples.rb @@ -15,7 +15,7 @@ RSpec.shared_examples 'schedules bulk repository shard moves' do let(:job_args) { [source_storage_name, destination_storage_name] } it 'schedules container repository storage moves' do - expect { subject }.to change(move_service_klass, :count).by(1) + expect { subject }.to change { move_service_klass.count }.by(1) storage_move = container.repository_storage_moves.last! diff --git a/spec/support/shared_examples/workers/update_repository_move_shared_examples.rb b/spec/support/shared_examples/workers/update_repository_move_shared_examples.rb index babd7cfbbeb..c50dc6d5372 100644 --- a/spec/support/shared_examples/workers/update_repository_move_shared_examples.rb +++ b/spec/support/shared_examples/workers/update_repository_move_shared_examples.rb @@ -15,7 +15,7 @@ RSpec.shared_examples 'an update storage move worker' do expect do subject.perform(container.id, 'test_second_storage') - end.to change(repository_storage_move_klass, :count).by(1) + end.to change { repository_storage_move_klass.count }.by(1) storage_move = container.repository_storage_moves.last expect(storage_move).to have_attributes( @@ -32,7 +32,7 @@ RSpec.shared_examples 'an update storage move worker' do expect do subject.perform(nil, nil, repository_storage_move.id) - end.not_to change(repository_storage_move_klass, :count) + end.not_to change { repository_storage_move_klass.count } end end end diff --git a/spec/workers/bulk_import_worker_spec.rb b/spec/workers/bulk_import_worker_spec.rb index 0d0b81d2ec0..61c33f123fa 100644 --- a/spec/workers/bulk_import_worker_spec.rb +++ b/spec/workers/bulk_import_worker_spec.rb @@ -72,7 +72,7 @@ RSpec.describe BulkImportWorker do entity_2 = create(:bulk_import_entity, :created, bulk_import: bulk_import) expect { subject.perform(bulk_import.id) } - .to change(BulkImports::Tracker, :count) + .to change { BulkImports::Tracker.count } .by(BulkImports::Groups::Stage.new(entity_1).pipelines.size * 2) expect(entity_1.trackers).not_to be_empty diff --git a/spec/workers/container_registry/migration/guard_worker_spec.rb b/spec/workers/container_registry/migration/guard_worker_spec.rb index d2bcfef2f5b..4ad2d5c300c 100644 --- a/spec/workers/container_registry/migration/guard_worker_spec.rb +++ b/spec/workers/container_registry/migration/guard_worker_spec.rb @@ -41,7 +41,7 @@ RSpec.describe ContainerRegistry::Migration::GuardWorker, :aggregate_failures do expect(ContainerRegistry::Migration).to receive(timeout).and_call_original expect { subject } - .to change(import_aborted_migrations, :count).by(1) + .to change { import_aborted_migrations.count }.by(1) .and change { stale_migration.reload.migration_state }.to('import_aborted') .and not_change { ongoing_migration.migration_state } end @@ -67,7 +67,7 @@ RSpec.describe ContainerRegistry::Migration::GuardWorker, :aggregate_failures do expect(ContainerRegistry::Migration).to receive(timeout).and_call_original expect { subject } - .to change(import_skipped_migrations, :count) + .to change { import_skipped_migrations.count } expect(stale_migration.reload.migration_state).to eq('import_skipped') expect(stale_migration.reload.migration_skipped_reason).to eq('migration_canceled') @@ -124,11 +124,11 @@ RSpec.describe ContainerRegistry::Migration::GuardWorker, :aggregate_failures do expect(worker).to receive(:log_extra_metadata_on_done).with(:aborted_stale_migrations_count, 1) expect { subject } - .to change(pre_importing_migrations, :count).by(-1) + .to change { pre_importing_migrations.count }.by(-1) .and not_change(pre_import_done_migrations, :count) .and not_change(importing_migrations, :count) .and not_change(import_done_migrations, :count) - .and change(import_aborted_migrations, :count).by(1) + .and change { import_aborted_migrations.count }.by(1) .and change { stale_migration.reload.migration_state }.from('pre_importing').to('import_aborted') .and not_change { ongoing_migration.migration_state } end @@ -223,10 +223,10 @@ RSpec.describe ContainerRegistry::Migration::GuardWorker, :aggregate_failures do expect { subject } .to not_change(pre_importing_migrations, :count) - .and change(pre_import_done_migrations, :count).by(-1) + .and change { pre_import_done_migrations.count }.by(-1) .and not_change(importing_migrations, :count) .and not_change(import_done_migrations, :count) - .and change(import_aborted_migrations, :count).by(1) + .and change { import_aborted_migrations.count }.by(1) .and change { stale_migration.reload.migration_state }.from('pre_import_done').to('import_aborted') .and not_change { ongoing_migration.migration_state } end @@ -252,9 +252,9 @@ RSpec.describe ContainerRegistry::Migration::GuardWorker, :aggregate_failures do expect { subject } .to not_change(pre_importing_migrations, :count) .and not_change(pre_import_done_migrations, :count) - .and change(importing_migrations, :count).by(-1) + .and change { importing_migrations.count }.by(-1) .and not_change(import_done_migrations, :count) - .and change(import_aborted_migrations, :count).by(1) + .and change { import_aborted_migrations.count }.by(1) .and change { stale_migration.reload.migration_state }.from('importing').to('import_aborted') .and not_change { ongoing_migration.migration_state } end diff --git a/spec/workers/incident_management/close_incident_worker_spec.rb b/spec/workers/incident_management/close_incident_worker_spec.rb index b0d284ba5db..c96bb4a3d1e 100644 --- a/spec/workers/incident_management/close_incident_worker_spec.rb +++ b/spec/workers/incident_management/close_incident_worker_spec.rb @@ -17,14 +17,14 @@ RSpec.describe IncidentManagement::CloseIncidentWorker do expect(service).to receive(:execute).with(issue, system_note: false).and_call_original end - expect { worker.perform(issue_id) }.to change(ResourceStateEvent, :count).by(1) + expect { worker.perform(issue_id) }.to change { ResourceStateEvent.count }.by(1) end shared_examples 'does not call the close issue service' do specify do expect(Issues::CloseService).not_to receive(:new) - expect { worker.perform(issue_id) }.not_to change(ResourceStateEvent, :count) + expect { worker.perform(issue_id) }.not_to change { ResourceStateEvent.count } end end @@ -58,7 +58,7 @@ RSpec.describe IncidentManagement::CloseIncidentWorker do end specify do - expect { worker.perform(issue_id) }.not_to change(ResourceStateEvent, :count) + expect { worker.perform(issue_id) }.not_to change { ResourceStateEvent.count } end end end diff --git a/spec/workers/incident_management/pager_duty/process_incident_worker_spec.rb b/spec/workers/incident_management/pager_duty/process_incident_worker_spec.rb index e2be91516b9..2b2903733a2 100644 --- a/spec/workers/incident_management/pager_duty/process_incident_worker_spec.rb +++ b/spec/workers/incident_management/pager_duty/process_incident_worker_spec.rb @@ -29,7 +29,7 @@ RSpec.describe IncidentManagement::PagerDuty::ProcessIncidentWorker do end it 'creates a GitLab issue' do - expect { perform }.to change(Issue, :count).by(1) + expect { perform }.to change { Issue.count }.by(1) end end @@ -41,7 +41,7 @@ RSpec.describe IncidentManagement::PagerDuty::ProcessIncidentWorker do end it 'does not create a GitLab issue' do - expect { perform }.not_to change(Issue, :count) + expect { perform }.not_to change { Issue.count } end it 'logs a warning' do diff --git a/spec/workers/issuable_export_csv_worker_spec.rb b/spec/workers/issuable_export_csv_worker_spec.rb index a18d10ad3df..a5172d916b6 100644 --- a/spec/workers/issuable_export_csv_worker_spec.rb +++ b/spec/workers/issuable_export_csv_worker_spec.rb @@ -13,7 +13,7 @@ RSpec.describe IssuableExportCsvWorker do let(:issuable_type) { :issue } it 'emails a CSV' do - expect { subject }.to change(ActionMailer::Base.deliveries, :size).by(1) + expect { subject }.to change { ActionMailer::Base.deliveries.size }.by(1) end it 'ensures that project_id is passed to issues_finder' do @@ -54,7 +54,7 @@ RSpec.describe IssuableExportCsvWorker do let(:issuable_type) { :merge_request } it 'emails a CSV' do - expect { subject }.to change(ActionMailer::Base.deliveries, :size).by(1) + expect { subject }.to change { ActionMailer::Base.deliveries.size }.by(1) end it 'calls the MR export service' do diff --git a/spec/workers/jira_connect/forward_event_worker_spec.rb b/spec/workers/jira_connect/forward_event_worker_spec.rb index 7de9952a1da..d3db07b8cb4 100644 --- a/spec/workers/jira_connect/forward_event_worker_spec.rb +++ b/spec/workers/jira_connect/forward_event_worker_spec.rb @@ -24,14 +24,14 @@ RSpec.describe JiraConnect::ForwardEventWorker do expect(Atlassian::Jwt).to receive(:encode).with({ iss: client_key, qsh: 'some_qsh' }, shared_secret).and_return('auth_token') expect(JiraConnect::RetryRequestWorker).to receive(:perform_async).with(event_url, 'auth_token') - expect { perform }.to change(JiraConnectInstallation, :count).by(-1) + expect { perform }.to change { JiraConnectInstallation.count }.by(-1) end context 'when installation does not exist' do let(:jira_connect_installation) { instance_double(JiraConnectInstallation, id: -1) } it 'does nothing' do - expect { perform }.not_to change(JiraConnectInstallation, :count) + expect { perform }.not_to change { JiraConnectInstallation.count } end end @@ -39,7 +39,7 @@ RSpec.describe JiraConnect::ForwardEventWorker do let!(:jira_connect_installation) { create(:jira_connect_installation) } it 'forwards the event including the auth header' do - expect { perform }.to change(JiraConnectInstallation, :count).by(-1) + expect { perform }.to change { JiraConnectInstallation.count }.by(-1) expect(JiraConnect::RetryRequestWorker).not_to receive(:perform_async) end diff --git a/spec/workers/metrics/dashboard/sync_dashboards_worker_spec.rb b/spec/workers/metrics/dashboard/sync_dashboards_worker_spec.rb index f151780ffd7..4b670a753e7 100644 --- a/spec/workers/metrics/dashboard/sync_dashboards_worker_spec.rb +++ b/spec/workers/metrics/dashboard/sync_dashboards_worker_spec.rb @@ -12,7 +12,7 @@ RSpec.describe Metrics::Dashboard::SyncDashboardsWorker do describe ".perform" do context 'with valid dashboard hash' do it 'imports metrics' do - expect { worker.perform(project.id) }.to change(PrometheusMetric, :count).by(3) + expect { worker.perform(project.id) }.to change { PrometheusMetric.count }.by(3) end it 'is idempotent' do @@ -32,7 +32,7 @@ RSpec.describe Metrics::Dashboard::SyncDashboardsWorker do end it 'does not import metrics' do - expect { worker.perform(project.id) }.not_to change(PrometheusMetric, :count) + expect { worker.perform(project.id) }.not_to change { PrometheusMetric.count } end it 'does not raise an error' do diff --git a/spec/workers/namespaces/process_sync_events_worker_spec.rb b/spec/workers/namespaces/process_sync_events_worker_spec.rb index 5e5179eab62..9f389089609 100644 --- a/spec/workers/namespaces/process_sync_events_worker_spec.rb +++ b/spec/workers/namespaces/process_sync_events_worker_spec.rb @@ -31,7 +31,7 @@ RSpec.describe Namespaces::ProcessSyncEventsWorker do expect(described_class).to receive(:perform_async).at_least(:twice).and_call_original expect do described_class.perform_async - end.to change(Namespaces::SyncEvent, :count).from(3).to(0) + end.to change { Namespaces::SyncEvent.count }.from(3).to(0) end end @@ -44,11 +44,11 @@ RSpec.describe Namespaces::ProcessSyncEventsWorker do end it 'consumes all sync events' do - expect { perform }.to change(Namespaces::SyncEvent, :count).from(5).to(0) + expect { perform }.to change { Namespaces::SyncEvent.count }.from(5).to(0) end it 'syncs namespace hierarchy traversal ids' do - expect { perform }.to change(Ci::NamespaceMirror, :all).to contain_exactly( + expect { perform }.to change { Ci::NamespaceMirror.all }.to contain_exactly( an_object_having_attributes(namespace_id: group1.id, traversal_ids: [group1.id]), an_object_having_attributes(namespace_id: group2.id, traversal_ids: [group1.id, group2.id]), an_object_having_attributes(namespace_id: group3.id, traversal_ids: [group1.id, group2.id, group3.id]) diff --git a/spec/workers/namespaces/schedule_aggregation_worker_spec.rb b/spec/workers/namespaces/schedule_aggregation_worker_spec.rb index f2fe53d6112..62f9be501cc 100644 --- a/spec/workers/namespaces/schedule_aggregation_worker_spec.rb +++ b/spec/workers/namespaces/schedule_aggregation_worker_spec.rb @@ -16,7 +16,7 @@ RSpec.describe Namespaces::ScheduleAggregationWorker, '#perform', :clean_gitlab_ expect do worker.perform(group.id) - end.not_to change(Namespace::AggregationSchedule, :count) + end.not_to change { Namespace::AggregationSchedule.count } end end @@ -26,7 +26,7 @@ RSpec.describe Namespaces::ScheduleAggregationWorker, '#perform', :clean_gitlab_ expect do worker.perform(group.id) - end.to change(Namespace::AggregationSchedule, :count).by(1) + end.to change { Namespace::AggregationSchedule.count }.by(1) expect(group.aggregation_schedule).to be_present end diff --git a/spec/workers/post_receive_spec.rb b/spec/workers/post_receive_spec.rb index d632ca39e44..65e9d2c1e6b 100644 --- a/spec/workers/post_receive_spec.rb +++ b/spec/workers/post_receive_spec.rb @@ -324,8 +324,8 @@ RSpec.describe PostReceive do expect do perform project.reload - end.to change(project, :last_activity_at) - .and change(project, :last_repository_updated_at) + end.to change { project.last_activity_at } + .and change { project.last_repository_updated_at } end end diff --git a/spec/workers/process_commit_worker_spec.rb b/spec/workers/process_commit_worker_spec.rb index 01c44399b0c..072c660bc2b 100644 --- a/spec/workers/process_commit_worker_spec.rb +++ b/spec/workers/process_commit_worker_spec.rb @@ -118,7 +118,7 @@ RSpec.describe ProcessCommitWorker do it 'creates Issue::CloseWorker jobs' do expect do worker.close_issues(project, user, user, commit, [issue]) - end.to change(Issues::CloseWorker.jobs, :size).by(1) + end.to change { Issues::CloseWorker.jobs.size }.by(1) end end diff --git a/spec/workers/projects/process_sync_events_worker_spec.rb b/spec/workers/projects/process_sync_events_worker_spec.rb index 202942ce905..a10a4797b2c 100644 --- a/spec/workers/projects/process_sync_events_worker_spec.rb +++ b/spec/workers/projects/process_sync_events_worker_spec.rb @@ -26,11 +26,11 @@ RSpec.describe Projects::ProcessSyncEventsWorker do end it 'consumes all sync events' do - expect { perform }.to change(Projects::SyncEvent, :count).from(2).to(0) + expect { perform }.to change { Projects::SyncEvent.count }.from(2).to(0) end it 'syncs project namespace id' do - expect { perform }.to change(Ci::ProjectMirror, :all).to contain_exactly( + expect { perform }.to change { Ci::ProjectMirror.all }.to contain_exactly( an_object_having_attributes(namespace_id: group.id) ) end diff --git a/spec/workers/releases/create_evidence_worker_spec.rb b/spec/workers/releases/create_evidence_worker_spec.rb index 743f2abc8a7..7e3edcfe44a 100644 --- a/spec/workers/releases/create_evidence_worker_spec.rb +++ b/spec/workers/releases/create_evidence_worker_spec.rb @@ -13,7 +13,7 @@ RSpec.describe Releases::CreateEvidenceWorker do expect(service).to receive(:execute).and_call_original end - expect { described_class.new.perform(release.id) }.to change(Releases::Evidence, :count).by(1) + expect { described_class.new.perform(release.id) }.to change { Releases::Evidence.count }.by(1) end it 'creates a new Evidence record with pipeline' do @@ -21,6 +21,6 @@ RSpec.describe Releases::CreateEvidenceWorker do expect(service).to receive(:execute).and_call_original end - expect { described_class.new.perform(release.id, pipeline.id) }.to change(Releases::Evidence, :count).by(1) + expect { described_class.new.perform(release.id, pipeline.id) }.to change { Releases::Evidence.count }.by(1) end end diff --git a/spec/workers/releases/manage_evidence_worker_spec.rb b/spec/workers/releases/manage_evidence_worker_spec.rb index 886fcd346eb..0004a4f4bfb 100644 --- a/spec/workers/releases/manage_evidence_worker_spec.rb +++ b/spec/workers/releases/manage_evidence_worker_spec.rb @@ -9,7 +9,7 @@ RSpec.describe Releases::ManageEvidenceWorker do specify :sidekiq_inline do aggregate_failures do expect(::Releases::CreateEvidenceService).not_to receive(:execute) - expect { described_class.new.perform }.to change(Releases::Evidence, :count).by(0) + expect { described_class.new.perform }.to change { Releases::Evidence.count }.by(0) end end end @@ -23,7 +23,7 @@ RSpec.describe Releases::ManageEvidenceWorker do expect(service).to receive(:execute).and_call_original end - expect { described_class.new.perform }.to change(Releases::Evidence, :count).by(1) + expect { described_class.new.perform }.to change { Releases::Evidence.count }.by(1) end end diff --git a/spec/workers/tasks_to_be_done/create_worker_spec.rb b/spec/workers/tasks_to_be_done/create_worker_spec.rb index a158872273f..e884a71933e 100644 --- a/spec/workers/tasks_to_be_done/create_worker_spec.rb +++ b/spec/workers/tasks_to_be_done/create_worker_spec.rb @@ -24,13 +24,13 @@ RSpec.describe TasksToBeDone::CreateWorker do .and_call_original end - expect { described_class.new.perform(*job_args) }.to change(Issue, :count).by(3) + expect { described_class.new.perform(*job_args) }.to change { Issue.count }.by(3) end end include_examples 'an idempotent worker' do it 'creates 3 task issues' do - expect { subject }.to change(Issue, :count).by(3) + expect { subject }.to change { Issue.count }.by(3) end end end diff --git a/spec/workers/update_highest_role_worker_spec.rb b/spec/workers/update_highest_role_worker_spec.rb index 0c8ee53da9a..cd127f26e95 100644 --- a/spec/workers/update_highest_role_worker_spec.rb +++ b/spec/workers/update_highest_role_worker_spec.rb @@ -10,7 +10,7 @@ RSpec.describe UpdateHighestRoleWorker, :clean_gitlab_redis_shared_state do describe '#perform' do context 'when user is not found' do it 'does not update or deletes any highest role', :aggregate_failures do - expect { worker.perform(-1) }.not_to change(UserHighestRole, :count) + expect { worker.perform(-1) }.not_to change { UserHighestRole.count } end end @@ -71,7 +71,7 @@ RSpec.describe UpdateHighestRoleWorker, :clean_gitlab_redis_shared_state do it 'does not delete a highest role' do user = create(:user, state: 'blocked') - expect { worker.perform(user.id) }.not_to change(UserHighestRole, :count) + expect { worker.perform(user.id) }.not_to change { UserHighestRole.count } end end end |