diff options
Diffstat (limited to 'spec/support')
234 files changed, 3573 insertions, 3550 deletions
diff --git a/spec/support/active_record_enum.rb b/spec/support/active_record_enum.rb index fb1189c7f17..1aa095b962c 100644 --- a/spec/support/active_record_enum.rb +++ b/spec/support/active_record_enum.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -shared_examples 'having unique enum values' do +shared_examples "having unique enum values" do described_class.defined_enums.each do |name, enum| it "has unique values in #{name.inspect}" do duplicated = enum.group_by(&:last).select { |key, value| value.size > 1 } diff --git a/spec/support/api/boards_shared_examples.rb b/spec/support/api/boards_shared_examples.rb index 592962ebf7c..bae84b4c72c 100644 --- a/spec/support/api/boards_shared_examples.rb +++ b/spec/support/api/boards_shared_examples.rb @@ -1,4 +1,4 @@ -shared_examples_for 'group and project boards' do |route_definition, ee = false| +shared_examples_for "group and project boards" do |route_definition, ee = false| let(:root_url) { route_definition.gsub(":id", board_parent.id.to_s) } before do @@ -30,16 +30,16 @@ shared_examples_for 'group and project boards' do |route_definition, ee = false| expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers - expect_schema_match_for(response, 'public_api/v4/boards', ee) + expect_schema_match_for(response, "public_api/v4/boards", ee) end describe "GET #{route_definition}/:board_id" do let(:url) { "#{root_url}/#{board.id}" } - it 'get a single board by id' do + it "get a single board by id" do get api(url, user) - expect_schema_match_for(response, 'public_api/v4/board', ee) + expect_schema_match_for(response, "public_api/v4/board", ee) end end end @@ -48,17 +48,17 @@ shared_examples_for 'group and project boards' do |route_definition, ee = false| describe "GET #{route_definition}/:board_id/lists" do let(:url) { "#{root_url}/#{board.id}/lists" } - it 'returns issue board lists' do + it "returns issue board lists" do get api(url, user) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(2) - expect(json_response.first['label']['name']).to eq(dev_label.title) + expect(json_response.first["label"]["name"]).to eq(dev_label.title) end - it 'returns 404 if board not found' do + it "returns 404 if board not found" do get api("#{root_url}/22343/lists", user) expect(response).to have_gitlab_http_status(404) @@ -68,16 +68,16 @@ shared_examples_for 'group and project boards' do |route_definition, ee = false| describe "GET #{route_definition}/:board_id/lists/:list_id" do let(:url) { "#{root_url}/#{board.id}/lists" } - it 'returns a list' do + it "returns a list" do get api("#{url}/#{dev_list.id}", user) expect(response).to have_gitlab_http_status(200) - expect(json_response['id']).to eq(dev_list.id) - expect(json_response['label']['name']).to eq(dev_label.title) - expect(json_response['position']).to eq(1) + expect(json_response["id"]).to eq(dev_list.id) + expect(json_response["label"]["name"]).to eq(dev_label.title) + expect(json_response["position"]).to eq(1) end - it 'returns 404 if list not found' do + it "returns 404 if list not found" do get api("#{url}/5324", user) expect(response).to have_gitlab_http_status(404) @@ -87,22 +87,22 @@ shared_examples_for 'group and project boards' do |route_definition, ee = false| describe "POST #{route_definition}/lists" do let(:url) { "#{root_url}/#{board.id}/lists" } - it 'creates a new issue board list for labels' do - post api(url, user), params: { label_id: ux_label.id } + it "creates a new issue board list for labels" do + post api(url, user), params: {label_id: ux_label.id} expect(response).to have_gitlab_http_status(201) - expect(json_response['label']['name']).to eq(ux_label.title) - expect(json_response['position']).to eq(3) + expect(json_response["label"]["name"]).to eq(ux_label.title) + expect(json_response["position"]).to eq(3) end - it 'returns 400 when creating a new list if label_id is invalid' do - post api(url, user), params: { label_id: 23423 } + it "returns 400 when creating a new list if label_id is invalid" do + post api(url, user), params: {label_id: 23423} expect(response).to have_gitlab_http_status(400) end - it 'returns 403 for members with guest role' do - put api("#{url}/#{test_list.id}", guest), params: { position: 1 } + it "returns 403 for members with guest role" do + put api("#{url}/#{test_list.id}", guest), params: {position: 1} expect(response).to have_gitlab_http_status(403) end @@ -112,20 +112,20 @@ shared_examples_for 'group and project boards' do |route_definition, ee = false| let(:url) { "#{root_url}/#{board.id}/lists" } it "updates a list" do - put api("#{url}/#{test_list.id}", user), params: { position: 1 } + put api("#{url}/#{test_list.id}", user), params: {position: 1} expect(response).to have_gitlab_http_status(200) - expect(json_response['position']).to eq(1) + expect(json_response["position"]).to eq(1) end it "returns 404 error if list id not found" do - put api("#{url}/44444", user), params: { position: 1 } + put api("#{url}/44444", user), params: {position: 1} expect(response).to have_gitlab_http_status(404) end it "returns 403 for members with guest role" do - put api("#{url}/#{test_list.id}", guest), params: { position: 1 } + put api("#{url}/#{test_list.id}", guest), params: {position: 1} expect(response).to have_gitlab_http_status(403) end @@ -169,7 +169,7 @@ shared_examples_for 'group and project boards' do |route_definition, ee = false| expect(response).to have_gitlab_http_status(204) end - it_behaves_like '412 response' do + it_behaves_like "412 response" do let(:request) { api("#{url}/#{dev_list.id}", owner) } end end diff --git a/spec/support/api/issues_resolving_discussions_shared_examples.rb b/spec/support/api/issues_resolving_discussions_shared_examples.rb index d2d6260dfa8..1323a807e5c 100644 --- a/spec/support/api/issues_resolving_discussions_shared_examples.rb +++ b/spec/support/api/issues_resolving_discussions_shared_examples.rb @@ -1,15 +1,15 @@ -shared_examples 'creating an issue resolving discussions through the API' do - it 'creates a new project issue' do +shared_examples "creating an issue resolving discussions through the API" do + it "creates a new project issue" do expect(response).to have_gitlab_http_status(:created) end - it 'resolves the discussions in a merge request' do + it "resolves the discussions in a merge request" do discussion.first_note.reload expect(discussion.resolved?).to be(true) end - it 'assigns a description to the issue mentioning the merge request' do - expect(json_response['description']).to include(merge_request.to_reference) + it "assigns a description to the issue mentioning the merge request" do + expect(json_response["description"]).to include(merge_request.to_reference) end end diff --git a/spec/support/api/members_shared_examples.rb b/spec/support/api/members_shared_examples.rb index 8d910e52eda..4f662af6efc 100644 --- a/spec/support/api/members_shared_examples.rb +++ b/spec/support/api/members_shared_examples.rb @@ -1,9 +1,9 @@ -shared_examples 'a 404 response when source is private' do +shared_examples "a 404 response when source is private" do before do source.update_column(:visibility_level, Gitlab::VisibilityLevel::PRIVATE) end - it 'returns 404' do + it "returns 404" do route expect(response).to have_gitlab_http_status(404) diff --git a/spec/support/api/milestones_shared_examples.rb b/spec/support/api/milestones_shared_examples.rb index 5f709831ce1..8c7db674bf3 100644 --- a/spec/support/api/milestones_shared_examples.rb +++ b/spec/support/api/milestones_shared_examples.rb @@ -1,114 +1,114 @@ -shared_examples_for 'group and project milestones' do |route_definition| +shared_examples_for "group and project milestones" do |route_definition| let(:resource_route) { "#{route}/#{milestone.id}" } - let(:label_1) { create(:label, title: 'label_1', project: project, priority: 1) } - let(:label_2) { create(:label, title: 'label_2', project: project, priority: 2) } - let(:label_3) { create(:label, title: 'label_3', project: project) } + let(:label_1) { create(:label, title: "label_1", project: project, priority: 1) } + let(:label_2) { create(:label, title: "label_2", project: project, priority: 2) } + let(:label_3) { create(:label, title: "label_3", project: project) } let(:merge_request) { create(:merge_request, source_project: project) } let(:another_merge_request) { create(:merge_request, :simple, source_project: project) } describe "GET #{route_definition}" do - it 'returns milestones list' do + it "returns milestones list" do get api(route, user) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array - expect(json_response.first['title']).to eq(milestone.title) + expect(json_response.first["title"]).to eq(milestone.title) end - it 'returns a 401 error if user not authenticated' do + it "returns a 401 error if user not authenticated" do get api(route) expect(response).to have_gitlab_http_status(401) end - it 'returns an array of active milestones' do + it "returns an array of active milestones" do get api("#{route}/?state=active", user) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.first['id']).to eq(milestone.id) + expect(json_response.first["id"]).to eq(milestone.id) end - it 'returns an array of closed milestones' do + it "returns an array of closed milestones" do get api("#{route}/?state=closed", user) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.first['id']).to eq(closed_milestone.id) + expect(json_response.first["id"]).to eq(closed_milestone.id) end - it 'returns an array of milestones specified by iids' do + it "returns an array of milestones specified by iids" do other_milestone = create(:milestone, project: try(:project), group: try(:group)) - get api(route, user), params: { iids: [closed_milestone.iid, other_milestone.iid] } + get api(route, user), params: {iids: [closed_milestone.iid, other_milestone.iid]} expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.length).to eq(2) - expect(json_response.map { |m| m['id'] }).to match_array([closed_milestone.id, other_milestone.id]) + expect(json_response.map { |m| m["id"] }).to match_array([closed_milestone.id, other_milestone.id]) end - it 'does not return any milestone if none found' do - get api(route, user), params: { iids: [Milestone.maximum(:iid).succ] } + it "does not return any milestone if none found" do + get api(route, user), params: {iids: [Milestone.maximum(:iid).succ]} expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.length).to eq(0) end - it 'returns a milestone by iids array' do + it "returns a milestone by iids array" do get api("#{route}?iids=#{closed_milestone.iid}", user) expect(response.status).to eq 200 expect(response).to include_pagination_headers expect(json_response.size).to eq(1) expect(json_response.size).to eq(1) - expect(json_response.first['title']).to eq closed_milestone.title - expect(json_response.first['id']).to eq closed_milestone.id + expect(json_response.first["title"]).to eq closed_milestone.title + expect(json_response.first["id"]).to eq closed_milestone.id end - it 'returns a milestone by searching for title' do - get api(route, user), params: { search: 'version2' } + it "returns a milestone by searching for title" do + get api(route, user), params: {search: "version2"} expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response.size).to eq(1) - expect(json_response.first['title']).to eq milestone.title - expect(json_response.first['id']).to eq milestone.id + expect(json_response.first["title"]).to eq milestone.title + expect(json_response.first["id"]).to eq milestone.id end - it 'returns a milestones by searching for description' do - get api(route, user), params: { search: 'open' } + it "returns a milestones by searching for description" do + get api(route, user), params: {search: "open"} expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response.size).to eq(1) - expect(json_response.first['title']).to eq milestone.title - expect(json_response.first['id']).to eq milestone.id + expect(json_response.first["title"]).to eq milestone.title + expect(json_response.first["id"]).to eq milestone.id end end describe "GET #{route_definition}/:milestone_id" do - it 'returns a milestone by id' do + it "returns a milestone by id" do get api(resource_route, user) expect(response).to have_gitlab_http_status(200) - expect(json_response['title']).to eq(milestone.title) - expect(json_response['iid']).to eq(milestone.iid) + expect(json_response["title"]).to eq(milestone.title) + expect(json_response["iid"]).to eq(milestone.iid) end - it 'returns 401 error if user not authenticated' do + it "returns 401 error if user not authenticated" do get api(resource_route) expect(response).to have_gitlab_http_status(401) end - it 'returns a 404 error if milestone id not found' do + it "returns a 404 error if milestone id not found" do get api("#{route}/1234", user) expect(response).to have_gitlab_http_status(404) @@ -116,76 +116,76 @@ shared_examples_for 'group and project milestones' do |route_definition| end describe "POST #{route_definition}" do - it 'creates a new milestone' do - post api(route, user), params: { title: 'new milestone' } + it "creates a new milestone" do + post api(route, user), params: {title: "new milestone"} expect(response).to have_gitlab_http_status(201) - expect(json_response['title']).to eq('new milestone') - expect(json_response['description']).to be_nil + expect(json_response["title"]).to eq("new milestone") + expect(json_response["description"]).to be_nil end - it 'creates a new milestone with description and dates' do - post api(route, user), params: { title: 'new milestone', description: 'release', due_date: '2013-03-02', start_date: '2013-02-02' } + it "creates a new milestone with description and dates" do + post api(route, user), params: {title: "new milestone", description: "release", due_date: "2013-03-02", start_date: "2013-02-02"} expect(response).to have_gitlab_http_status(201) - expect(json_response['description']).to eq('release') - expect(json_response['due_date']).to eq('2013-03-02') - expect(json_response['start_date']).to eq('2013-02-02') + expect(json_response["description"]).to eq("release") + expect(json_response["due_date"]).to eq("2013-03-02") + expect(json_response["start_date"]).to eq("2013-02-02") end - it 'returns a 400 error if title is missing' do + it "returns a 400 error if title is missing" do post api(route, user) expect(response).to have_gitlab_http_status(400) end - it 'returns a 400 error if params are invalid (duplicate title)' do - post api(route, user), params: { title: milestone.title, description: 'release', due_date: '2013-03-02' } + it "returns a 400 error if params are invalid (duplicate title)" do + post api(route, user), params: {title: milestone.title, description: "release", due_date: "2013-03-02"} expect(response).to have_gitlab_http_status(400) end - it 'creates a new milestone with reserved html characters' do - post api(route, user), params: { title: 'foo & bar 1.1 -> 2.2' } + it "creates a new milestone with reserved html characters" do + post api(route, user), params: {title: "foo & bar 1.1 -> 2.2"} expect(response).to have_gitlab_http_status(201) - expect(json_response['title']).to eq('foo & bar 1.1 -> 2.2') - expect(json_response['description']).to be_nil + expect(json_response["title"]).to eq("foo & bar 1.1 -> 2.2") + expect(json_response["description"]).to be_nil end end describe "PUT #{route_definition}/:milestone_id" do - it 'updates a milestone' do - put api(resource_route, user), params: { title: 'updated title' } + it "updates a milestone" do + put api(resource_route, user), params: {title: "updated title"} expect(response).to have_gitlab_http_status(200) - expect(json_response['title']).to eq('updated title') + expect(json_response["title"]).to eq("updated title") end - it 'removes a due date if nil is passed' do + it "removes a due date if nil is passed" do milestone.update!(due_date: "2016-08-05") - put api(resource_route, user), params: { due_date: nil } + put api(resource_route, user), params: {due_date: nil} expect(response).to have_gitlab_http_status(200) - expect(json_response['due_date']).to be_nil + expect(json_response["due_date"]).to be_nil end - it 'returns a 404 error if milestone id not found' do - put api("#{route}/1234", user), params: { title: 'updated title' } + it "returns a 404 error if milestone id not found" do + put api("#{route}/1234", user), params: {title: "updated title"} expect(response).to have_gitlab_http_status(404) end - it 'closes milestone' do - put api(resource_route, user), params: { state_event: 'close' } + it "closes milestone" do + put api(resource_route, user), params: {state_event: "close"} expect(response).to have_gitlab_http_status(200) - expect(json_response['state']).to eq('closed') + expect(json_response["state"]).to eq("closed") end - it 'updates milestone with only start date' do - put api(resource_route, user), params: { start_date: Date.tomorrow } + it "updates milestone with only start date" do + put api(resource_route, user), params: {start_date: Date.tomorrow} expect(response).to have_gitlab_http_status(200) end @@ -201,7 +201,7 @@ shared_examples_for 'group and project milestones' do |route_definition| expect(response).to have_gitlab_http_status(403) end - it 'deletes the milestone when the user has developer access to the project' do + it "deletes the milestone when the user has developer access to the project" do delete api(resource_route, user) expect(project.milestones.find_by_id(milestone.id)).to be_nil @@ -215,41 +215,41 @@ shared_examples_for 'group and project milestones' do |route_definition| before do milestone.issues << create(:issue, project: project) end - it 'returns issues for a particular milestone' do + it "returns issues for a particular milestone" do get api(issues_route, user) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array - expect(json_response.first['milestone']['title']).to eq(milestone.title) + expect(json_response.first["milestone"]["title"]).to eq(milestone.title) end - it 'returns issues sorted by label priority' do + it "returns issues sorted by label priority" do issue_1 = create(:labeled_issue, project: project, milestone: milestone, labels: [label_3]) issue_2 = create(:labeled_issue, project: project, milestone: milestone, labels: [label_1]) issue_3 = create(:labeled_issue, project: project, milestone: milestone, labels: [label_2]) get api(issues_route, user) - expect(json_response.first['id']).to eq(issue_2.id) - expect(json_response.second['id']).to eq(issue_3.id) - expect(json_response.third['id']).to eq(issue_1.id) + expect(json_response.first["id"]).to eq(issue_2.id) + expect(json_response.second["id"]).to eq(issue_3.id) + expect(json_response.third["id"]).to eq(issue_1.id) end - it 'matches V4 response schema for a list of issues' do + it "matches V4 response schema for a list of issues" do get api(issues_route, user) expect(response).to have_gitlab_http_status(200) - expect(response).to match_response_schema('public_api/v4/issues') + expect(response).to match_response_schema("public_api/v4/issues") end - it 'returns a 401 error if user not authenticated' do + it "returns a 401 error if user not authenticated" do get api(issues_route) expect(response).to have_gitlab_http_status(401) end - describe 'confidential issues' do + describe "confidential issues" do let!(:public_project) { create(:project, :public) } let!(:context_group) { try(:group) } let!(:milestone) do @@ -273,7 +273,7 @@ shared_examples_for 'group and project milestones' do |route_definition| milestone.issues << issue << confidential_issue end - it 'returns confidential issues to team members' do + it "returns confidential issues to team members" do get api(issues_route, user) expect(response).to have_gitlab_http_status(200) @@ -281,10 +281,10 @@ shared_examples_for 'group and project milestones' do |route_definition| expect(json_response).to be_an Array # 2 for projects, 3 for group(which has another project with an issue) expect(json_response.size).to be_between(2, 3) - expect(json_response.map { |issue| issue['id'] }).to include(issue.id, confidential_issue.id) + expect(json_response.map { |issue| issue["id"] }).to include(issue.id, confidential_issue.id) end - it 'does not return confidential issues to team members with guest role' do + it "does not return confidential issues to team members with guest role" do member = create(:user) public_project.add_guest(member) @@ -294,20 +294,20 @@ shared_examples_for 'group and project milestones' do |route_definition| expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.size).to eq(1) - expect(json_response.map { |issue| issue['id'] }).to include(issue.id) + expect(json_response.map { |issue| issue["id"] }).to include(issue.id) end - it 'does not return confidential issues to regular users' do + it "does not return confidential issues to regular users" do get api(issues_route, create(:user)) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.size).to eq(1) - expect(json_response.map { |issue| issue['id'] }).to include(issue.id) + expect(json_response.map { |issue| issue["id"] }).to include(issue.id) end - it 'returns issues ordered by label priority' do + it "returns issues ordered by label priority" do issue.labels << label_2 confidential_issue.labels << label_1 @@ -318,8 +318,8 @@ shared_examples_for 'group and project milestones' do |route_definition| expect(json_response).to be_an Array # 2 for projects, 3 for group(which has another project with an issue) expect(json_response.size).to be_between(2, 3) - expect(json_response.first['id']).to eq(confidential_issue.id) - expect(json_response.second['id']).to eq(issue.id) + expect(json_response.first["id"]).to eq(confidential_issue.id) + expect(json_response.second["id"]).to eq(issue.id) end end end @@ -331,7 +331,7 @@ shared_examples_for 'group and project milestones' do |route_definition| milestone.merge_requests << merge_request end - it 'returns merge_requests for a particular milestone' do + it "returns merge_requests for a particular milestone" do # eager-load another_merge_request another_merge_request get api(merge_requests_route, user) @@ -339,23 +339,23 @@ shared_examples_for 'group and project milestones' do |route_definition| expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.size).to eq(1) - expect(json_response.first['title']).to eq(merge_request.title) - expect(json_response.first['milestone']['title']).to eq(milestone.title) + expect(json_response.first["title"]).to eq(merge_request.title) + expect(json_response.first["milestone"]["title"]).to eq(milestone.title) end - it 'returns merge_requests sorted by label priority' do - merge_request_1 = create(:labeled_merge_request, source_branch: 'branch_1', source_project: project, milestone: milestone, labels: [label_2]) - merge_request_2 = create(:labeled_merge_request, source_branch: 'branch_2', source_project: project, milestone: milestone, labels: [label_1]) - merge_request_3 = create(:labeled_merge_request, source_branch: 'branch_3', source_project: project, milestone: milestone, labels: [label_3]) + it "returns merge_requests sorted by label priority" do + merge_request_1 = create(:labeled_merge_request, source_branch: "branch_1", source_project: project, milestone: milestone, labels: [label_2]) + merge_request_2 = create(:labeled_merge_request, source_branch: "branch_2", source_project: project, milestone: milestone, labels: [label_1]) + merge_request_3 = create(:labeled_merge_request, source_branch: "branch_3", source_project: project, milestone: milestone, labels: [label_3]) get api(merge_requests_route, user) - expect(json_response.first['id']).to eq(merge_request_2.id) - expect(json_response.second['id']).to eq(merge_request_1.id) - expect(json_response.third['id']).to eq(merge_request_3.id) + expect(json_response.first["id"]).to eq(merge_request_2.id) + expect(json_response.second["id"]).to eq(merge_request_1.id) + expect(json_response.third["id"]).to eq(merge_request_3.id) end - it 'returns a 404 error if milestone id not found' do + it "returns a 404 error if milestone id not found" do not_found_route = "#{route}/1234/merge_requests" get api(not_found_route, user) @@ -363,20 +363,20 @@ shared_examples_for 'group and project milestones' do |route_definition| expect(response).to have_gitlab_http_status(404) end - it 'returns a 404 if the user has no access to the milestone' do + it "returns a 404 if the user has no access to the milestone" do new_user = create :user get api(merge_requests_route, new_user) expect(response).to have_gitlab_http_status(404) end - it 'returns a 401 error if user not authenticated' do + it "returns a 401 error if user not authenticated" do get api(merge_requests_route) expect(response).to have_gitlab_http_status(401) end - it 'returns merge_requests ordered by position asc' do + it "returns merge_requests ordered by position asc" do milestone.merge_requests << another_merge_request another_merge_request.labels << label_1 merge_request.labels << label_2 @@ -387,8 +387,8 @@ shared_examples_for 'group and project milestones' do |route_definition| expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.size).to eq(2) - expect(json_response.first['id']).to eq(another_merge_request.id) - expect(json_response.second['id']).to eq(merge_request.id) + expect(json_response.first["id"]).to eq(another_merge_request.id) + expect(json_response.second["id"]).to eq(merge_request.id) end end end diff --git a/spec/support/api/repositories_shared_context.rb b/spec/support/api/repositories_shared_context.rb index f1341804e56..a410e71ccb5 100644 --- a/spec/support/api/repositories_shared_context.rb +++ b/spec/support/api/repositories_shared_context.rb @@ -1,4 +1,4 @@ -shared_context 'disabled repository' do +shared_context "disabled repository" do before do project.project_feature.update!( repository_access_level: ProjectFeature::DISABLED, diff --git a/spec/support/api/schema_matcher.rb b/spec/support/api/schema_matcher.rb index 6591d56e473..51fd655cd4d 100644 --- a/spec/support/api/schema_matcher.rb +++ b/spec/support/api/schema_matcher.rb @@ -1,13 +1,14 @@ module SchemaPath - def self.expand(schema, dir = '') - Rails.root.join('spec', dir, "fixtures/api/schemas/#{schema}.json").to_s + def self.expand(schema, dir = "") + Rails.root.join("spec", dir, "fixtures/api/schemas/#{schema}.json").to_s end end -RSpec::Matchers.define :match_response_schema do |schema, dir: '', **options| +RSpec::Matchers.define :match_response_schema do |schema, dir: "", **options| match do |response| @errors = JSON::Validator.fully_validate( - SchemaPath.expand(schema, dir), response.body, options) + SchemaPath.expand(schema, dir), response.body, options + ) @errors.empty? end @@ -18,7 +19,7 @@ RSpec::Matchers.define :match_response_schema do |schema, dir: '', **options| end end -RSpec::Matchers.define :match_schema do |schema, dir: '', **options| +RSpec::Matchers.define :match_schema do |schema, dir: "", **options| match do |data| JSON::Validator.validate!(SchemaPath.expand(schema, dir), data, options) end diff --git a/spec/support/api/scopes/read_user_shared_examples.rb b/spec/support/api/scopes/read_user_shared_examples.rb index 683234264a8..355fe76a3b0 100644 --- a/spec/support/api/scopes/read_user_shared_examples.rb +++ b/spec/support/api/scopes/read_user_shared_examples.rb @@ -1,9 +1,9 @@ shared_examples_for 'allows the "read_user" scope' do |api_version| - let(:version) { api_version || 'v4' } + let(:version) { api_version || "v4" } - context 'for personal access tokens' do + context "for personal access tokens" do context 'when the requesting token has the "api" scope' do - let(:token) { create(:personal_access_token, scopes: ['api'], user: user) } + let(:token) { create(:personal_access_token, scopes: ["api"], user: user) } it 'returns a "200" response' do get api_call.call(path, user, personal_access_token: token, version: version) @@ -13,7 +13,7 @@ shared_examples_for 'allows the "read_user" scope' do |api_version| end context 'when the requesting token has the "read_user" scope' do - let(:token) { create(:personal_access_token, scopes: ['read_user'], user: user) } + let(:token) { create(:personal_access_token, scopes: ["read_user"], user: user) } it 'returns a "200" response' do get api_call.call(path, user, personal_access_token: token, version: version) @@ -22,8 +22,8 @@ shared_examples_for 'allows the "read_user" scope' do |api_version| end end - context 'when the requesting token does not have any required scope' do - let(:token) { create(:personal_access_token, scopes: ['read_registry'], user: user) } + context "when the requesting token does not have any required scope" do + let(:token) { create(:personal_access_token, scopes: ["read_registry"], user: user) } before do stub_container_registry_config(enabled: true) @@ -37,7 +37,7 @@ shared_examples_for 'allows the "read_user" scope' do |api_version| end end - context 'for doorkeeper (OAuth) tokens' do + context "for doorkeeper (OAuth) tokens" do let!(:application) { Doorkeeper::Application.create!(name: "MyApp", redirect_uri: "https://app.com", owner: user) } context 'when the requesting token has the "api" scope' do @@ -60,7 +60,7 @@ shared_examples_for 'allows the "read_user" scope' do |api_version| end end - context 'when the requesting token does not have any required scope' do + context "when the requesting token does not have any required scope" do let!(:token) { Doorkeeper::AccessToken.create! application_id: application.id, resource_owner_id: user.id, scopes: "invalid" } it 'returns a "403" response' do @@ -74,7 +74,7 @@ end shared_examples_for 'does not allow the "read_user" scope' do context 'when the requesting token has the "read_user" scope' do - let(:token) { create(:personal_access_token, scopes: ['read_user'], user: user) } + let(:token) { create(:personal_access_token, scopes: ["read_user"], user: user) } it 'returns a "403" response' do post api_call.call(path, user, personal_access_token: token), params: attributes_for(:user, projects_limit: 3) diff --git a/spec/support/api/time_tracking_shared_examples.rb b/spec/support/api/time_tracking_shared_examples.rb index e883d33f671..74868dfe845 100644 --- a/spec/support/api/time_tracking_shared_examples.rb +++ b/spec/support/api/time_tracking_shared_examples.rb @@ -1,144 +1,144 @@ -shared_examples 'an unauthorized API user' do +shared_examples "an unauthorized API user" do it { is_expected.to eq(403) } end -shared_examples 'time tracking endpoints' do |issuable_name| +shared_examples "time tracking endpoints" do |issuable_name| issuable_collection_name = issuable_name.pluralize describe "POST /projects/:id/#{issuable_collection_name}/:#{issuable_name}_id/time_estimate" do - context 'with an unauthorized user' do - subject { post(api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", non_member), params: { duration: '1w' }) } + context "with an unauthorized user" do + subject { post(api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", non_member), params: {duration: "1w"}) } - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end it "sets the time estimate for #{issuable_name}" do - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: { duration: '1w' } + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: {duration: "1w"} expect(response).to have_gitlab_http_status(200) - expect(json_response['human_time_estimate']).to eq('1w') + expect(json_response["human_time_estimate"]).to eq("1w") end - describe 'updating the current estimate' do + describe "updating the current estimate" do before do - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: { duration: '1w' } + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: {duration: "1w"} end - context 'when duration has a bad format' do - it 'does not modify the original estimate' do - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: { duration: 'foo' } + context "when duration has a bad format" do + it "does not modify the original estimate" do + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: {duration: "foo"} expect(response).to have_gitlab_http_status(400) - expect(issuable.reload.human_time_estimate).to eq('1w') + expect(issuable.reload.human_time_estimate).to eq("1w") end end - context 'with a valid duration' do - it 'updates the estimate' do - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: { duration: '3w1h' } + context "with a valid duration" do + it "updates the estimate" do + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_estimate", user), params: {duration: "3w1h"} expect(response).to have_gitlab_http_status(200) - expect(issuable.reload.human_time_estimate).to eq('3w 1h') + expect(issuable.reload.human_time_estimate).to eq("3w 1h") end end end end describe "POST /projects/:id/#{issuable_collection_name}/:#{issuable_name}_id/reset_time_estimate" do - context 'with an unauthorized user' do + context "with an unauthorized user" do subject { post(api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/reset_time_estimate", non_member)) } - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end it "resets the time estimate for #{issuable_name}" do post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/reset_time_estimate", user) expect(response).to have_gitlab_http_status(200) - expect(json_response['time_estimate']).to eq(0) + expect(json_response["time_estimate"]).to eq(0) end end describe "POST /projects/:id/#{issuable_collection_name}/:#{issuable_name}_id/add_spent_time" do - context 'with an unauthorized user' do + context "with an unauthorized user" do subject do - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", non_member), params: { duration: '2h' } + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", non_member), params: {duration: "2h"} end - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end it "add spent time for #{issuable_name}" do Timecop.travel(1.minute.from_now) do - expect do - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", user), params: { duration: '2h' } - end.to change { issuable.reload.updated_at } + expect { + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", user), params: {duration: "2h"} + }.to change { issuable.reload.updated_at } end expect(response).to have_gitlab_http_status(201) - expect(json_response['human_total_time_spent']).to eq('2h') + expect(json_response["human_total_time_spent"]).to eq("2h") end - context 'when subtracting time' do - it 'subtracts time of the total spent time' do + context "when subtracting time" do + it "subtracts time of the total spent time" do Timecop.travel(1.minute.from_now) do - expect do - issuable.update!(spend_time: { duration: 7200, user_id: user.id }) - end.to change { issuable.reload.updated_at } + expect { + issuable.update!(spend_time: {duration: 7200, user_id: user.id}) + }.to change { issuable.reload.updated_at } end - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", user), params: { duration: '-1h' } + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", user), params: {duration: "-1h"} expect(response).to have_gitlab_http_status(201) - expect(json_response['total_time_spent']).to eq(3600) + expect(json_response["total_time_spent"]).to eq(3600) end end - context 'when time to subtract is greater than the total spent time' do - it 'does not modify the total time spent' do - issuable.update!(spend_time: { duration: 7200, user_id: user.id }) + context "when time to subtract is greater than the total spent time" do + it "does not modify the total time spent" do + issuable.update!(spend_time: {duration: 7200, user_id: user.id}) Timecop.travel(1.minute.from_now) do - expect do - post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", user), params: { duration: '-1w' } - end.not_to change { issuable.reload.updated_at } + expect { + post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/add_spent_time", user), params: {duration: "-1w"} + }.not_to change { issuable.reload.updated_at } end expect(response).to have_gitlab_http_status(400) - expect(json_response['message']['time_spent'].first).to match(/exceeds the total time spent/) + expect(json_response["message"]["time_spent"].first).to match(/exceeds the total time spent/) end end end describe "POST /projects/:id/#{issuable_collection_name}/:#{issuable_name}_id/reset_spent_time" do - context 'with an unauthorized user' do + context "with an unauthorized user" do subject { post(api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/reset_spent_time", non_member)) } - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end it "resets spent time for #{issuable_name}" do Timecop.travel(1.minute.from_now) do - expect do + expect { post api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/reset_spent_time", user) - end.to change { issuable.reload.updated_at } + }.to change { issuable.reload.updated_at } end expect(response).to have_gitlab_http_status(200) - expect(json_response['total_time_spent']).to eq(0) + expect(json_response["total_time_spent"]).to eq(0) end end describe "GET /projects/:id/#{issuable_collection_name}/:#{issuable_name}_id/time_stats" do it "returns the time stats for #{issuable_name}" do - issuable.update!(spend_time: { duration: 1800, user_id: user.id }, + issuable.update!(spend_time: {duration: 1800, user_id: user.id}, time_estimate: 3600) get api("/projects/#{project.id}/#{issuable_collection_name}/#{issuable.iid}/time_stats", user) expect(response).to have_gitlab_http_status(200) - expect(json_response['total_time_spent']).to eq(1800) - expect(json_response['time_estimate']).to eq(3600) + expect(json_response["total_time_spent"]).to eq(1800) + expect(json_response["time_estimate"]).to eq(3600) end end end diff --git a/spec/support/banzai/reference_filter_shared_examples.rb b/spec/support/banzai/reference_filter_shared_examples.rb index 476d80f3a93..38d14bac8c6 100644 --- a/spec/support/banzai/reference_filter_shared_examples.rb +++ b/spec/support/banzai/reference_filter_shared_examples.rb @@ -2,11 +2,11 @@ # # Requires a reference: # let(:reference) { '#42' } -shared_examples 'a reference containing an element node' do - let(:inner_html) { 'element <code>node</code> inside' } - let(:reference_with_element) { %{<a href="#{reference}">#{inner_html}</a>} } +shared_examples "a reference containing an element node" do + let(:inner_html) { "element <code>node</code> inside" } + let(:reference_with_element) { %(<a href="#{reference}">#{inner_html}</a>) } - it 'does not escape inner html' do + it "does not escape inner html" do doc = reference_filter(reference_with_element) expect(doc.children.first.inner_html).to eq(inner_html) end @@ -16,69 +16,69 @@ end # subject { create(:user) } # let(:reference) { subject.to_reference } # let(:subject_name) { 'user' } -shared_examples 'user reference or project reference' do - shared_examples 'it contains a data- attribute' do - it 'includes a data- attribute' do +shared_examples "user reference or project reference" do + shared_examples "it contains a data- attribute" do + it "includes a data- attribute" do doc = reference_filter("Hey #{reference}") - link = doc.css('a').first + link = doc.css("a").first expect(link).to have_attribute("data-#{subject_name}") expect(link.attr("data-#{subject_name}")).to eq subject.id.to_s end end - context 'mentioning a resource' do - it_behaves_like 'a reference containing an element node' - it_behaves_like 'it contains a data- attribute' + context "mentioning a resource" do + it_behaves_like "a reference containing an element node" + it_behaves_like "it contains a data- attribute" it "links to a resource" do doc = reference_filter("Hey #{reference}") - expect(doc.css('a').first.attr('href')).to eq urls.send("#{subject_name}_url", subject) + expect(doc.css("a").first.attr("href")).to eq urls.send("#{subject_name}_url", subject) end - it 'links to a resource with a period' do - subject = create(subject_name.to_sym, name: 'alphA.Beta') + it "links to a resource with a period" do + subject = create(subject_name.to_sym, name: "alphA.Beta") doc = reference_filter("Hey #{get_reference(subject)}") - expect(doc.css('a').length).to eq 1 + expect(doc.css("a").length).to eq 1 end - it 'links to a resource with an underscore' do - subject = create(subject_name.to_sym, name: 'ping_pong_king') + it "links to a resource with an underscore" do + subject = create(subject_name.to_sym, name: "ping_pong_king") doc = reference_filter("Hey #{get_reference(subject)}") - expect(doc.css('a').length).to eq 1 + expect(doc.css("a").length).to eq 1 end - it 'links to a resource with different case-sensitivity' do - subject = create(subject_name.to_sym, name: 'RescueRanger') + it "links to a resource with different case-sensitivity" do + subject = create(subject_name.to_sym, name: "RescueRanger") reference = get_reference(subject) doc = reference_filter("Hey #{reference.upcase}") - expect(doc.css('a').length).to eq 1 - expect(doc.css('a').text).to eq(reference) + expect(doc.css("a").length).to eq 1 + expect(doc.css("a").text).to eq(reference) end end - it 'supports an :only_path context' do + it "supports an :only_path context" do doc = reference_filter("Hey #{reference}", only_path: true) - link = doc.css('a').first.attr('href') + link = doc.css("a").first.attr("href") - expect(link).not_to match %r(https?://) + expect(link).not_to match %r{https?://} expect(link).to eq urls.send "#{subject_name}_path", subject end - context 'referencing a resource in a link href' do - let(:reference) { %Q{<a href="#{get_reference(subject)}">Some text</a>} } + context "referencing a resource in a link href" do + let(:reference) { %(<a href="#{get_reference(subject)}">Some text</a>) } - it_behaves_like 'it contains a data- attribute' + it_behaves_like "it contains a data- attribute" - it 'links to the resource' do + it "links to the resource" do doc = reference_filter("Hey #{reference}") - expect(doc.css('a').first.attr('href')).to eq urls.send "#{subject_name}_url", subject + expect(doc.css("a").first.attr("href")).to eq urls.send "#{subject_name}_url", subject end - it 'links with adjacent text' do + it "links with adjacent text" do doc = reference_filter("Mention me (#{reference}.)") expect(doc.to_html).to match(%r{\(<a.+>Some text</a>\.\)}) end diff --git a/spec/support/capybara.rb b/spec/support/capybara.rb index 18a7a392c12..07ad9ffb25e 100644 --- a/spec/support/capybara.rb +++ b/spec/support/capybara.rb @@ -1,11 +1,11 @@ # rubocop:disable Style/GlobalVars -require 'capybara/rails' -require 'capybara/rspec' -require 'capybara-screenshot/rspec' -require 'selenium-webdriver' +require "capybara/rails" +require "capybara/rspec" +require "capybara-screenshot/rspec" +require "selenium-webdriver" # Give CI some extra time -timeout = (ENV['CI'] || ENV['CI_SERVER']) ? 60 : 30 +timeout = ENV["CI"] || ENV["CI_SERVER"] ? 60 : 30 # Define an error class for JS console messages JSConsoleError = Class.new(StandardError) @@ -14,7 +14,7 @@ JSConsoleError = Class.new(StandardError) JS_CONSOLE_FILTER = Regexp.union([ '"[HMR] Waiting for update signal from WDS..."', '"[WDS] Hot Module Replacement enabled."', - "Download the Vue Devtools extension" + "Download the Vue Devtools extension", ]) Capybara.register_driver :chrome do |app| @@ -24,7 +24,7 @@ Capybara.register_driver :chrome do |app| browser: "ALL", client: "ALL", driver: "ALL", - server: "ALL" + server: "ALL", } ) @@ -35,10 +35,10 @@ Capybara.register_driver :chrome do |app| options.add_argument("no-sandbox") # Run headless by default unless CHROME_HEADLESS specified - options.add_argument("headless") unless ENV['CHROME_HEADLESS'] =~ /^(false|no|0)$/i + options.add_argument("headless") unless ENV["CHROME_HEADLESS"] =~ /^(false|no|0)$/i # Disable /dev/shm use in CI. See https://gitlab.com/gitlab-org/gitlab-ee/issues/4252 - options.add_argument("disable-dev-shm-usage") if ENV['CI'] || ENV['CI_SERVER'] + options.add_argument("disable-dev-shm-usage") if ENV["CI"] || ENV["CI_SERVER"] Capybara::Selenium::Driver.new( app, @@ -75,11 +75,16 @@ RSpec.configure do |config| allow(Gitlab::Application.routes).to receive(:default_url_options).and_return( host: session.server.host, port: session.server.port, - protocol: 'http') + protocol: "http" + ) # reset window size between tests unless session.current_window.size == [1240, 1400] - session.current_window.resize_to(1240, 1400) rescue nil + begin + session.current_window.resize_to(1240, 1400) + rescue + nil + end end end @@ -94,7 +99,7 @@ RSpec.configure do |config| end # prevent localStorage from introducing side effects based on test order - unless ['', 'about:blank', 'data:,'].include? Capybara.current_session.driver.browser.current_url + unless ["", "about:blank", "data:,"].include? Capybara.current_session.driver.browser.current_url execute_script("localStorage.clear();") end diff --git a/spec/support/carrierwave.rb b/spec/support/carrierwave.rb index b376822d530..673fe328ac8 100644 --- a/spec/support/carrierwave.rb +++ b/spec/support/carrierwave.rb @@ -1,4 +1,4 @@ -CarrierWave.root = File.expand_path('tmp/tests/public', Rails.root) +CarrierWave.root = File.expand_path("tmp/tests/public", Rails.root) RSpec.configure do |config| config.after do diff --git a/spec/support/chunked_io/chunked_io_helpers.rb b/spec/support/chunked_io/chunked_io_helpers.rb index fec1f951563..ebadb29eaf3 100644 --- a/spec/support/chunked_io/chunked_io_helpers.rb +++ b/spec/support/chunked_io/chunked_io_helpers.rb @@ -1,11 +1,11 @@ module ChunkedIOHelpers def sample_trace_raw - @sample_trace_raw ||= File.read(expand_fixture_path('trace/sample_trace')) + @sample_trace_raw ||= File.read(expand_fixture_path("trace/sample_trace")) .force_encoding(Encoding::BINARY) end def stub_buffer_size(size) - stub_const('Ci::BuildTraceChunk::CHUNK_SIZE', size) - stub_const('Gitlab::Ci::Trace::ChunkedIO::CHUNK_SIZE', size) + stub_const("Ci::BuildTraceChunk::CHUNK_SIZE", size) + stub_const("Gitlab::Ci::Trace::ChunkedIO::CHUNK_SIZE", size) end end diff --git a/spec/support/commit_trailers_spec_helper.rb b/spec/support/commit_trailers_spec_helper.rb index efa317fd2f9..b53230e5545 100644 --- a/spec/support/commit_trailers_spec_helper.rb +++ b/spec/support/commit_trailers_spec_helper.rb @@ -5,7 +5,7 @@ module CommitTrailersSpecHelper wrapper = find_user_wrapper(doc, trailer) expect_to_have_links_with_url_and_avatar(wrapper, urls.user_url(user), email || user.email) - expect(wrapper.attribute('data-user').value).to eq user.id.to_s + expect(wrapper.attribute("data-user").value).to eq user.id.to_s end def expect_to_have_mailto_link_with_avatar(doc, email:, trailer:) @@ -18,7 +18,7 @@ module CommitTrailersSpecHelper expect(doc).not_to be_nil expect(doc.xpath("a[position()<3 and @href='#{url}']").size).to eq 2 expect(doc.xpath("a[position()=3 and @href='mailto:#{CGI.escape_html(email)}']").size).to eq 1 - expect(doc.css('img').size).to eq 1 + expect(doc.css("img").size).to eq 1 end def find_user_wrapper(doc, trailer) diff --git a/spec/support/controllers/githubish_import_controller_shared_context.rb b/spec/support/controllers/githubish_import_controller_shared_context.rb index e71994edec6..67d0abededa 100644 --- a/spec/support/controllers/githubish_import_controller_shared_context.rb +++ b/spec/support/controllers/githubish_import_controller_shared_context.rb @@ -1,7 +1,7 @@ -shared_context 'a GitHub-ish import controller' do +shared_context "a GitHub-ish import controller" do let(:user) { create(:user) } let(:token) { "asdasd12345" } - let(:access_params) { { github_access_token: token } } + let(:access_params) { {github_access_token: token} } before do sign_in(user) diff --git a/spec/support/controllers/githubish_import_controller_shared_examples.rb b/spec/support/controllers/githubish_import_controller_shared_examples.rb index 5bb1269a19d..b3599975c71 100644 --- a/spec/support/controllers/githubish_import_controller_shared_examples.rb +++ b/spec/support/controllers/githubish_import_controller_shared_examples.rb @@ -5,38 +5,38 @@ # being currently tested). def assign_session_token(provider) - session[:"#{provider}_access_token"] = 'asdasd12345' + session[:"#{provider}_access_token"] = "asdasd12345" end -shared_examples 'a GitHub-ish import controller: POST personal_access_token' do +shared_examples "a GitHub-ish import controller: POST personal_access_token" do let(:status_import_url) { public_send("status_import_#{provider}_url") } it "updates access token" do - token = 'asdfasdf9876' + token = "asdfasdf9876" allow_any_instance_of(Gitlab::LegacyGithubImport::Client) .to receive(:user).and_return(true) - post :personal_access_token, params: { personal_access_token: token } + post :personal_access_token, params: {personal_access_token: token} expect(session[:"#{provider}_access_token"]).to eq(token) expect(controller).to redirect_to(status_import_url) end it "strips access token with spaces" do - token = 'asdfasdf9876' + token = "asdfasdf9876" allow_any_instance_of(Gitlab::LegacyGithubImport::Client) .to receive(:user).and_return(true) - post :personal_access_token, params: { personal_access_token: " #{token} " } + post :personal_access_token, params: {personal_access_token: " #{token} "} expect(session[:"#{provider}_access_token"]).to eq(token) expect(controller).to redirect_to(status_import_url) end end -shared_examples 'a GitHub-ish import controller: GET new' do +shared_examples "a GitHub-ish import controller: GET new" do let(:status_import_url) { public_send("status_import_#{provider}_url") } it "redirects to status if we already have a token" do @@ -55,19 +55,19 @@ shared_examples 'a GitHub-ish import controller: GET new' do end end -shared_examples 'a GitHub-ish import controller: GET status' do +shared_examples "a GitHub-ish import controller: GET status" do let(:new_import_url) { public_send("new_import_#{provider}_url") } let(:user) { create(:user) } - let(:repo) { OpenStruct.new(login: 'vim', full_name: 'asd/vim', name: 'vim', owner: { login: 'owner' }) } - let(:org) { OpenStruct.new(login: 'company') } - let(:org_repo) { OpenStruct.new(login: 'company', full_name: 'company/repo', name: 'repo', owner: { login: 'owner' }) } + let(:repo) { OpenStruct.new(login: "vim", full_name: "asd/vim", name: "vim", owner: {login: "owner"}) } + let(:org) { OpenStruct.new(login: "company") } + let(:org_repo) { OpenStruct.new(login: "company", full_name: "company/repo", name: "repo", owner: {login: "owner"}) } before do assign_session_token(provider) end it "returns variables for json request" do - project = create(:project, import_type: provider, namespace: user.namespace, import_status: :finished, import_source: 'example/repo') + project = create(:project, import_type: provider, namespace: user.namespace, import_status: :finished, import_source: "example/repo") group = create(:group) group.add_owner(user) stub_client(repos: [repo, org_repo], orgs: [org], org_repos: [org_repo]) @@ -82,7 +82,7 @@ shared_examples 'a GitHub-ish import controller: GET status' do end it "does not show already added project" do - project = create(:project, import_type: provider, namespace: user.namespace, import_status: :finished, import_source: 'asd/vim') + project = create(:project, import_type: provider, namespace: user.namespace, import_status: :finished, import_source: "asd/vim") stub_client(repos: [repo], orgs: []) get :status, format: :json @@ -125,9 +125,9 @@ shared_examples 'a GitHub-ish import controller: GET status' do group_a.add_owner(user) create(:project, :import_started, import_type: provider, namespace: user.namespace) - control_count = ActiveRecord::QueryRecorder.new(skip_cached: false) do + control_count = ActiveRecord::QueryRecorder.new(skip_cached: false) { get :status, format: :json - end.count + }.count stub_client(repos: [repo, org_repo], orgs: []) group_b = create(:group) @@ -139,14 +139,14 @@ shared_examples 'a GitHub-ish import controller: GET status' do end end -shared_examples 'a GitHub-ish import controller: POST create' do +shared_examples "a GitHub-ish import controller: POST create" do let(:user) { create(:user) } let(:provider_username) { user.username } let(:provider_user) { OpenStruct.new(login: provider_username) } let(:project) { create(:project, import_type: provider, import_status: :finished, import_source: "#{provider_username}/vim") } let(:provider_repo) do OpenStruct.new( - name: 'vim', + name: "vim", full_name: "#{provider_username}/vim", owner: OpenStruct.new(login: provider_username) ) @@ -157,35 +157,35 @@ shared_examples 'a GitHub-ish import controller: POST create' do assign_session_token(provider) end - it 'returns 200 response when the project is imported successfully' do + it "returns 200 response when the project is imported successfully" do allow(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) post :create, format: :json expect(response).to have_gitlab_http_status(200) end - it 'returns 422 response with the base error when the project could not be imported' do + it "returns 422 response with the base error when the project could not be imported" do project = build(:project) - project.errors.add(:name, 'is invalid') - project.errors.add(:path, 'is old') + project.errors.add(:name, "is invalid") + project.errors.add(:path, "is old") allow(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) post :create, format: :json expect(response).to have_gitlab_http_status(422) - expect(json_response['errors']).to eq('Name is invalid, Path is old') + expect(json_response["errors"]).to eq("Name is invalid, Path is old") end it "touches the etag cache store" do allow(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) expect_next_instance_of(Gitlab::EtagCaching::Store) do |store| expect(store).to receive(:touch) { "realtime_changes_import_#{provider}_path" } end @@ -198,7 +198,7 @@ shared_examples 'a GitHub-ish import controller: POST create' do it "takes the current user's namespace" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) post :create, format: :json end @@ -210,7 +210,7 @@ shared_examples 'a GitHub-ish import controller: POST create' do it "takes the current user's namespace" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) post :create, format: :json end @@ -237,7 +237,7 @@ shared_examples 'a GitHub-ish import controller: POST create' do it "takes the existing namespace" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, existing_namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) post :create, format: :json end @@ -249,7 +249,7 @@ shared_examples 'a GitHub-ish import controller: POST create' do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) post :create, format: :json end @@ -262,15 +262,15 @@ 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 expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, an_instance_of(Group), user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - post :create, params: { target_namespace: provider_repo.name }, format: :json + post :create, params: {target_namespace: provider_repo.name}, format: :json end end @@ -289,166 +289,166 @@ shared_examples 'a GitHub-ish import controller: POST create' do it "takes the current user's namespace" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) post :create, format: :json end end end - context 'user has chosen a namespace and name for the project' do - let(:test_namespace) { create(:group, name: 'test_namespace') } - let(:test_name) { 'test_name' } + context "user has chosen a namespace and name for the project" do + let(:test_namespace) { create(:group, name: "test_namespace") } + let(:test_name) { "test_name" } before do test_namespace.add_owner(user) end - it 'takes the selected namespace and name' do + it "takes the selected namespace and name" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, test_namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - post :create, params: { target_namespace: test_namespace.name, new_name: test_name }, format: :json + post :create, params: {target_namespace: test_namespace.name, new_name: test_name}, format: :json end - it 'takes the selected name and default namespace' do + it "takes the selected name and default namespace" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - post :create, params: { new_name: test_name }, format: :json + post :create, params: {new_name: test_name}, format: :json end end - context 'user has chosen an existing nested namespace and name for the project', :postgresql do - let(:parent_namespace) { create(:group, name: 'foo') } - let(:nested_namespace) { create(:group, name: 'bar', parent: parent_namespace) } - let(:test_name) { 'test_name' } + context "user has chosen an existing nested namespace and name for the project", :postgresql do + let(:parent_namespace) { create(:group, name: "foo") } + let(:nested_namespace) { create(:group, name: "bar", parent: parent_namespace) } + let(:test_name) { "test_name" } before do parent_namespace.add_owner(user) nested_namespace.add_owner(user) end - it 'takes the selected namespace and name' do + it "takes the selected namespace and name" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, nested_namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - post :create, params: { target_namespace: nested_namespace.full_path, new_name: test_name }, format: :json + post :create, params: {target_namespace: nested_namespace.full_path, new_name: test_name}, format: :json end end - context 'user has chosen a non-existent nested namespaces and name for the project', :postgresql do - let(:test_name) { 'test_name' } + context "user has chosen a non-existent nested namespaces and name for the project", :postgresql do + let(:test_name) { "test_name" } - it 'takes the selected namespace and name' do + it "takes the selected namespace and name" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, kind_of(Namespace), user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - post :create, params: { target_namespace: 'foo/bar', new_name: test_name }, format: :json + post :create, params: {target_namespace: "foo/bar", new_name: test_name}, format: :json end - it 'creates the namespaces' do + it "creates the namespaces" do allow(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, kind_of(Namespace), user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - expect { post :create, params: { target_namespace: 'foo/bar', new_name: test_name }, format: :json } + expect { post :create, params: {target_namespace: "foo/bar", new_name: test_name}, format: :json } .to change { Namespace.count }.by(2) end - it 'new namespace has the right parent' do + it "new namespace has the right parent" do allow(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, kind_of(Namespace), user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - post :create, params: { target_namespace: 'foo/bar', new_name: test_name }, format: :json + post :create, params: {target_namespace: "foo/bar", new_name: test_name}, format: :json - expect(Namespace.find_by_path_or_name('bar').parent.path).to eq('foo') + expect(Namespace.find_by_path_or_name("bar").parent.path).to eq("foo") end end - context 'user has chosen existent and non-existent nested namespaces and name for the project', :postgresql do - let(:test_name) { 'test_name' } - let!(:parent_namespace) { create(:group, name: 'foo') } + context "user has chosen existent and non-existent nested namespaces and name for the project", :postgresql do + let(:test_name) { "test_name" } + let!(:parent_namespace) { create(:group, name: "foo") } before do parent_namespace.add_owner(user) end - it 'takes the selected namespace and name' do + it "takes the selected namespace and name" do expect(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, kind_of(Namespace), user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - post :create, params: { target_namespace: 'foo/foobar/bar', new_name: test_name }, format: :json + post :create, params: {target_namespace: "foo/foobar/bar", new_name: test_name}, format: :json end - it 'creates the namespaces' do + it "creates the namespaces" do allow(Gitlab::LegacyGithubImport::ProjectCreator) .to receive(:new).with(provider_repo, test_name, kind_of(Namespace), user, access_params, type: provider) - .and_return(double(execute: project)) + .and_return(double(execute: project)) - expect { post :create, params: { target_namespace: 'foo/foobar/bar', new_name: test_name }, format: :json } + expect { post :create, params: {target_namespace: "foo/foobar/bar", new_name: test_name}, format: :json } .to change { Namespace.count }.by(2) end - it 'does not create a new namespace under the user namespace' do + it "does not create a new namespace under the user namespace" do expect(Gitlab::LegacyGithubImport::ProjectCreator) - .to receive(:new).with(provider_repo, test_name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .to receive(:new).with(provider_repo, test_name, user.namespace, user, access_params, type: provider) + .and_return(double(execute: project)) - expect { post :create, params: { target_namespace: "#{user.namespace_path}/test_group", new_name: test_name }, format: :js } - .not_to change { Namespace.count } + expect { post :create, params: {target_namespace: "#{user.namespace_path}/test_group", new_name: test_name}, format: :js } + .not_to change { Namespace.count } end end - context 'user cannot create a subgroup inside a group is not a member of' do - let(:test_name) { 'test_name' } - let!(:parent_namespace) { create(:group, name: 'foo') } + context "user cannot create a subgroup inside a group is not a member of" do + let(:test_name) { "test_name" } + let!(:parent_namespace) { create(:group, name: "foo") } - it 'does not take the selected namespace and name' do + it "does not take the selected namespace and name" do expect(Gitlab::LegacyGithubImport::ProjectCreator) - .to receive(:new).with(provider_repo, test_name, user.namespace, user, access_params, type: provider) - .and_return(double(execute: project)) + .to receive(:new).with(provider_repo, test_name, user.namespace, user, access_params, type: provider) + .and_return(double(execute: project)) - post :create, params: { target_namespace: 'foo/foobar/bar', new_name: test_name }, format: :js + post :create, params: {target_namespace: "foo/foobar/bar", new_name: test_name}, format: :js end - it 'does not create the namespaces' do + it "does not create the namespaces" do allow(Gitlab::LegacyGithubImport::ProjectCreator) - .to receive(:new).with(provider_repo, test_name, kind_of(Namespace), user, access_params, type: provider) - .and_return(double(execute: project)) + .to receive(:new).with(provider_repo, test_name, kind_of(Namespace), user, access_params, type: provider) + .and_return(double(execute: project)) - expect { post :create, params: { target_namespace: 'foo/foobar/bar', new_name: test_name }, format: :js } - .not_to change { Namespace.count } + expect { post :create, params: {target_namespace: "foo/foobar/bar", new_name: test_name}, format: :js } + .not_to change { Namespace.count } end end - context 'user can use a group without having permissions to create a group' do - let(:test_name) { 'test_name' } - let!(:group) { create(:group, name: 'foo') } + context "user can use a group without having permissions to create a group" do + let(:test_name) { "test_name" } + let!(:group) { create(:group, name: "foo") } - it 'takes the selected namespace and name' do + it "takes the selected namespace and name" do group.add_owner(user) user.update!(can_create_group: false) expect(Gitlab::LegacyGithubImport::ProjectCreator) - .to receive(:new).with(provider_repo, test_name, group, user, access_params, type: provider) - .and_return(double(execute: project)) + .to receive(:new).with(provider_repo, test_name, group, user, access_params, type: provider) + .and_return(double(execute: project)) - post :create, params: { target_namespace: 'foo', new_name: test_name }, format: :js + post :create, params: {target_namespace: "foo", new_name: test_name}, format: :js end end - context 'when user can not create projects in the chosen namespace' do - it 'returns 422 response' do - other_namespace = create(:group, name: 'other_namespace') + context "when user can not create projects in the chosen namespace" do + it "returns 422 response" do + other_namespace = create(:group, name: "other_namespace") - post :create, params: { target_namespace: other_namespace.name }, format: :json + post :create, params: {target_namespace: other_namespace.name}, format: :json expect(response).to have_gitlab_http_status(422) end @@ -456,19 +456,19 @@ shared_examples 'a GitHub-ish import controller: POST create' do end end -shared_examples 'a GitHub-ish import controller: GET realtime_changes' do +shared_examples "a GitHub-ish import controller: GET realtime_changes" do let(:user) { create(:user) } before do assign_session_token(provider) end - it 'sets a Poll-Interval header' do - project = create(:project, import_type: provider, namespace: user.namespace, import_status: :finished, import_source: 'example/repo') + it "sets a Poll-Interval header" do + project = create(:project, import_type: provider, namespace: user.namespace, import_status: :finished, import_source: "example/repo") get :realtime_changes - expect(json_response).to eq([{ "id" => project.id, "import_status" => project.import_status }]) - expect(Integer(response.headers['Poll-Interval'])).to be > -1 + expect(json_response).to eq([{"id" => project.id, "import_status" => project.import_status}]) + expect(Integer(response.headers["Poll-Interval"])).to be > -1 end end diff --git a/spec/support/controllers/ldap_omniauth_callbacks_controller_shared_context.rb b/spec/support/controllers/ldap_omniauth_callbacks_controller_shared_context.rb index 72912ffb89d..6f6ff80c563 100644 --- a/spec/support/controllers/ldap_omniauth_callbacks_controller_shared_context.rb +++ b/spec/support/controllers/ldap_omniauth_callbacks_controller_shared_context.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +require "spec_helper" -shared_context 'Ldap::OmniauthCallbacksController' do +shared_context "Ldap::OmniauthCallbacksController" do include LoginHelpers include LdapHelpers - let(:uid) { 'my-uid' } - let(:provider) { 'ldapmain' } + let(:uid) { "my-uid" } + let(:provider) { "ldapmain" } let(:valid_login?) { true } let(:user) { create(:omniauth_user, extern_uid: uid, provider: provider) } let(:ldap_server_config) do - { main: ldap_config_defaults(:main) } + {main: ldap_config_defaults(:main)} end def ldap_config_defaults(key, hash = {}) { provider_name: "ldap#{key}", attributes: {}, - encryption: 'plain' + encryption: "plain", }.merge(hash) end diff --git a/spec/support/controllers/sessionless_auth_controller_shared_examples.rb b/spec/support/controllers/sessionless_auth_controller_shared_examples.rb index 355555d9d19..93333a128d6 100644 --- a/spec/support/controllers/sessionless_auth_controller_shared_examples.rb +++ b/spec/support/controllers/sessionless_auth_controller_shared_examples.rb @@ -1,4 +1,4 @@ -shared_examples 'authenticates sessionless user' do |path, format, params| +shared_examples "authenticates sessionless user" do |path, format, params| params ||= {} before do @@ -7,14 +7,14 @@ shared_examples 'authenticates sessionless user' do |path, format, params| let(:user) { create(:user) } let(:personal_access_token) { create(:personal_access_token, user: user) } - let(:default_params) { { format: format }.merge(params.except(:public) || {}) } + let(:default_params) { {format: format}.merge(params.except(:public) || {}) } context "when the 'personal_access_token' param is populated with the personal access token" do - it 'logs the user in' do + it "logs the user in" do expect(authentication_metrics) .to increment(:user_authenticated_counter) - .and increment(:user_session_override_counter) - .and increment(:user_sessionless_authentication_counter) + .and increment(:user_session_override_counter) + .and increment(:user_sessionless_authentication_counter) get path, params: default_params.merge(private_token: personal_access_token.token) @@ -22,7 +22,7 @@ shared_examples 'authenticates sessionless user' do |path, format, params| expect(controller.current_user).to eq(user) end - it 'does not log the user in if page is public', if: params[:public] do + it "does not log the user in if page is public", if: params[:public] do get path, params: default_params expect(response).to have_gitlab_http_status(200) @@ -30,8 +30,8 @@ shared_examples 'authenticates sessionless user' do |path, format, params| end end - context 'when the personal access token has no api scope', unless: params[:public] do - it 'does not log the user in' do + context "when the personal access token has no api scope", unless: params[:public] do + it "does not log the user in" do expect(authentication_metrics) .to increment(:user_unauthenticated_counter) @@ -44,13 +44,13 @@ shared_examples 'authenticates sessionless user' do |path, format, params| end context "when the 'PERSONAL_ACCESS_TOKEN' header is populated with the personal access token" do - it 'logs the user in' do + it "logs the user in" do expect(authentication_metrics) .to increment(:user_authenticated_counter) - .and increment(:user_session_override_counter) - .and increment(:user_sessionless_authentication_counter) + .and increment(:user_session_override_counter) + .and increment(:user_sessionless_authentication_counter) - @request.headers['PRIVATE-TOKEN'] = personal_access_token.token + @request.headers["PRIVATE-TOKEN"] = personal_access_token.token get path, params: default_params expect(response).to have_gitlab_http_status(200) @@ -61,8 +61,8 @@ shared_examples 'authenticates sessionless user' do |path, format, params| it "logs the user in" do expect(authentication_metrics) .to increment(:user_authenticated_counter) - .and increment(:user_session_override_counter) - .and increment(:user_sessionless_authentication_counter) + .and increment(:user_session_override_counter) + .and increment(:user_sessionless_authentication_counter) get path, params: default_params.merge(feed_token: user.feed_token) @@ -75,7 +75,7 @@ shared_examples 'authenticates sessionless user' do |path, format, params| expect(authentication_metrics) .to increment(:user_unauthenticated_counter) - get path, params: default_params.merge(feed_token: 'token') + get path, params: default_params.merge(feed_token: "token") expect(response.status).not_to eq 200 end @@ -85,7 +85,7 @@ shared_examples 'authenticates sessionless user' do |path, format, params| expect(authentication_metrics) .to increment(:user_unauthenticated_counter) - get path, params: default_params.merge(private_token: 'token') + get path, params: default_params.merge(private_token: "token") expect(response.status).not_to eq(200) end diff --git a/spec/support/cycle_analytics_helpers/test_generation.rb b/spec/support/cycle_analytics_helpers/test_generation.rb index 19b32c84d81..a80f95520be 100644 --- a/spec/support/cycle_analytics_helpers/test_generation.rb +++ b/spec/support/cycle_analytics_helpers/test_generation.rb @@ -28,7 +28,7 @@ module CycleAnalyticsHelpers context "start condition: #{start_time_conditions.map(&:first).to_sentence}" do context "end condition: #{end_time_conditions.map(&:first).to_sentence}" do it "finds the median of available durations between the two conditions" do - time_differences = Array.new(5) do |index| + time_differences = Array.new(5) { |index| data = data_fn[self] start_time = (index * 10).days.from_now end_time = start_time + rand(1..5).days @@ -47,7 +47,7 @@ module CycleAnalyticsHelpers Timecop.freeze(end_time + 1.day) { post_fn[self, data] } if post_fn end_time - start_time - end + } median_time_difference = time_differences.sort[2] expect(subject[phase].median).to be_within(5).of(median_time_difference) @@ -85,7 +85,7 @@ module CycleAnalyticsHelpers end context "when the end condition happens before the start condition" do - it 'returns nil' do + it "returns nil" do data = data_fn[self] start_time = Time.now end_time = start_time + rand(1..5).days diff --git a/spec/support/db_cleaner.rb b/spec/support/db_cleaner.rb index 34b9efaaecd..aba8d892b09 100644 --- a/spec/support/db_cleaner.rb +++ b/spec/support/db_cleaner.rb @@ -1,4 +1,4 @@ -require 'database_cleaner/active_record/deletion' +require "database_cleaner/active_record/deletion" module FakeInformationSchema # Work around a bug in DatabaseCleaner when using the deletion strategy: @@ -28,15 +28,15 @@ RSpec.configure do |config| end config.before(:each, :js) do - DatabaseCleaner.strategy = :deletion, { cache_tables: false } + DatabaseCleaner.strategy = :deletion, {cache_tables: false} end config.before(:each, :delete) do - DatabaseCleaner.strategy = :deletion, { cache_tables: false } + DatabaseCleaner.strategy = :deletion, {cache_tables: false} end config.before(:each, :migration) do - DatabaseCleaner.strategy = :deletion, { cache_tables: false } + DatabaseCleaner.strategy = :deletion, {cache_tables: false} end config.before do diff --git a/spec/support/features/discussion_comments_shared_example.rb b/spec/support/features/discussion_comments_shared_example.rb index 42a086d58d2..7e8e3e9d4ad 100644 --- a/spec/support/features/discussion_comments_shared_example.rb +++ b/spec/support/features/discussion_comments_shared_example.rb @@ -1,16 +1,16 @@ -shared_examples 'discussion comments' do |resource_name| - let(:form_selector) { '.js-main-target-form' } +shared_examples "discussion comments" do |resource_name| + let(:form_selector) { ".js-main-target-form" } let(:dropdown_selector) { "#{form_selector} .comment-type-dropdown" } let(:toggle_selector) { "#{dropdown_selector} .dropdown-toggle" } let(:menu_selector) { "#{dropdown_selector} .dropdown-menu" } let(:submit_selector) { "#{form_selector} .js-comment-submit-button" } let(:close_selector) { "#{form_selector} .btn-comment-and-close" } - let(:comments_selector) { '.timeline > .note.timeline-entry' } + let(:comments_selector) { ".timeline > .note.timeline-entry" } it 'clicking "Comment" will post a comment' do expect(page).to have_selector toggle_selector - find("#{form_selector} .note-textarea").send_keys('a') + find("#{form_selector} .note-textarea").send_keys("a") find(submit_selector).click @@ -19,13 +19,13 @@ shared_examples 'discussion comments' do |resource_name| find(comments_selector, match: :first) new_comment = all(comments_selector).last - expect(new_comment).to have_content 'a' - expect(new_comment).not_to have_selector '.discussion' + expect(new_comment).to have_content "a" + expect(new_comment).not_to have_selector ".discussion" end - if resource_name == 'issue' + if resource_name == "issue" it "clicking 'Comment & close #{resource_name}' will post a comment and close the #{resource_name}" do - find("#{form_selector} .note-textarea").send_keys('a') + find("#{form_selector} .note-textarea").send_keys("a") find(close_selector).click wait_for_requests @@ -36,14 +36,14 @@ shared_examples 'discussion comments' do |resource_name| close_note = entries.last new_comment = entries[-2] - expect(close_note).to have_content 'closed' - expect(new_comment).not_to have_selector '.discussion' + expect(close_note).to have_content "closed" + expect(new_comment).not_to have_selector ".discussion" end end - describe 'when the toggle is clicked' do + describe "when the toggle is clicked" do before do - find("#{form_selector} .note-textarea").send_keys('a') + find("#{form_selector} .note-textarea").send_keys("a") find(toggle_selector).click end @@ -54,18 +54,18 @@ shared_examples 'discussion comments' do |resource_name| find("#{menu_selector} li", match: :first) items = all("#{menu_selector} li") - expect(items.first).to have_content 'Comment' + expect(items.first).to have_content "Comment" expect(items.first).to have_content "Add a general comment to this #{resource_name}." - expect(items.first).to have_selector '.fa-check' - expect(items.first['class']).to match 'droplab-item-selected' + expect(items.first).to have_selector ".fa-check" + expect(items.first["class"]).to match "droplab-item-selected" - expect(items.last).to have_content 'Start discussion' - expect(items.last).to have_content "Discuss a specific suggestion or question#{' that needs to be resolved' if resource_name == 'merge request'}." - expect(items.last).not_to have_selector '.fa-check' - expect(items.last['class']).not_to match 'droplab-item-selected' + expect(items.last).to have_content "Start discussion" + expect(items.last).to have_content "Discuss a specific suggestion or question#{" that needs to be resolved" if resource_name == "merge request"}." + expect(items.last).not_to have_selector ".fa-check" + expect(items.last["class"]).not_to match "droplab-item-selected" end - it 'closes the menu when clicking the toggle or body' do + it "closes the menu when clicking the toggle or body" do find(toggle_selector).click expect(page).not_to have_selector menu_selector @@ -76,7 +76,7 @@ shared_examples 'discussion comments' do |resource_name| expect(page).not_to have_selector menu_selector end - it 'clicking the ul padding or divider should not change the text' do + it "clicking the ul padding or divider should not change the text" do execute_script("document.querySelector('#{menu_selector}').click()") # on issues page, the menu closes when clicking anywhere, on other pages it will @@ -85,7 +85,7 @@ shared_examples 'discussion comments' do |resource_name| # if dropdown menu is not toggled (and also not present), # it's "issue-type" dropdown if first(menu_selector).nil? - expect(find(dropdown_selector)).to have_content 'Comment' + expect(find(dropdown_selector)).to have_content "Comment" find(toggle_selector).click execute_script("document.querySelector('#{menu_selector} .divider').click()") @@ -93,14 +93,14 @@ shared_examples 'discussion comments' do |resource_name| execute_script("document.querySelector('#{menu_selector}').click()") expect(page).to have_selector menu_selector - expect(find(dropdown_selector)).to have_content 'Comment' + expect(find(dropdown_selector)).to have_content "Comment" execute_script("document.querySelector('#{menu_selector} .divider').click()") expect(page).to have_selector menu_selector end - expect(find(dropdown_selector)).to have_content 'Comment' + expect(find(dropdown_selector)).to have_content "Comment" end describe 'when selecting "Start discussion"' do @@ -109,32 +109,32 @@ shared_examples 'discussion comments' do |resource_name| all("#{menu_selector} li").last.click end - it 'updates the submit button text and closes the dropdown' do + it "updates the submit button text and closes the dropdown" do button = find(submit_selector) # on issues page, the submit input is a <button>, on other pages it is <input> - if button.tag_name == 'button' - expect(find(submit_selector)).to have_content 'Start discussion' + if button.tag_name == "button" + expect(find(submit_selector)).to have_content "Start discussion" else - expect(find(submit_selector).value).to eq 'Start discussion' + expect(find(submit_selector).value).to eq "Start discussion" end expect(page).not_to have_selector menu_selector end - if resource_name =~ /(issue|merge request)/ - it 'updates the close button text' do + if /(issue|merge request)/.match?(resource_name) + it "updates the close button text" do expect(find(close_selector)).to have_content "Start discussion & close #{resource_name}" end - it 'typing does not change the close button text' do - find("#{form_selector} .note-textarea").send_keys('b') + it "typing does not change the close button text" do + find("#{form_selector} .note-textarea").send_keys("b") expect(find(close_selector)).to have_content "Start discussion & close #{resource_name}" end end - describe 'creating a discussion' do + describe "creating a discussion" do before do find(submit_selector).click wait_for_requests @@ -153,43 +153,43 @@ shared_examples 'discussion comments' do |resource_name| it 'clicking "Start discussion" will post a discussion' do new_comment = all(comments_selector).last - expect(new_comment).to have_content 'a' - expect(new_comment).to have_selector '.discussion' + expect(new_comment).to have_content "a" + expect(new_comment).to have_selector ".discussion" end - if resource_name =~ /(issue|merge request)/ - it 'can be replied to' do - submit_reply('some text') + if /(issue|merge request)/.match?(resource_name) + it "can be replied to" do + submit_reply("some text") - expect(page).to have_css('.discussion-notes .note', count: 2) - expect(page).to have_content 'Collapse replies' + expect(page).to have_css(".discussion-notes .note", count: 2) + expect(page).to have_content "Collapse replies" end - it 'can be collapsed' do - submit_reply('another text') + it "can be collapsed" do + submit_reply("another text") - find('.js-collapse-replies').click - expect(page).to have_css('.discussion-notes .note', count: 1) - expect(page).to have_content '1 reply' + find(".js-collapse-replies").click + expect(page).to have_css(".discussion-notes .note", count: 1) + expect(page).to have_content "1 reply" end end - if resource_name == 'merge request' - let(:note_id) { find("#{comments_selector} .note:first-child", match: :first)['data-note-id'] } - let(:reply_id) { find("#{comments_selector} .note:last-child", match: :first)['data-note-id'] } + if resource_name == "merge request" + let(:note_id) { find("#{comments_selector} .note:first-child", match: :first)["data-note-id"] } + let(:reply_id) { find("#{comments_selector} .note:last-child", match: :first)["data-note-id"] } - it 'can be replied to after resolving' do + it "can be replied to after resolving" do click_button "Resolve discussion" wait_for_requests refresh wait_for_requests - submit_reply('to reply or not reply') + submit_reply("to reply or not reply") end - it 'shows resolved discussion when toggled' do - submit_reply('a') + it "shows resolved discussion when toggled" do + submit_reply("a") click_button "Resolve discussion" wait_for_requests @@ -204,7 +204,7 @@ shared_examples 'discussion comments' do |resource_name| end end - if resource_name == 'issue' + if resource_name == "issue" it "clicking 'Start discussion & close #{resource_name}' will post a discussion and close the #{resource_name}" do find(close_selector).click @@ -214,12 +214,12 @@ shared_examples 'discussion comments' do |resource_name| close_note = entries.last new_discussion = entries[-2] - expect(close_note).to have_content 'closed' - expect(new_discussion).to have_selector '.discussion' + expect(close_note).to have_content "closed" + expect(new_discussion).to have_selector ".discussion" end end - describe 'when opening the menu' do + describe "when opening the menu" do before do find(toggle_selector).click end @@ -228,13 +228,13 @@ shared_examples 'discussion comments' do |resource_name| find("#{menu_selector} li", match: :first) items = all("#{menu_selector} li") - expect(items.first).to have_content 'Comment' - expect(items.first).not_to have_selector '.fa-check' - expect(items.first['class']).not_to match 'droplab-item-selected' + expect(items.first).to have_content "Comment" + expect(items.first).not_to have_selector ".fa-check" + expect(items.first["class"]).not_to match "droplab-item-selected" - expect(items.last).to have_content 'Start discussion' - expect(items.last).to have_selector '.fa-check' - expect(items.last['class']).to match 'droplab-item-selected' + expect(items.last).to have_content "Start discussion" + expect(items.last).to have_selector ".fa-check" + expect(items.last["class"]).to match "droplab-item-selected" end describe 'when selecting "Comment"' do @@ -242,26 +242,26 @@ shared_examples 'discussion comments' do |resource_name| find("#{menu_selector} li", match: :first).click end - it 'updates the submit button text and closes the dropdown' do + it "updates the submit button text and closes the dropdown" do button = find(submit_selector) # on issues page, the submit input is a <button>, on other pages it is <input> - if button.tag_name == 'button' - expect(button).to have_content 'Comment' + if button.tag_name == "button" + expect(button).to have_content "Comment" else - expect(button.value).to eq 'Comment' + expect(button.value).to eq "Comment" end expect(page).not_to have_selector menu_selector end - if resource_name =~ /(issue|merge request)/ - it 'updates the close button text' do + if /(issue|merge request)/.match?(resource_name) + it "updates the close button text" do expect(find(close_selector)).to have_content "Comment & close #{resource_name}" end - it 'typing does not change the close button text' do - find("#{form_selector} .note-textarea").send_keys('b') + it "typing does not change the close button text" do + find("#{form_selector} .note-textarea").send_keys("b") expect(find(close_selector)).to have_content "Comment & close #{resource_name}" end @@ -273,26 +273,26 @@ shared_examples 'discussion comments' do |resource_name| find("#{menu_selector} li", match: :first) items = all("#{menu_selector} li") - expect(items.first).to have_content 'Comment' - expect(items.first).to have_selector '.fa-check' - expect(items.first['class']).to match 'droplab-item-selected' + expect(items.first).to have_content "Comment" + expect(items.first).to have_selector ".fa-check" + expect(items.first["class"]).to match "droplab-item-selected" - expect(items.last).to have_content 'Start discussion' - expect(items.last).not_to have_selector '.fa-check' - expect(items.last['class']).not_to match 'droplab-item-selected' + expect(items.last).to have_content "Start discussion" + expect(items.last).not_to have_selector ".fa-check" + expect(items.last["class"]).not_to match "droplab-item-selected" end end end end end - if resource_name =~ /(issue|merge request)/ + if /(issue|merge request)/.match?(resource_name) describe "on a closed #{resource_name}" do before do find("#{form_selector} .js-note-target-close").click wait_for_requests - find("#{form_selector} .note-textarea").send_keys('a') + find("#{form_selector} .note-textarea").send_keys("a") end it "should show a 'Comment & reopen #{resource_name}' button" do diff --git a/spec/support/features/issuable_quick_actions_shared_examples.rb b/spec/support/features/issuable_quick_actions_shared_examples.rb index 2a883ce1074..b43a91d403f 100644 --- a/spec/support/features/issuable_quick_actions_shared_examples.rb +++ b/spec/support/features/issuable_quick_actions_shared_examples.rb @@ -1,7 +1,7 @@ # Specifications for behavior common to all objects with executable attributes. # It takes a `issuable_type`, and expect an `issuable`. -shared_examples 'issuable record that supports quick actions in its description and notes' do |issuable_type| +shared_examples "issuable record that supports quick actions in its description and notes" do |issuable_type| include Spec::Support::Helpers::Features::NotesHelpers let(:maintainer) { create(:user) } @@ -13,9 +13,9 @@ shared_examples 'issuable record that supports quick actions in its description create(:project, :public) end end - let!(:milestone) { create(:milestone, project: project, title: 'ASAP') } - let!(:label_bug) { create(:label, project: project, title: 'bug') } - let!(:label_feature) { create(:label, project: project, title: 'feature') } + let!(:milestone) { create(:milestone, project: project, title: "ASAP") } + let!(:label_bug) { create(:label, project: project, title: "bug") } + let!(:label_feature) { create(:label, project: project, title: "feature") } let(:new_url_opts) { {} } before do @@ -30,7 +30,7 @@ shared_examples 'issuable record that supports quick actions in its description end describe "new #{issuable_type}", :js do - context 'with commands in the description' do + context "with commands in the description" do it "creates the #{issuable_type} and interpret commands accordingly" do case issuable_type when :merge_request @@ -38,7 +38,7 @@ shared_examples 'issuable record that supports quick actions in its description when :issue visit public_send("new_namespace_project_issue_path", project.namespace, project, new_url_opts) end - fill_in "#{issuable_type}_title", with: 'bug 345' + fill_in "#{issuable_type}_title", with: "bug 345" fill_in "#{issuable_type}_description", with: "bug description\n/label ~bug\n/milestone %\"ASAP\"" click_button "Submit #{issuable_type}".humanize @@ -47,8 +47,8 @@ shared_examples 'issuable record that supports quick actions in its description expect(issuable.description).to eq "bug description" expect(issuable.labels).to eq [label_bug] expect(issuable.milestone).to eq milestone - expect(page).to have_content 'bug 345' - expect(page).to have_content 'bug description' + expect(page).to have_content "bug 345" + expect(page).to have_content "bug description" end end end @@ -58,14 +58,14 @@ shared_examples 'issuable record that supports quick actions in its description visit public_send("project_#{issuable_type}_path", project, issuable) end - context 'with a note containing commands' do - it 'creates a note without the commands and interpret the commands accordingly' do - assignee = create(:user, username: 'bob') + context "with a note containing commands" do + it "creates a note without the commands and interpret the commands accordingly" do + assignee = create(:user, username: "bob") add_note("Awesome!\n\n/assign @bob\n\n/label ~bug\n\n/milestone %\"ASAP\"") - expect(page).to have_content 'Awesome!' - expect(page).not_to have_content '/assign @bob' - expect(page).not_to have_content '/label ~bug' + expect(page).to have_content "Awesome!" + expect(page).not_to have_content "/assign @bob" + expect(page).not_to have_content "/label ~bug" expect(page).not_to have_content '/milestone %"ASAP"' wait_for_requests @@ -78,25 +78,25 @@ shared_examples 'issuable record that supports quick actions in its description expect(issuable.milestone).to eq milestone end - it 'removes the quick action from note and explains it in the preview' do + it "removes the quick action from note and explains it in the preview" do preview_note("Awesome!\n\n/close") - expect(page).to have_content 'Awesome!' - expect(page).not_to have_content '/close' - issuable_name = issuable.is_a?(Issue) ? 'issue' : 'merge request' + expect(page).to have_content "Awesome!" + expect(page).not_to have_content "/close" + issuable_name = issuable.is_a?(Issue) ? "issue" : "merge request" expect(page).to have_content "Closes this #{issuable_name}." end end - context 'with a note containing only commands' do - it 'does not create a note but interpret the commands accordingly' do - assignee = create(:user, username: 'bob') + context "with a note containing only commands" do + it "does not create a note but interpret the commands accordingly" do + assignee = create(:user, username: "bob") add_note("/assign @bob\n\n/label ~bug\n\n/milestone %\"ASAP\"") - expect(page).not_to have_content '/assign @bob' - expect(page).not_to have_content '/label ~bug' + expect(page).not_to have_content "/assign @bob" + expect(page).not_to have_content "/label ~bug" expect(page).not_to have_content '/milestone %"ASAP"' - expect(page).to have_content 'Commands applied' + expect(page).to have_content "Commands applied" issuable.reload @@ -116,8 +116,8 @@ shared_examples 'issuable record that supports quick actions in its description it "closes the #{issuable_type}" do add_note("/close") - expect(page).not_to have_content '/close' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/close" + expect(page).to have_content "Commands applied" expect(issuable.reload).to be_closed end @@ -136,7 +136,7 @@ shared_examples 'issuable record that supports quick actions in its description it "does not close the #{issuable_type}" do add_note("/close") - expect(page).not_to have_content 'Commands applied' + expect(page).not_to have_content "Commands applied" expect(issuable).to be_open end @@ -153,8 +153,8 @@ shared_examples 'issuable record that supports quick actions in its description it "reopens the #{issuable_type}" do add_note("/reopen") - expect(page).not_to have_content '/reopen' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/reopen" + expect(page).to have_content "Commands applied" expect(issuable.reload).to be_open end @@ -173,7 +173,7 @@ shared_examples 'issuable record that supports quick actions in its description it "does not reopen the #{issuable_type}" do add_note("/reopen") - expect(page).not_to have_content 'Commands applied' + expect(page).not_to have_content "Commands applied" expect(issuable).to be_closed end @@ -185,10 +185,10 @@ shared_examples 'issuable record that supports quick actions in its description it "reopens the #{issuable_type}" do add_note("/title Awesome new title") - expect(page).not_to have_content '/title' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/title" + expect(page).to have_content "Commands applied" - expect(issuable.reload.title).to eq 'Awesome new title' + expect(issuable.reload.title).to eq "Awesome new title" end end @@ -205,9 +205,9 @@ shared_examples 'issuable record that supports quick actions in its description it "does not change the #{issuable_type} title" do add_note("/title Awesome new title") - expect(page).not_to have_content 'Commands applied' + expect(page).not_to have_content "Commands applied" - expect(issuable.reload.title).not_to eq 'Awesome new title' + expect(issuable.reload.title).not_to eq "Awesome new title" end end end @@ -216,8 +216,8 @@ shared_examples 'issuable record that supports quick actions in its description it "creates a new todo for the #{issuable_type}" do add_note("/todo") - expect(page).not_to have_content '/todo' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/todo" + expect(page).to have_content "Commands applied" todos = TodosFinder.new(maintainer).execute todo = todos.first @@ -247,8 +247,8 @@ shared_examples 'issuable record that supports quick actions in its description add_note("/done") - expect(page).not_to have_content '/done' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/done" + expect(page).to have_content "Commands applied" expect(todo.reload).to be_done end @@ -260,8 +260,8 @@ shared_examples 'issuable record that supports quick actions in its description add_note("/subscribe") - expect(page).not_to have_content '/subscribe' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/subscribe" + expect(page).to have_content "Commands applied" expect(issuable.subscribed?(maintainer, project)).to be_truthy end @@ -277,8 +277,8 @@ shared_examples 'issuable record that supports quick actions in its description add_note("/unsubscribe") - expect(page).not_to have_content '/unsubscribe' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/unsubscribe" + expect(page).to have_content "Commands applied" expect(issuable.subscribed?(maintainer, project)).to be_falsy end @@ -288,8 +288,8 @@ shared_examples 'issuable record that supports quick actions in its description it "assigns the #{issuable_type} to the current user" do add_note("/assign me") - expect(page).not_to have_content '/assign me' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/assign me" + expect(page).to have_content "Commands applied" expect(issuable.reload.assignees).to eq [maintainer] end @@ -305,8 +305,8 @@ shared_examples 'issuable record that supports quick actions in its description it "locks the #{issuable_type} discussion" do add_note("/lock") - expect(page).not_to have_content '/lock' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/lock" + expect(page).to have_content "Commands applied" expect(issuable.reload).to be_discussion_locked end @@ -325,7 +325,7 @@ shared_examples 'issuable record that supports quick actions in its description it "does not lock the #{issuable_type} discussion" do add_note("/lock") - expect(page).not_to have_content 'Commands applied' + expect(page).not_to have_content "Commands applied" expect(issuable).not_to be_discussion_locked end @@ -342,8 +342,8 @@ shared_examples 'issuable record that supports quick actions in its description it "unlocks the #{issuable_type} discussion" do add_note("/unlock") - expect(page).not_to have_content '/unlock' - expect(page).to have_content 'Commands applied' + expect(page).not_to have_content "/unlock" + expect(page).to have_content "Commands applied" expect(issuable.reload).not_to be_discussion_locked end @@ -362,7 +362,7 @@ shared_examples 'issuable record that supports quick actions in its description it "does not unlock the #{issuable_type} discussion" do add_note("/unlock") - expect(page).not_to have_content 'Commands applied' + expect(page).not_to have_content "Commands applied" expect(issuable).to be_discussion_locked end @@ -371,18 +371,18 @@ shared_examples 'issuable record that supports quick actions in its description end describe "preview of note on #{issuable_type}", :js do - it 'removes quick actions from note and explains them' do - create(:user, username: 'bob') + it "removes quick actions from note and explains them" do + create(:user, username: "bob") visit public_send("project_#{issuable_type}_path", project, issuable) - page.within('.js-main-target-form') do - fill_in 'note[note]', with: "Awesome!\n/assign @bob " - click_on 'Preview' + page.within(".js-main-target-form") do + fill_in "note[note]", with: "Awesome!\n/assign @bob " + click_on "Preview" - expect(page).to have_content 'Awesome!' - expect(page).not_to have_content '/assign @bob' - expect(page).to have_content 'Assigns @bob.' + expect(page).to have_content "Awesome!" + expect(page).not_to have_content "/assign @bob" + expect(page).to have_content "Assigns @bob." end end end diff --git a/spec/support/features/reportable_note_shared_examples.rb b/spec/support/features/reportable_note_shared_examples.rb index 8cfce49da8a..329eb696353 100644 --- a/spec/support/features/reportable_note_shared_examples.rb +++ b/spec/support/features/reportable_note_shared_examples.rb @@ -1,49 +1,49 @@ -require 'spec_helper' +require "spec_helper" -shared_examples 'reportable note' do |type| +shared_examples "reportable note" do |type| include MobileHelpers include NotesHelper let(:comment) { find("##{ActionView::RecordIdentifier.dom_id(note)}") } - let(:more_actions_selector) { '.more-actions.dropdown' } + let(:more_actions_selector) { ".more-actions.dropdown" } let(:abuse_report_path) { new_abuse_report_path(user_id: note.author.id, ref_url: noteable_note_url(note)) } - it 'has an edit button' do - expect(comment).to have_selector('.js-note-edit') + it "has an edit button" do + expect(comment).to have_selector(".js-note-edit") end - it 'has a `More actions` dropdown' do + it "has a `More actions` dropdown" do expect(comment).to have_selector(more_actions_selector) end - it 'dropdown has Report and Delete links' do + it "dropdown has Report and Delete links" do dropdown = comment.find(more_actions_selector) open_dropdown(dropdown) - expect(dropdown).to have_link('Report abuse to GitLab', href: abuse_report_path) + expect(dropdown).to have_link("Report abuse to GitLab", href: abuse_report_path) - if type == 'issue' || type == 'merge_request' - expect(dropdown).to have_button('Delete comment') + if type == "issue" || type == "merge_request" + expect(dropdown).to have_button("Delete comment") else - expect(dropdown).to have_link('Delete comment', href: note_url(note, project)) + expect(dropdown).to have_link("Delete comment", href: note_url(note, project)) end end - it 'Report button links to a report page' do + it "Report button links to a report page" do dropdown = comment.find(more_actions_selector) open_dropdown(dropdown) - dropdown.click_link('Report abuse to GitLab') + dropdown.click_link("Report abuse to GitLab") - expect(find('#user_name')['value']).to match(note.author.username) - expect(find('#abuse_report_message')['value']).to match(noteable_note_url(note)) + expect(find("#user_name")["value"]).to match(note.author.username) + expect(find("#abuse_report_message")["value"]).to match(noteable_note_url(note)) end def open_dropdown(dropdown) # make window wide enough that tooltip doesn't trigger horizontal scrollbar resize_window(1200, 800) - dropdown.find('.more-actions-toggle').click - dropdown.find('.dropdown-menu li', match: :first) + dropdown.find(".more-actions-toggle").click + dropdown.find(".dropdown-menu li", match: :first) end end diff --git a/spec/support/features/resolving_discussions_in_issues_shared_examples.rb b/spec/support/features/resolving_discussions_in_issues_shared_examples.rb index 38e5fb155a4..53e671594fe 100644 --- a/spec/support/features/resolving_discussions_in_issues_shared_examples.rb +++ b/spec/support/features/resolving_discussions_in_issues_shared_examples.rb @@ -1,40 +1,40 @@ -shared_examples 'creating an issue for a discussion' do - it 'shows an issue with the title filled in' do - title_field = page.find_field('issue[title]') +shared_examples "creating an issue for a discussion" do + it "shows an issue with the title filled in" do + title_field = page.find_field("issue[title]") expect(title_field.value).to include(merge_request.title) end - it 'has a mention of the discussion in the description' do - description_field = page.find_field('issue[description]') + it "has a mention of the discussion in the description" do + description_field = page.find_field("issue[description]") expect(description_field.value).to include(discussion.first_note.note) end - it 'can create a new issue for the project' do - expect { click_button 'Submit issue' }.to change { project.issues.reload.size }.by(1) + it "can create a new issue for the project" do + expect { click_button "Submit issue" }.to change { project.issues.reload.size }.by(1) end - it 'resolves the discussion in the merge request' do - click_button 'Submit issue' + it "resolves the discussion in the merge request" do + click_button "Submit issue" discussion.first_note.reload expect(discussion.resolved?).to eq(true) end - it 'shows a flash messaage after resolving a discussion' do - click_button 'Submit issue' + it "shows a flash messaage after resolving a discussion" do + click_button "Submit issue" - page.within '.flash-notice' do + page.within ".flash-notice" do # Only check for the word 'Resolved' since the spec might have resolved # multiple discussions - expect(page).to have_content('Resolved') + expect(page).to have_content("Resolved") end end - it 'has a hidden field for the merge request' do - merge_request_field = find('#merge_request_to_resolve_discussions_of', visible: false) + it "has a hidden field for the merge request" do + merge_request_field = find("#merge_request_to_resolve_discussions_of", visible: false) expect(merge_request_field.value).to eq(merge_request.iid.to_s) end diff --git a/spec/support/features/variable_list_shared_examples.rb b/spec/support/features/variable_list_shared_examples.rb index 73156d18c1b..c6b28b3161e 100644 --- a/spec/support/features/variable_list_shared_examples.rb +++ b/spec/support/features/variable_list_shared_examples.rb @@ -1,317 +1,317 @@ -shared_examples 'variable list' do - it 'shows list of variables' do - page.within('.js-ci-variable-list-section') do - expect(first('.js-ci-variable-input-key').value).to eq(variable.key) +shared_examples "variable list" do + it "shows list of variables" do + page.within(".js-ci-variable-list-section") do + expect(first(".js-ci-variable-input-key").value).to eq(variable.key) end end - it 'adds new CI variable' do - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('key') - find('.js-ci-variable-input-value').set('key_value') + it "adds new CI variable" do + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("key") + find(".js-ci-variable-input-value").set("key_value") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path # We check the first row because it re-sorts to alphabetical order on refresh - page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do - expect(find('.js-ci-variable-input-key').value).to eq('key') - expect(find('.js-ci-variable-input-value', visible: false).value).to eq('key_value') + page.within(".js-ci-variable-list-section .js-row:nth-child(1)") do + expect(find(".js-ci-variable-input-key").value).to eq("key") + expect(find(".js-ci-variable-input-value", visible: false).value).to eq("key_value") end end - it 'adds empty variable' do - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('key') - find('.js-ci-variable-input-value').set('') + it "adds empty variable" do + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("key") + find(".js-ci-variable-input-value").set("") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path # We check the first row because it re-sorts to alphabetical order on refresh - page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do - expect(find('.js-ci-variable-input-key').value).to eq('key') - expect(find('.js-ci-variable-input-value', visible: false).value).to eq('') + page.within(".js-ci-variable-list-section .js-row:nth-child(1)") do + expect(find(".js-ci-variable-input-key").value).to eq("key") + expect(find(".js-ci-variable-input-value", visible: false).value).to eq("") end end - it 'adds new protected variable' do - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('key') - find('.js-ci-variable-input-value').set('key_value') - find('.ci-variable-protected-item .js-project-feature-toggle').click + it "adds new protected variable" do + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("key") + find(".js-ci-variable-input-value").set("key_value") + find(".ci-variable-protected-item .js-project-feature-toggle").click - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('true') + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("true") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path # We check the first row because it re-sorts to alphabetical order on refresh - page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do - expect(find('.js-ci-variable-input-key').value).to eq('key') - expect(find('.js-ci-variable-input-value', visible: false).value).to eq('key_value') - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('true') + page.within(".js-ci-variable-list-section .js-row:nth-child(1)") do + expect(find(".js-ci-variable-input-key").value).to eq("key") + expect(find(".js-ci-variable-input-value", visible: false).value).to eq("key_value") + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("true") end end - context 'defaults to the application setting' do - context 'application setting is true' do + context "defaults to the application setting" do + context "application setting is true" do before do stub_application_setting(protected_ci_variables: true) visit page_path end - it 'defaults to protected' do - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('key') + it "defaults to protected" do + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("key") end - values = all('.js-ci-variable-input-protected', visible: false).map(&:value) + values = all(".js-ci-variable-input-protected", visible: false).map(&:value) - expect(values).to eq %w(false true true) + expect(values).to eq %w[false true true] end - it 'shows a message regarding the changed default' do - expect(page).to have_content 'Environment variables are configured by your administrator to be protected by default' + it "shows a message regarding the changed default" do + expect(page).to have_content "Environment variables are configured by your administrator to be protected by default" end end - context 'application setting is false' do + context "application setting is false" do before do stub_application_setting(protected_ci_variables: false) visit page_path end - it 'defaults to unprotected' do - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('key') + it "defaults to unprotected" do + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("key") end - values = all('.js-ci-variable-input-protected', visible: false).map(&:value) + values = all(".js-ci-variable-input-protected", visible: false).map(&:value) - expect(values).to eq %w(false false false) + expect(values).to eq %w[false false false] end - it 'does not show a message regarding the default' do - expect(page).not_to have_content 'Environment variables are configured by your administrator to be protected by default' + it "does not show a message regarding the default" do + expect(page).not_to have_content "Environment variables are configured by your administrator to be protected by default" end end end - it 'reveals and hides variables' do - page.within('.js-ci-variable-list-section') do - expect(first('.js-ci-variable-input-key').value).to eq(variable.key) - expect(first('.js-ci-variable-input-value', visible: false).value).to eq(variable.value) - expect(page).to have_content('*' * 20) + it "reveals and hides variables" do + page.within(".js-ci-variable-list-section") do + expect(first(".js-ci-variable-input-key").value).to eq(variable.key) + expect(first(".js-ci-variable-input-value", visible: false).value).to eq(variable.value) + expect(page).to have_content("*" * 20) - click_button('Reveal value') + click_button("Reveal value") - expect(first('.js-ci-variable-input-key').value).to eq(variable.key) - expect(first('.js-ci-variable-input-value').value).to eq(variable.value) - expect(page).not_to have_content('*' * 20) + expect(first(".js-ci-variable-input-key").value).to eq(variable.key) + expect(first(".js-ci-variable-input-value").value).to eq(variable.value) + expect(page).not_to have_content("*" * 20) - click_button('Hide value') + click_button("Hide value") - expect(first('.js-ci-variable-input-key').value).to eq(variable.key) - expect(first('.js-ci-variable-input-value', visible: false).value).to eq(variable.value) - expect(page).to have_content('*' * 20) + expect(first(".js-ci-variable-input-key").value).to eq(variable.key) + expect(first(".js-ci-variable-input-value", visible: false).value).to eq(variable.value) + expect(page).to have_content("*" * 20) end end - it 'deletes variable' do - page.within('.js-ci-variable-list-section') do - expect(page).to have_selector('.js-row', count: 2) + it "deletes variable" do + page.within(".js-ci-variable-list-section") do + expect(page).to have_selector(".js-row", count: 2) - first('.js-row-remove-button').click + first(".js-row-remove-button").click - click_button('Save variables') + click_button("Save variables") wait_for_requests - expect(page).to have_selector('.js-row', count: 1) + expect(page).to have_selector(".js-row", count: 1) end end - it 'edits variable' do - page.within('.js-ci-variable-list-section') do - click_button('Reveal value') + it "edits variable" do + page.within(".js-ci-variable-list-section") do + click_button("Reveal value") - page.within('.js-row:nth-child(1)') do - find('.js-ci-variable-input-key').set('new_key') - find('.js-ci-variable-input-value').set('new_value') + page.within(".js-row:nth-child(1)") do + find(".js-ci-variable-input-key").set("new_key") + find(".js-ci-variable-input-value").set("new_value") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path - page.within('.js-row:nth-child(1)') do - expect(find('.js-ci-variable-input-key').value).to eq('new_key') - expect(find('.js-ci-variable-input-value', visible: false).value).to eq('new_value') + page.within(".js-row:nth-child(1)") do + expect(find(".js-ci-variable-input-key").value).to eq("new_key") + expect(find(".js-ci-variable-input-value", visible: false).value).to eq("new_value") end end end - it 'edits variable with empty value' do - page.within('.js-ci-variable-list-section') do - click_button('Reveal value') + it "edits variable with empty value" do + page.within(".js-ci-variable-list-section") do + click_button("Reveal value") - page.within('.js-row:nth-child(1)') do - find('.js-ci-variable-input-key').set('new_key') - find('.js-ci-variable-input-value').set('') + page.within(".js-row:nth-child(1)") do + find(".js-ci-variable-input-key").set("new_key") + find(".js-ci-variable-input-value").set("") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path - page.within('.js-row:nth-child(1)') do - expect(find('.js-ci-variable-input-key').value).to eq('new_key') - expect(find('.js-ci-variable-input-value', visible: false).value).to eq('') + page.within(".js-row:nth-child(1)") do + expect(find(".js-ci-variable-input-key").value).to eq("new_key") + expect(find(".js-ci-variable-input-value", visible: false).value).to eq("") end end end - it 'edits variable to be protected' do + it "edits variable to be protected" do # Create the unprotected variable - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('unprotected_key') - find('.js-ci-variable-input-value').set('unprotected_value') + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("unprotected_key") + find(".js-ci-variable-input-value").set("unprotected_value") - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('false') + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("false") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path # We check the first row because it re-sorts to alphabetical order on refresh - page.within('.js-ci-variable-list-section .js-row:nth-child(2)') do - find('.ci-variable-protected-item .js-project-feature-toggle').click + page.within(".js-ci-variable-list-section .js-row:nth-child(2)") do + find(".ci-variable-protected-item .js-project-feature-toggle").click - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('true') + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("true") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path # We check the first row because it re-sorts to alphabetical order on refresh - page.within('.js-ci-variable-list-section .js-row:nth-child(2)') do - expect(find('.js-ci-variable-input-key').value).to eq('unprotected_key') - expect(find('.js-ci-variable-input-value', visible: false).value).to eq('unprotected_value') - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('true') + page.within(".js-ci-variable-list-section .js-row:nth-child(2)") do + expect(find(".js-ci-variable-input-key").value).to eq("unprotected_key") + expect(find(".js-ci-variable-input-value", visible: false).value).to eq("unprotected_value") + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("true") end end - it 'edits variable to be unprotected' do + it "edits variable to be unprotected" do # Create the protected variable - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('protected_key') - find('.js-ci-variable-input-value').set('protected_value') - find('.ci-variable-protected-item .js-project-feature-toggle').click + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("protected_key") + find(".js-ci-variable-input-value").set("protected_value") + find(".ci-variable-protected-item .js-project-feature-toggle").click - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('true') + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("true") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path - page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do - find('.ci-variable-protected-item .js-project-feature-toggle').click + page.within(".js-ci-variable-list-section .js-row:nth-child(1)") do + find(".ci-variable-protected-item .js-project-feature-toggle").click - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('false') + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("false") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path - page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do - expect(find('.js-ci-variable-input-key').value).to eq('protected_key') - expect(find('.js-ci-variable-input-value', visible: false).value).to eq('protected_value') - expect(find('.js-ci-variable-input-protected', visible: false).value).to eq('false') + page.within(".js-ci-variable-list-section .js-row:nth-child(1)") do + expect(find(".js-ci-variable-input-key").value).to eq("protected_key") + expect(find(".js-ci-variable-input-value", visible: false).value).to eq("protected_value") + expect(find(".js-ci-variable-input-protected", visible: false).value).to eq("false") end end - it 'handles multiple edits and deletion in the middle' do - page.within('.js-ci-variable-list-section') do + it "handles multiple edits and deletion in the middle" do + page.within(".js-ci-variable-list-section") do # Create 2 variables - page.within('.js-row:last-child') do - find('.js-ci-variable-input-key').set('akey') - find('.js-ci-variable-input-value').set('akeyvalue') + page.within(".js-row:last-child") do + find(".js-ci-variable-input-key").set("akey") + find(".js-ci-variable-input-value").set("akeyvalue") end - page.within('.js-row:last-child') do - find('.js-ci-variable-input-key').set('zkey') - find('.js-ci-variable-input-value').set('zkeyvalue') + page.within(".js-row:last-child") do + find(".js-ci-variable-input-key").set("zkey") + find(".js-ci-variable-input-value").set("zkeyvalue") end - click_button('Save variables') + click_button("Save variables") wait_for_requests - expect(page).to have_selector('.js-row', count: 4) + expect(page).to have_selector(".js-row", count: 4) # Remove the `akey` variable - page.within('.js-row:nth-child(2)') do - first('.js-row-remove-button').click + page.within(".js-row:nth-child(2)") do + first(".js-row-remove-button").click end # Add another variable - page.within('.js-row:last-child') do - find('.js-ci-variable-input-key').set('ckey') - find('.js-ci-variable-input-value').set('ckeyvalue') + page.within(".js-row:last-child") do + find(".js-ci-variable-input-key").set("ckey") + find(".js-ci-variable-input-value").set("ckeyvalue") end - click_button('Save variables') + click_button("Save variables") wait_for_requests visit page_path # Expect to find 3 variables(4 rows) in alphbetical order - expect(page).to have_selector('.js-row', count: 4) - row_keys = all('.js-ci-variable-input-key') - expect(row_keys[0].value).to eq('ckey') - expect(row_keys[1].value).to eq('test_key') - expect(row_keys[2].value).to eq('zkey') - expect(row_keys[3].value).to eq('') + expect(page).to have_selector(".js-row", count: 4) + row_keys = all(".js-ci-variable-input-key") + expect(row_keys[0].value).to eq("ckey") + expect(row_keys[1].value).to eq("test_key") + expect(row_keys[2].value).to eq("zkey") + expect(row_keys[3].value).to eq("") end end - it 'shows validation error box about duplicate keys' do - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('samekey') - find('.js-ci-variable-input-value').set('value1') + it "shows validation error box about duplicate keys" do + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("samekey") + find(".js-ci-variable-input-value").set("value1") end - page.within('.js-ci-variable-list-section .js-row:last-child') do - find('.js-ci-variable-input-key').set('samekey') - find('.js-ci-variable-input-value').set('value2') + page.within(".js-ci-variable-list-section .js-row:last-child") do + find(".js-ci-variable-input-key").set("samekey") + find(".js-ci-variable-input-value").set("value2") end - click_button('Save variables') + click_button("Save variables") wait_for_requests - expect(all('.js-ci-variable-list-section .js-ci-variable-error-box ul li').count).to eq(1) + expect(all(".js-ci-variable-list-section .js-ci-variable-error-box ul li").count).to eq(1) # We check the first row because it re-sorts to alphabetical order on refresh - page.within('.js-ci-variable-list-section') do - expect(find('.js-ci-variable-error-box')).to have_content(/Validation failed Variables have duplicate values \(.+\)/) + page.within(".js-ci-variable-list-section") do + expect(find(".js-ci-variable-error-box")).to have_content(/Validation failed Variables have duplicate values \(.+\)/) end end end diff --git a/spec/support/generate-seed-repo-rb b/spec/support/generate-seed-repo-rb index bee9d419376..a0d496445e6 100755 --- a/spec/support/generate-seed-repo-rb +++ b/spec/support/generate-seed-repo-rb @@ -12,16 +12,16 @@ # # -require 'erb' -require 'tempfile' +require "erb" +require "tempfile" -SOURCE = File.expand_path('gitlab-git-test.git', __dir__).freeze -SCRIPT_NAME = 'generate-seed-repo-rb'.freeze -REPO_NAME = 'gitlab-git-test.git'.freeze +SOURCE = File.expand_path("gitlab-git-test.git", __dir__).freeze +SCRIPT_NAME = "generate-seed-repo-rb".freeze +REPO_NAME = "gitlab-git-test.git".freeze def main Dir.mktmpdir do |dir| - unless system(*%W[git clone --bare #{SOURCE} #{REPO_NAME}], chdir: dir) + unless system("git", "clone", "--bare", SOURCE.to_s, REPO_NAME.to_s, chdir: dir) abort "git clone failed" end @@ -32,8 +32,8 @@ def main end def capture!(cmd, dir) - output = IO.popen(cmd, 'r', chdir: dir) { |io| io.read } - raise "command failed with #{$?}: #{cmd.join(' ')}" unless $?.success? + output = IO.popen(cmd, "r", chdir: dir) { |io| io.read } + raise "command failed with #{$?}: #{cmd.join(" ")}" unless $?.success? output.chomp end diff --git a/spec/support/google_api/cloud_platform_helpers.rb b/spec/support/google_api/cloud_platform_helpers.rb index 2fdbddd40c2..0084e7b30d8 100644 --- a/spec/support/google_api/cloud_platform_helpers.rb +++ b/spec/support/google_api/cloud_platform_helpers.rb @@ -1,12 +1,12 @@ module GoogleApi module CloudPlatformHelpers def stub_google_api_validate_token - request.session[GoogleApi::CloudPlatform::Client.session_key_for_token] = 'token' + request.session[GoogleApi::CloudPlatform::Client.session_key_for_token] = "token" request.session[GoogleApi::CloudPlatform::Client.session_key_for_expires_at] = 1.hour.since.to_i.to_s end def stub_google_api_expired_token - request.session[GoogleApi::CloudPlatform::Client.session_key_for_token] = 'token' + request.session[GoogleApi::CloudPlatform::Client.session_key_for_token] = "token" request.session[GoogleApi::CloudPlatform::Client.session_key_for_expires_at] = 1.hour.ago.to_i.to_s end @@ -71,11 +71,11 @@ module GoogleApi end def cloud_platform_response(body) - { status: 200, headers: { 'Content-Type' => 'application/json' }, body: body.to_json } + {status: 200, headers: {"Content-Type" => "application/json"}, body: body.to_json} end def load_sample_cert - pem_file = File.expand_path(Rails.root.join('spec/fixtures/clusters/sample_cert.pem')) + pem_file = File.expand_path(Rails.root.join("spec/fixtures/clusters/sample_cert.pem")) Base64.encode64(File.read(pem_file)) end @@ -86,51 +86,51 @@ module GoogleApi # rubocop:disable Metrics/PerceivedComplexity def cloud_platform_cluster_body(**options) { - "name": options[:name] || 'string', - "description": options[:description] || 'string', - "initialNodeCount": options[:initialNodeCount] || 'number', + "name": options[:name] || "string", + "description": options[:description] || "string", + "initialNodeCount": options[:initialNodeCount] || "number", "masterAuth": { - "username": options[:username] || 'string', - "password": options[:password] || 'string', + "username": options[:username] || "string", + "password": options[:password] || "string", "clusterCaCertificate": options[:clusterCaCertificate] || load_sample_cert, - "clientCertificate": options[:clientCertificate] || 'string', - "clientKey": options[:clientKey] || 'string' + "clientCertificate": options[:clientCertificate] || "string", + "clientKey": options[:clientKey] || "string", }, - "loggingService": options[:loggingService] || 'string', - "monitoringService": options[:monitoringService] || 'string', - "network": options[:network] || 'string', - "clusterIpv4Cidr": options[:clusterIpv4Cidr] || 'string', - "subnetwork": options[:subnetwork] || 'string', - "enableKubernetesAlpha": options[:enableKubernetesAlpha] || 'boolean', - "labelFingerprint": options[:labelFingerprint] || 'string', - "selfLink": options[:selfLink] || 'string', - "zone": options[:zone] || 'string', - "endpoint": options[:endpoint] || 'string', - "initialClusterVersion": options[:initialClusterVersion] || 'string', - "currentMasterVersion": options[:currentMasterVersion] || 'string', - "currentNodeVersion": options[:currentNodeVersion] || 'string', - "createTime": options[:createTime] || 'string', - "status": options[:status] || 'RUNNING', - "statusMessage": options[:statusMessage] || 'string', - "nodeIpv4CidrSize": options[:nodeIpv4CidrSize] || 'number', - "servicesIpv4Cidr": options[:servicesIpv4Cidr] || 'string', - "currentNodeCount": options[:currentNodeCount] || 'number', - "expireTime": options[:expireTime] || 'string' + "loggingService": options[:loggingService] || "string", + "monitoringService": options[:monitoringService] || "string", + "network": options[:network] || "string", + "clusterIpv4Cidr": options[:clusterIpv4Cidr] || "string", + "subnetwork": options[:subnetwork] || "string", + "enableKubernetesAlpha": options[:enableKubernetesAlpha] || "boolean", + "labelFingerprint": options[:labelFingerprint] || "string", + "selfLink": options[:selfLink] || "string", + "zone": options[:zone] || "string", + "endpoint": options[:endpoint] || "string", + "initialClusterVersion": options[:initialClusterVersion] || "string", + "currentMasterVersion": options[:currentMasterVersion] || "string", + "currentNodeVersion": options[:currentNodeVersion] || "string", + "createTime": options[:createTime] || "string", + "status": options[:status] || "RUNNING", + "statusMessage": options[:statusMessage] || "string", + "nodeIpv4CidrSize": options[:nodeIpv4CidrSize] || "number", + "servicesIpv4Cidr": options[:servicesIpv4Cidr] || "string", + "currentNodeCount": options[:currentNodeCount] || "number", + "expireTime": options[:expireTime] || "string", } end def cloud_platform_operation_body(**options) { - "name": options[:name] || 'operation-1234567891234-1234567', - "zone": options[:zone] || 'us-central1-a', - "operationType": options[:operationType] || 'CREATE_CLUSTER', - "status": options[:status] || 'PENDING', - "detail": options[:detail] || 'detail', - "statusMessage": options[:statusMessage] || '', - "selfLink": options[:selfLink] || 'https://container.googleapis.com/v1/projects/123456789101/zones/us-central1-a/operations/operation-1234567891234-1234567', - "targetLink": options[:targetLink] || 'https://container.googleapis.com/v1/projects/123456789101/zones/us-central1-a/clusters/test-cluster', - "startTime": options[:startTime] || '2017-09-13T16:49:13.055601589Z', - "endTime": options[:endTime] || '' + "name": options[:name] || "operation-1234567891234-1234567", + "zone": options[:zone] || "us-central1-a", + "operationType": options[:operationType] || "CREATE_CLUSTER", + "status": options[:status] || "PENDING", + "detail": options[:detail] || "detail", + "statusMessage": options[:statusMessage] || "", + "selfLink": options[:selfLink] || "https://container.googleapis.com/v1/projects/123456789101/zones/us-central1-a/operations/operation-1234567891234-1234567", + "targetLink": options[:targetLink] || "https://container.googleapis.com/v1/projects/123456789101/zones/us-central1-a/clusters/test-cluster", + "startTime": options[:startTime] || "2017-09-13T16:49:13.055601589Z", + "endTime": options[:endTime] || "", } end @@ -145,19 +145,19 @@ module GoogleApi "createTime": "2017-12-16T01:48:29.129Z", "parent": { "type": "organization", - "id": "12345" - } - } - ] + "id": "12345", + }, + }, + ], } end def cloud_platform_projects_billing_info_body(project_id, billing_enabled) { "name": "projects/#{project_id}/billingInfo", - "projectId": "#{project_id}", + "projectId": project_id.to_s, "billingAccountName": "account-name", - "billingEnabled": billing_enabled + "billingEnabled": billing_enabled, } end end diff --git a/spec/support/helpers/api_helpers.rb b/spec/support/helpers/api_helpers.rb index 4a9ce9beb78..b7cc583f79e 100644 --- a/spec/support/helpers/api_helpers.rb +++ b/spec/support/helpers/api_helpers.rb @@ -30,7 +30,7 @@ module ApiHelpers end if query_string - full_path << (path.index('?') ? '&' : '?') + full_path << (path.index("?") ? "&" : "?") full_path << query_string end @@ -41,6 +41,6 @@ module ApiHelpers expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array - expect(json_response.map { |item| item['id'] }).to eq(Array(items)) + expect(json_response.map { |item| item["id"] }).to eq(Array(items)) end end diff --git a/spec/support/helpers/assets_helpers.rb b/spec/support/helpers/assets_helpers.rb index 09bbf451671..67519c30c0d 100644 --- a/spec/support/helpers/assets_helpers.rb +++ b/spec/support/helpers/assets_helpers.rb @@ -6,7 +6,7 @@ module AssetsHelpers # # Sprockets doesn't provide one method to access an asset for both cases. def find_asset(asset_name) - if ENV['CI'] + if ENV["CI"] Sprockets::Railtie.build_environment(Rails.application, true)[asset_name] else Rails.application.assets.find_asset(asset_name) diff --git a/spec/support/helpers/bare_repo_operations.rb b/spec/support/helpers/bare_repo_operations.rb index 3f4a4243cb6..c2273fc941f 100644 --- a/spec/support/helpers/bare_repo_operations.rb +++ b/spec/support/helpers/bare_repo_operations.rb @@ -1,4 +1,4 @@ -require 'zlib' +require "zlib" class BareRepoOperations include Gitlab::Popen @@ -8,45 +8,45 @@ class BareRepoOperations end def commit_tree(tree_id, msg, parent: Gitlab::Git::EMPTY_TREE_ID) - commit_tree_args = ['commit-tree', tree_id, '-m', msg] - commit_tree_args += ['-p', parent] unless parent == Gitlab::Git::EMPTY_TREE_ID + commit_tree_args = ["commit-tree", tree_id, "-m", msg] + commit_tree_args += ["-p", parent] unless parent == Gitlab::Git::EMPTY_TREE_ID commit_id = execute(commit_tree_args) commit_id[0] end # Based on https://stackoverflow.com/a/25556917/1856239 - def commit_file(file, dst_path, branch = 'master') - head_id = execute(['show', '--format=format:%H', '--no-patch', branch], allow_failure: true)[0] || Gitlab::Git::EMPTY_TREE_ID + def commit_file(file, dst_path, branch = "master") + head_id = execute(["show", "--format=format:%H", "--no-patch", branch], allow_failure: true)[0] || Gitlab::Git::EMPTY_TREE_ID - execute(['read-tree', '--empty']) - execute(['read-tree', head_id]) + execute(["read-tree", "--empty"]) + execute(["read-tree", head_id]) - blob_id = execute(['hash-object', '--stdin', '-w']) do |stdin| + blob_id = execute(["hash-object", "--stdin", "-w"]) { |stdin| stdin.write(file.read) - end + } - execute(['update-index', '--add', '--cacheinfo', '100644', blob_id[0], dst_path]) + execute(["update-index", "--add", "--cacheinfo", "100644", blob_id[0], dst_path]) - tree_id = execute(['write-tree']) + tree_id = execute(["write-tree"]) commit_id = commit_tree(tree_id[0], "Add #{dst_path}", parent: head_id) - execute(['update-ref', "refs/heads/#{branch}", commit_id]) + execute(["update-ref", "refs/heads/#{branch}", commit_id]) end private def execute(args, allow_failure: false) - output, status = popen(base_args + args, nil) do |stdin| + output, status = popen(base_args + args, nil) { |stdin| yield stdin if block_given? - end + } unless status.zero? if allow_failure return [] else - raise "Got a non-zero exit code while calling out `#{args.join(' ')}`: #{output}" + raise "Got a non-zero exit code while calling out `#{args.join(" ")}`: #{output}" end end @@ -56,7 +56,7 @@ class BareRepoOperations def base_args [ Gitlab.config.git.bin_path, - "--git-dir=#{@path_to_repo}" + "--git-dir=#{@path_to_repo}", ] end end diff --git a/spec/support/helpers/board_helpers.rb b/spec/support/helpers/board_helpers.rb index b85fde222ea..d67302584ec 100644 --- a/spec/support/helpers/board_helpers.rb +++ b/spec/support/helpers/board_helpers.rb @@ -1,7 +1,7 @@ module BoardHelpers def click_card(card) within card do - first('.board-card-number').click + first(".board-card-number").click end wait_for_sidebar diff --git a/spec/support/helpers/capybara_helpers.rb b/spec/support/helpers/capybara_helpers.rb index bcc2df44708..88971ed7968 100644 --- a/spec/support/helpers/capybara_helpers.rb +++ b/spec/support/helpers/capybara_helpers.rb @@ -32,12 +32,12 @@ module CapybaraHelpers # def refresh url = current_url - visit 'about:blank' + visit "about:blank" visit url end # Simulate a browser restart by clearing the session cookie. def clear_browser_session - page.driver.browser.manage.delete_cookie('_gitlab_session') + page.driver.browser.manage.delete_cookie("_gitlab_session") end end diff --git a/spec/support/helpers/ci_artifact_metadata_generator.rb b/spec/support/helpers/ci_artifact_metadata_generator.rb index ef638d59d2d..c8bcad34415 100644 --- a/spec/support/helpers/ci_artifact_metadata_generator.rb +++ b/spec/support/helpers/ci_artifact_metadata_generator.rb @@ -13,7 +13,7 @@ class CiArtifactMetadataGenerator end def add_entry(filename) - @entries[filename] = { CRC: rand(0xfffffff), Comment: FFaker::Lorem.sentence(10) } + @entries[filename] = {CRC: rand(0xfffffff), Comment: FFaker::Lorem.sentence(10)} end def write @@ -30,7 +30,7 @@ class CiArtifactMetadataGenerator end def write_errors - write_string('{}') + write_string("{}") end def write_entries @@ -41,7 +41,7 @@ class CiArtifactMetadataGenerator end def write_string(data) - bytes = [data.length].pack('L>') + bytes = [data.length].pack("L>") output.write(bytes) output.write(data) end diff --git a/spec/support/helpers/cookie_helper.rb b/spec/support/helpers/cookie_helper.rb index 5ff7b0b68c9..d35d907ae60 100644 --- a/spec/support/helpers/cookie_helper.rb +++ b/spec/support/helpers/cookie_helper.rb @@ -13,7 +13,7 @@ module CookieHelper def selenium_set_cookie(name, value, options = {}) # Selenium driver will not set cookies for a given domain when the browser is at `about:blank`. # It also doesn't appear to allow overriding the cookie path. loading `/` is the most inclusive. - visit options.fetch(:path, '/') unless on_a_page? + visit options.fetch(:path, "/") unless on_a_page? page.driver.browser.manage.add_cookie(name: name, value: value, **options) end @@ -29,6 +29,6 @@ module CookieHelper def on_a_page? current_url = Capybara.current_session.driver.browser.current_url - current_url && current_url != '' && current_url != 'about:blank' && current_url != 'data:,' + current_url && current_url != "" && current_url != "about:blank" && current_url != "data:," end end diff --git a/spec/support/helpers/cycle_analytics_helpers.rb b/spec/support/helpers/cycle_analytics_helpers.rb index ecefdc23811..6ab7beca91c 100644 --- a/spec/support/helpers/cycle_analytics_helpers.rb +++ b/spec/support/helpers/cycle_analytics_helpers.rb @@ -2,7 +2,7 @@ module CycleAnalyticsHelpers include GitHelpers def create_commit_referencing_issue(issue, branch_name: generate(:branch)) - project.repository.add_branch(user, branch_name, 'master') + project.repository.add_branch(user, branch_name, "master") create_commit("Commit for ##{issue.iid}", issue.project, user, branch_name) end @@ -14,20 +14,20 @@ module CycleAnalyticsHelpers mock_gitaly_multi_action_dates(repository, commit_time) end - commit_shas = Array.new(count) do |index| + commit_shas = Array.new(count) { |index| commit_sha = repository.create_file(user, generate(:branch), "content", message: message, branch_name: branch_name) repository.commit(commit_sha) commit_sha - end + } return if skip_push_handler GitPushService.new(project, - user, - oldrev: oldrev, - newrev: commit_shas.last, - ref: 'refs/heads/master').execute + user, + oldrev: oldrev, + newrev: commit_shas.last, + ref: "refs/heads/master").execute end def create_cycle(user, project, issue, mr, milestone, pipeline) @@ -42,10 +42,10 @@ module CycleAnalyticsHelpers ci_build end - def create_merge_request_closing_issue(user, project, issue, message: nil, source_branch: nil, commit_message: 'commit message') + def create_merge_request_closing_issue(user, project, issue, message: nil, source_branch: nil, commit_message: "commit message") if !source_branch || project.repository.commit(source_branch).blank? source_branch = generate(:branch) - project.repository.add_branch(user, source_branch, 'master') + project.repository.add_branch(user, source_branch, "master") end # Cycle analytic specs often test with frozen times, which causes metrics to be @@ -55,10 +55,10 @@ module CycleAnalyticsHelpers create_commit(commit_message, project, user, source_branch, commit_time: Time.now + 1.second, skip_push_handler: true) opts = { - title: 'Awesome merge_request', + title: "Awesome merge_request", description: message || "Fixes #{issue.to_reference}", source_branch: source_branch, - target_branch: 'master' + target_branch: "master", } mr = MergeRequests::CreateService.new(project, user, opts).execute @@ -68,18 +68,18 @@ module CycleAnalyticsHelpers def merge_merge_requests_closing_issue(user, project, issue) merge_requests = Issues::ReferencedMergeRequestsService - .new(project, user) - .closed_by_merge_requests(issue) + .new(project, user) + .closed_by_merge_requests(issue) merge_requests.each { |merge_request| MergeRequests::MergeService.new(project, user).execute(merge_request) } end - def deploy_master(user, project, environment: 'production') + def deploy_master(user, project, environment: "production") dummy_job = case environment - when 'production' + when "production" dummy_production_job(user, project) - when 'staging' + when "staging" dummy_staging_job(user, project) else raise ArgumentError @@ -89,17 +89,17 @@ module CycleAnalyticsHelpers end def dummy_production_job(user, project) - new_dummy_job(user, project, 'production') + new_dummy_job(user, project, "production") end def dummy_staging_job(user, project) - new_dummy_job(user, project, 'staging') + new_dummy_job(user, project, "staging") end def dummy_pipeline(project) create(:ci_pipeline, - sha: project.repository.commit('master').sha, - ref: 'master', + sha: project.repository.commit("master").sha, + ref: "master", source: :push, project: project, protected: false) @@ -110,10 +110,10 @@ module CycleAnalyticsHelpers project: project, user: user, environment: environment, - ref: 'master', + ref: "master", tag: false, - name: 'dummy', - stage: 'dummy', + name: "dummy", + stage: "dummy", pipeline: dummy_pipeline(project), protected: false) end diff --git a/spec/support/helpers/devise_helpers.rb b/spec/support/helpers/devise_helpers.rb index d32bc2424c0..029934bb466 100644 --- a/spec/support/helpers/devise_helpers.rb +++ b/spec/support/helpers/devise_helpers.rb @@ -4,7 +4,7 @@ module DeviseHelpers def set_devise_mapping(context:) env = env_from_context(context) - env['devise.mapping'] = Devise.mappings[:user] if env + env["devise.mapping"] = Devise.mappings[:user] if env end def env_from_context(context) diff --git a/spec/support/helpers/drag_to_helper.rb b/spec/support/helpers/drag_to_helper.rb index 6d53ad0b602..c477fe39eac 100644 --- a/spec/support/helpers/drag_to_helper.rb +++ b/spec/support/helpers/drag_to_helper.rb @@ -1,5 +1,5 @@ module DragTo - def drag_to(list_from_index: 0, from_index: 0, to_index: 0, list_to_index: 0, selector: '', scrollable: 'body', duration: 1000) + def drag_to(list_from_index: 0, from_index: 0, to_index: 0, list_to_index: 0, selector: "", scrollable: "body", duration: 1000) evaluate_script("simulateDrag({scrollable: $('#{scrollable}').get(0), duration: #{duration}, from: {el: $('#{selector}').eq(#{list_from_index}).get(0), index: #{from_index}}, to: {el: $('#{selector}').eq(#{list_to_index}).get(0), index: #{to_index}}});") Timeout.timeout(Capybara.default_max_wait_time) do @@ -8,6 +8,6 @@ module DragTo end def drag_active? - page.evaluate_script('window.SIMULATE_DRAG_ACTIVE').nonzero? + page.evaluate_script("window.SIMULATE_DRAG_ACTIVE").nonzero? end end diff --git a/spec/support/helpers/dropzone_helper.rb b/spec/support/helpers/dropzone_helper.rb index fe72d320fcf..bb6570c9e73 100644 --- a/spec/support/helpers/dropzone_helper.rb +++ b/spec/support/helpers/dropzone_helper.rb @@ -23,7 +23,7 @@ module DropzoneHelper JS # Attach files to the fake input selector with Capybara - attach_file('fakeFileInput', files) + attach_file("fakeFileInput", files) # Manually trigger a Dropzone "drop" event with the fake input's file list page.execute_script <<-JS.strip_heredoc @@ -51,7 +51,7 @@ module DropzoneHelper if wait_for_queuecomplete # Wait until Dropzone's fired `queuecomplete` - loop until page.evaluate_script('window._dropzoneComplete === true') + loop until page.evaluate_script("window._dropzoneComplete === true") end end @@ -64,7 +64,7 @@ module DropzoneHelper JS # Attach the file to the fake input selector with Capybara - attach_file('fakeFileInput', file_path) + attach_file("fakeFileInput", file_path) # Add the file to a fileList array and trigger the fake drop event page.execute_script <<-JS diff --git a/spec/support/helpers/email_helpers.rb b/spec/support/helpers/email_helpers.rb index ad6e1064499..2bf9d244e81 100644 --- a/spec/support/helpers/email_helpers.rb +++ b/spec/support/helpers/email_helpers.rb @@ -36,7 +36,7 @@ module EmailHelpers end def have_referable_subject(referable, include_project: true, reply: false) - prefix = (include_project && referable.project ? "#{referable.project.name} | " : '').freeze + prefix = (include_project && referable.project ? "#{referable.project.name} | " : "").freeze prefix = "Re: #{prefix}" if reply suffix = "#{referable.title} (#{referable.to_reference})" diff --git a/spec/support/helpers/exclusive_lease_helpers.rb b/spec/support/helpers/exclusive_lease_helpers.rb index 383cc7dee81..ed0d25889e0 100644 --- a/spec/support/helpers/exclusive_lease_helpers.rb +++ b/spec/support/helpers/exclusive_lease_helpers.rb @@ -1,5 +1,5 @@ module ExclusiveLeaseHelpers - def stub_exclusive_lease(key = nil, uuid = 'uuid', renew: false, timeout: nil) + def stub_exclusive_lease(key = nil, uuid = "uuid", renew: false, timeout: nil) key ||= instance_of(String) timeout ||= instance_of(Integer) @@ -22,7 +22,7 @@ module ExclusiveLeaseHelpers stub_exclusive_lease(key, nil, timeout: timeout) end - def expect_to_obtain_exclusive_lease(key, uuid = 'uuid', timeout: nil) + def expect_to_obtain_exclusive_lease(key, uuid = "uuid", timeout: nil) lease = stub_exclusive_lease(key, uuid, timeout: timeout) expect(lease).to receive(:try_obtain) diff --git a/spec/support/helpers/expect_offense.rb b/spec/support/helpers/expect_offense.rb index 35718ba90c5..8aed8112518 100644 --- a/spec/support/helpers/expect_offense.rb +++ b/spec/support/helpers/expect_offense.rb @@ -1,4 +1,4 @@ -require 'rubocop/rspec/support' +require "rubocop/rspec/support" # https://github.com/backus/rubocop-rspec/blob/master/spec/support/expect_offense.rb # rubocop-rspec gem extension of RuboCop's ExpectOffense module. @@ -8,7 +8,7 @@ require 'rubocop/rspec/support' module ExpectOffense include RuboCop::RSpec::ExpectOffense - DEFAULT_FILENAME = 'example_spec.rb'.freeze + DEFAULT_FILENAME = "example_spec.rb".freeze def expect_offense(source, filename = DEFAULT_FILENAME) super diff --git a/spec/support/helpers/fake_blob_helpers.rb b/spec/support/helpers/fake_blob_helpers.rb index 801ca8b7412..c864df2fde0 100644 --- a/spec/support/helpers/fake_blob_helpers.rb +++ b/spec/support/helpers/fake_blob_helpers.rb @@ -4,7 +4,7 @@ module FakeBlobHelpers attr_reader :path, :size, :data, :lfs_oid, :lfs_size - def initialize(path: 'file.txt', size: 1.kilobyte, data: 'foo', binary: false, lfs: nil) + def initialize(path: "file.txt", size: 1.kilobyte, data: "foo", binary: false, lfs: nil) @path = path @size = size @data = data @@ -17,7 +17,7 @@ module FakeBlobHelpers end end - alias_method :name, :path + alias name path def id 0 @@ -31,7 +31,7 @@ module FakeBlobHelpers :lfs if @lfs_pointer end - alias_method :external_size, :lfs_size + alias external_size lfs_size end def fake_blob(**kwargs) diff --git a/spec/support/helpers/fake_migration_classes.rb b/spec/support/helpers/fake_migration_classes.rb index c7766df7a52..66054ba753c 100644 --- a/spec/support/helpers/fake_migration_classes.rb +++ b/spec/support/helpers/fake_migration_classes.rb @@ -2,7 +2,7 @@ class FakeRenameReservedPathMigrationV1 < ActiveRecord::Migration[4.2] include Gitlab::Database::RenameReservedPathsMigration::V1 def version - '20170316163845' + "20170316163845" end def name diff --git a/spec/support/helpers/fake_u2f_device.rb b/spec/support/helpers/fake_u2f_device.rb index a7605cd483a..368da8cdaf9 100644 --- a/spec/support/helpers/fake_u2f_device.rb +++ b/spec/support/helpers/fake_u2f_device.rb @@ -7,8 +7,8 @@ class FakeU2fDevice end def respond_to_u2f_registration - app_id = @page.evaluate_script('gon.u2f.app_id') - challenges = @page.evaluate_script('gon.u2f.challenges') + app_id = @page.evaluate_script("gon.u2f.app_id") + challenges = @page.evaluate_script("gon.u2f.challenges") json_response = u2f_device(app_id).register_response(challenges[0]) @@ -20,8 +20,8 @@ class FakeU2fDevice end def respond_to_u2f_authentication - app_id = @page.evaluate_script('gon.u2f.app_id') - challenge = @page.evaluate_script('gon.u2f.challenge') + app_id = @page.evaluate_script("gon.u2f.app_id") + challenge = @page.evaluate_script("gon.u2f.challenge") json_response = u2f_device(app_id).sign_response(challenge) @page.execute_script(" diff --git a/spec/support/helpers/features/list_rows_helpers.rb b/spec/support/helpers/features/list_rows_helpers.rb index 0626415361c..ce1711d13b4 100644 --- a/spec/support/helpers/features/list_rows_helpers.rb +++ b/spec/support/helpers/features/list_rows_helpers.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + # These helpers allow you to access rows in the list # # Usage: @@ -15,11 +16,11 @@ module Spec module Features module ListRowsHelpers def first_row - page.all('ul.content-list > li')[0] + page.all("ul.content-list > li")[0] end def second_row - page.all('ul.content-list > li')[1] + page.all("ul.content-list > li")[1] end end end diff --git a/spec/support/helpers/features/notes_helpers.rb b/spec/support/helpers/features/notes_helpers.rb index 89517fde6e2..ebb5da4736d 100644 --- a/spec/support/helpers/features/notes_helpers.rb +++ b/spec/support/helpers/features/notes_helpers.rb @@ -22,9 +22,9 @@ module Spec end def preview_note(text) - page.within('.js-main-target-form') do - fill_in('note[note]', with: text) - click_on('Preview') + page.within(".js-main-target-form") do + fill_in("note[note]", with: text) + click_on("Preview") end end end diff --git a/spec/support/helpers/features/responsive_table_helpers.rb b/spec/support/helpers/features/responsive_table_helpers.rb index 7a175219fe9..3ba7c5c1f13 100644 --- a/spec/support/helpers/features/responsive_table_helpers.rb +++ b/spec/support/helpers/features/responsive_table_helpers.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + # These helpers allow you to access rows in a responsive table # # Usage: @@ -19,11 +20,11 @@ module Spec module Features module ResponsiveTableHelpers def first_row - page.all('.gl-responsive-table-row')[1] + page.all(".gl-responsive-table-row")[1] end def second_row - page.all('.gl-responsive-table-row')[2] + page.all(".gl-responsive-table-row")[2] end end end diff --git a/spec/support/helpers/features/sorting_helpers.rb b/spec/support/helpers/features/sorting_helpers.rb index 003ecb251fe..b90c5c573e4 100644 --- a/spec/support/helpers/features/sorting_helpers.rb +++ b/spec/support/helpers/features/sorting_helpers.rb @@ -13,9 +13,9 @@ module Spec module Features module SortingHelpers def sort_by(value) - find('.filter-dropdown-container .dropdown').click + find(".filter-dropdown-container .dropdown").click - page.within('ul.dropdown-menu.dropdown-menu-right li') do + page.within("ul.dropdown-menu.dropdown-menu-right li") do click_link(value) end end diff --git a/spec/support/helpers/filter_spec_helper.rb b/spec/support/helpers/filter_spec_helper.rb index 721d359c2ee..25fbfecf0f2 100644 --- a/spec/support/helpers/filter_spec_helper.rb +++ b/spec/support/helpers/filter_spec_helper.rb @@ -45,7 +45,7 @@ module FilterSpecHelper filters = [ Banzai::Filter::AutolinkFilter, - described_class + described_class, ] HTML::Pipeline.new(filters, context) @@ -68,10 +68,10 @@ module FilterSpecHelper # # Returns a String def invalidate_reference(reference) - if reference =~ /\A(.+)?[^\d]\d+\z/ + if /\A(.+)?[^\d]\d+\z/.match?(reference) # Integer-based reference with optional project prefix reference.gsub(/\d+\z/) { |i| i.to_i + 10_000 } - elsif reference =~ /\A(.+@)?(\h{7,40}\z)/ + elsif /\A(.+@)?(\h{7,40}\z)/.match?(reference) # SHA-based reference with optional prefix reference.gsub(/\h{7,40}\z/) { |v| v.reverse } else diff --git a/spec/support/helpers/filtered_search_helpers.rb b/spec/support/helpers/filtered_search_helpers.rb index 6569feec39b..af3e638d584 100644 --- a/spec/support/helpers/filtered_search_helpers.rb +++ b/spec/support/helpers/filtered_search_helpers.rb @@ -1,6 +1,6 @@ module FilteredSearchHelpers def filtered_search - page.find('.filtered-search') + page.find(".filtered-search") end # Enables input to be set (similar to copy and paste) @@ -26,10 +26,10 @@ module FilteredSearchHelpers def select_label_on_dropdown(label_title) input_filtered_search("label:", submit: false) - within('#js-dropdown-label') do + within("#js-dropdown-label") do wait_for_requests - find('li', text: label_title).click + find("li", text: label_title).click end filtered_search.send_keys(:enter) @@ -39,8 +39,8 @@ module FilteredSearchHelpers all_count = open_count + closed_count expect(page).to have_issuable_counts(open: open_count, closed: closed_count, all: all_count) - page.within '.issues-list' do - expect(page).to have_selector('.issue', count: open_count) + page.within ".issues-list" do + expect(page).to have_selector(".issue", count: open_count) end end @@ -52,11 +52,11 @@ module FilteredSearchHelpers end def expect_filtered_search_input(input) - expect(find('.filtered-search').value).to eq(input) + expect(find(".filtered-search").value).to eq(input) end def clear_search_field - find('.filtered-search-box .clear-search').click + find(".filtered-search-box .clear-search").click end def reset_filters @@ -65,79 +65,79 @@ module FilteredSearchHelpers end def init_label_search - filtered_search.set('label:') + filtered_search.set("label:") # This ensures the dropdown is shown - expect(find('#js-dropdown-label')).not_to have_css('.filter-dropdown-loading') + expect(find("#js-dropdown-label")).not_to have_css(".filter-dropdown-loading") end def expect_filtered_search_input_empty - expect(find('.filtered-search').value).to eq('') + expect(find(".filtered-search").value).to eq("") end # Iterates through each visual token inside # .tokens-container to make sure the correct names and values are rendered def expect_tokens(tokens) - page.within '.filtered-search-box .tokens-container' do - page.all(:css, '.tokens-container li .selectable').each_with_index do |el, index| + page.within ".filtered-search-box .tokens-container" do + page.all(:css, ".tokens-container li .selectable").each_with_index do |el, index| token_name = tokens[index][:name] token_value = tokens[index][:value] token_emoji = tokens[index][:emoji_name] - expect(el.find('.name')).to have_content(token_name) + expect(el.find(".name")).to have_content(token_name) if token_value - expect(el.find('.value')).to have_content(token_value) + expect(el.find(".value")).to have_content(token_value) end # gl-emoji content is blank when the emoji unicode is not supported if token_emoji selector = %(gl-emoji[data-name="#{token_emoji}"]) - expect(el.find('.value')).to have_css(selector) + expect(el.find(".value")).to have_css(selector) end end end end def create_token(token_name, token_value = nil, symbol = nil) - { name: token_name, value: "#{symbol}#{token_value}" } + {name: token_name, value: "#{symbol}#{token_value}"} end def author_token(author_name = nil) - create_token('Author', author_name) + create_token("Author", author_name) end def assignee_token(assignee_name = nil) - create_token('Assignee', assignee_name) + create_token("Assignee", assignee_name) end def milestone_token(milestone_name = nil, has_symbol = true) - symbol = has_symbol ? '%' : nil - create_token('Milestone', milestone_name, symbol) + symbol = has_symbol ? "%" : nil + create_token("Milestone", milestone_name, symbol) end def label_token(label_name = nil, has_symbol = true) - symbol = has_symbol ? '~' : nil - create_token('Label', label_name, symbol) + symbol = has_symbol ? "~" : nil + create_token("Label", label_name, symbol) end def reaction_token(reaction_name = nil, is_emoji = true) if is_emoji - { name: 'My-Reaction', emoji_name: reaction_name } + {name: "My-Reaction", emoji_name: reaction_name} else - create_token('My-Reaction', reaction_name) + create_token("My-Reaction", reaction_name) end end def default_placeholder - 'Search or filter results...' + "Search or filter results..." end def get_filtered_search_placeholder - find('.filtered-search')['placeholder'] + find(".filtered-search")["placeholder"] end def remove_recent_searches - execute_script('window.localStorage.clear();') + execute_script("window.localStorage.clear();") end def set_recent_searches(key, input) @@ -146,7 +146,7 @@ module FilteredSearchHelpers def wait_for_filtered_search(text) Timeout.timeout(Capybara.default_max_wait_time) do - loop until find('.filtered-search').value.strip == text + loop until find(".filtered-search").value.strip == text end end end diff --git a/spec/support/helpers/fixture_helpers.rb b/spec/support/helpers/fixture_helpers.rb index 611d19f36a0..e0748a1a000 100644 --- a/spec/support/helpers/fixture_helpers.rb +++ b/spec/support/helpers/fixture_helpers.rb @@ -1,11 +1,11 @@ module FixtureHelpers - def fixture_file(filename, dir: '') - return '' if filename.blank? + def fixture_file(filename, dir: "") + return "" if filename.blank? File.read(expand_fixture_path(filename, dir: dir)) end - def expand_fixture_path(filename, dir: '') - File.expand_path(Rails.root.join(dir, 'spec', 'fixtures', filename)) + def expand_fixture_path(filename, dir: "") + File.expand_path(Rails.root.join(dir, "spec", "fixtures", filename)) end end diff --git a/spec/support/helpers/git_helpers.rb b/spec/support/helpers/git_helpers.rb index 99a7c39852e..bc8a4fd852d 100644 --- a/spec/support/helpers/git_helpers.rb +++ b/spec/support/helpers/git_helpers.rb @@ -2,7 +2,7 @@ module GitHelpers def rugged_repo(repository) - path = File.join(TestEnv.repos_path, repository.disk_path + '.git') + path = File.join(TestEnv.repos_path, repository.disk_path + ".git") Rugged::Repository.new(path) end @@ -11,7 +11,7 @@ module GitHelpers Gitlab::GitalyClient::StorageSettings.allow_disk_access do project_path = project.repository.raw_repository.path - File.exist?(File.join(project_path, 'hooks', 'post-receive')) + File.exist?(File.join(project_path, "hooks", "post-receive")) end end end diff --git a/spec/support/helpers/git_http_helpers.rb b/spec/support/helpers/git_http_helpers.rb index cd49bb148f2..d5a36c0a3cf 100644 --- a/spec/support/helpers/git_http_helpers.rb +++ b/spec/support/helpers/git_http_helpers.rb @@ -1,6 +1,6 @@ module GitHttpHelpers def clone_get(project, options = {}) - get "/#{project}/info/refs", params: { service: 'git-upload-pack' }, headers: auth_env(*options.values_at(:user, :password, :spnego_request_token)) + get "/#{project}/info/refs", params: {service: "git-upload-pack"}, headers: auth_env(*options.values_at(:user, :password, :spnego_request_token)) end def clone_post(project, options = {}) @@ -8,7 +8,7 @@ module GitHttpHelpers end def push_get(project, options = {}) - get "/#{project}/info/refs", params: { service: 'git-receive-pack' }, headers: auth_env(*options.values_at(:user, :password, :spnego_request_token)) + get "/#{project}/info/refs", params: {service: "git-receive-pack"}, headers: auth_env(*options.values_at(:user, :password, :spnego_request_token)) end def push_post(project, options = {}) @@ -16,7 +16,7 @@ module GitHttpHelpers end def download(project, user: nil, password: nil, spnego_request_token: nil) - args = [project, { user: user, password: password, spnego_request_token: spnego_request_token }] + args = [project, {user: user, password: password, spnego_request_token: spnego_request_token}] clone_get(*args) yield response @@ -26,7 +26,7 @@ module GitHttpHelpers end def upload(project, user: nil, password: nil, spnego_request_token: nil) - args = [project, { user: user, password: password, spnego_request_token: spnego_request_token }] + args = [project, {user: user, password: password, spnego_request_token: spnego_request_token}] push_get(*args) yield response @@ -43,9 +43,9 @@ module GitHttpHelpers def auth_env(user, password, spnego_request_token) env = workhorse_internal_api_request_header if user - env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user, password) + env["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Basic.encode_credentials(user, password) elsif spnego_request_token - env['HTTP_AUTHORIZATION'] = "Negotiate #{::Base64.strict_encode64('opaque_request_token')}" + env["HTTP_AUTHORIZATION"] = "Negotiate #{::Base64.strict_encode64("opaque_request_token")}" end env diff --git a/spec/support/helpers/gpg_helpers.rb b/spec/support/helpers/gpg_helpers.rb index 8d1637228d0..eaa580f9370 100644 --- a/spec/support/helpers/gpg_helpers.rb +++ b/spec/support/helpers/gpg_helpers.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true module GpgHelpers - SIGNED_COMMIT_SHA = '8a852d50dda17cc8fd1408d2fd0c5b0f24c76ca4' - SIGNED_AND_AUTHORED_SHA = '3c1d9a0266cb0c62d926f4a6c649beed561846f5' - DIFFERING_EMAIL_SHA = 'a17a9f66543673edf0a3d1c6b93bdda3fe600f32' + SIGNED_COMMIT_SHA = "8a852d50dda17cc8fd1408d2fd0c5b0f24c76ca4" + SIGNED_AND_AUTHORED_SHA = "3c1d9a0266cb0c62d926f4a6c649beed561846f5" + DIFFERING_EMAIL_SHA = "a17a9f66543673edf0a3d1c6b93bdda3fe600f32" module User1 extend self @@ -141,15 +141,15 @@ module GpgHelpers end def fingerprint - '5F7EA3981A5845B141ABD522CCFBE19F00AC8B1D' + "5F7EA3981A5845B141ABD522CCFBE19F00AC8B1D" end def names - ['Nannie Bernhard'] + ["Nannie Bernhard"] end def emails - ['nannie.bernhard@example.com'] + ["nannie.bernhard@example.com"] end end @@ -234,15 +234,15 @@ module GpgHelpers end def fingerprint - '6D494CA6FC90C0CAE0910E42BF9D925F911EFD65' + "6D494CA6FC90C0CAE0910E42BF9D925F911EFD65" end def names - ['Bette Cartwright', 'Bette Cartwright'] + ["Bette Cartwright", "Bette Cartwright"] end def emails - ['bette.cartwright@example.com', 'bette.cartwright@example.net'] + ["bette.cartwright@example.com", "bette.cartwright@example.net"] end end @@ -430,19 +430,19 @@ module GpgHelpers end def fingerprint - 'EA3F8B88972A8FD474872F2F115B3AF1AAD3EDBA' + "EA3F8B88972A8FD474872F2F115B3AF1AAD3EDBA" end def subkey_fingerprints - %w(159AD5DDF199591D67D2B87AA3CEC5C0A7C270EC 0522DD29B98F167CD8421752E38FFCAF75ABD92A) + %w[159AD5DDF199591D67D2B87AA3CEC5C0A7C270EC 0522DD29B98F167CD8421752E38FFCAF75ABD92A] end def names - ['John Doe'] + ["John Doe"] end def emails - ['john.doe@example.com'] + ["john.doe@example.com"] end end @@ -515,7 +515,7 @@ module GpgHelpers end def fingerprint - '08748B360CD25C2ECC99D59407016CF9E13A3F9B' + "08748B360CD25C2ECC99D59407016CF9E13A3F9B" end end end diff --git a/spec/support/helpers/graphql_helpers.rb b/spec/support/helpers/graphql_helpers.rb index e468ee4676d..739ca8be46a 100644 --- a/spec/support/helpers/graphql_helpers.rb +++ b/spec/support/helpers/graphql_helpers.rb @@ -18,12 +18,10 @@ module GraphqlHelpers # Runs a block inside a BatchLoader::Executor wrapper def batch(max_queries: nil, &blk) wrapper = proc do - begin - BatchLoader::Executor.ensure_current - yield - ensure - BatchLoader::Executor.clear_current - end + BatchLoader::Executor.ensure_current + yield + ensure + BatchLoader::Executor.clear_current end if max_queries @@ -37,9 +35,9 @@ module GraphqlHelpers def graphql_query_for(name, attributes = {}, fields = nil) <<~QUERY - { - #{query_graphql_field(name, attributes, fields)} - } + { + #{query_graphql_field(name, attributes, fields)} + } QUERY end @@ -50,7 +48,7 @@ module GraphqlHelpers fields ||= all_graphql_fields_for(mutation_field.type) query = <<~MUTATION - mutation(#{input_variable_name}: #{mutation_field.arguments['input'].type}) { + mutation(#{input_variable_name}: #{mutation_field.arguments["input"].type}) { #{mutation_name}(input: #{input_variable_name}) { #{fields} } @@ -63,13 +61,13 @@ module GraphqlHelpers def variables_for_mutation(name, input) graphql_input = input.map { |name, value| [GraphqlHelpers.fieldnamerize(name), value] }.to_h - { input_variable_name_for_mutation(name) => graphql_input }.to_json + {input_variable_name_for_mutation(name) => graphql_input}.to_json end def input_variable_name_for_mutation(mutation_name) mutation_name = GraphqlHelpers.fieldnamerize(mutation_name) mutation_field = GitlabSchema.mutation.fields[mutation_name] - input_type = field_type(mutation_field.arguments['input']) + input_type = field_type(mutation_field.arguments["input"]) GraphqlHelpers.fieldnamerize(input_type) end @@ -88,7 +86,7 @@ module GraphqlHelpers type = GitlabSchema.types[class_name.to_s] return "" unless type - type.fields.map do |name, field| + type.fields.map { |name, field| # We can't guess arguments, so skip fields that require them next if required_arguments?(field) @@ -106,17 +104,17 @@ module GraphqlHelpers else name end - end.compact.join("\n") + }.compact.join("\n") end def attributes_to_graphql(attributes) - attributes.map do |name, value| + attributes.map { |name, value| "#{GraphqlHelpers.fieldnamerize(name.to_s)}: \"#{value}\"" - end.join(", ") + }.join(", ") end def post_graphql(query, current_user: nil, variables: nil) - post api('/', current_user, version: 'graphql'), params: { query: query, variables: variables } + post api("/", current_user, version: "graphql"), params: {query: query, variables: variables} end def post_graphql_mutation(mutation, current_user: nil) @@ -124,11 +122,11 @@ module GraphqlHelpers end def graphql_data - json_response['data'] + json_response["data"] end def graphql_errors - json_response['errors'] + json_response["errors"] end def graphql_mutation_response(mutation_name) diff --git a/spec/support/helpers/import_spec_helper.rb b/spec/support/helpers/import_spec_helper.rb index d4eced724fa..b919ddc3700 100644 --- a/spec/support/helpers/import_spec_helper.rb +++ b/spec/support/helpers/import_spec_helper.rb @@ -1,4 +1,4 @@ -require 'ostruct' +require "ostruct" # Helper methods for controller specs in the Import namespace # @@ -16,7 +16,7 @@ module ImportSpecHelper # # Returns the client double def stub_client(messages = {}) - client = double('client', messages).as_null_object + client = double("client", messages).as_null_object allow(controller).to receive(:client).and_return(client) client @@ -25,8 +25,8 @@ module ImportSpecHelper def stub_omniauth_provider(name) provider = OpenStruct.new( name: name, - app_id: 'asd123', - app_secret: 'asd123' + app_id: "asd123", + app_secret: "asd123" ) stub_omniauth_setting(providers: [provider]) end diff --git a/spec/support/helpers/input_helper.rb b/spec/support/helpers/input_helper.rb index acbb42274ec..a2a57a46c53 100644 --- a/spec/support/helpers/input_helper.rb +++ b/spec/support/helpers/input_helper.rb @@ -1,7 +1,7 @@ # see app/assets/javascripts/test_utils/simulate_input.js module InputHelper - def simulate_input(selector, input = '') + def simulate_input(selector, input = "") evaluate_script("window.simulateInput(#{selector.to_json}, #{input.to_json});") end end diff --git a/spec/support/helpers/inspect_requests.rb b/spec/support/helpers/inspect_requests.rb index 88ddc5c7f6c..b3784fb302b 100644 --- a/spec/support/helpers/inspect_requests.rb +++ b/spec/support/helpers/inspect_requests.rb @@ -1,4 +1,4 @@ -require_relative './wait_for_requests' +require_relative "./wait_for_requests" module InspectRequests extend self diff --git a/spec/support/helpers/issue_helpers.rb b/spec/support/helpers/issue_helpers.rb index ffd72515f37..6f21f32112f 100644 --- a/spec/support/helpers/issue_helpers.rb +++ b/spec/support/helpers/issue_helpers.rb @@ -4,10 +4,10 @@ module IssueHelpers end def first_issue - page.all('ul.issues-list > li').first.text + page.all("ul.issues-list > li").first.text end def last_issue - page.all('ul.issues-list > li').last.text + page.all("ul.issues-list > li").last.text end end diff --git a/spec/support/helpers/javascript_fixtures_helpers.rb b/spec/support/helpers/javascript_fixtures_helpers.rb index 89c5ec7a718..70d2e3f36da 100644 --- a/spec/support/helpers/javascript_fixtures_helpers.rb +++ b/spec/support/helpers/javascript_fixtures_helpers.rb @@ -1,10 +1,10 @@ -require 'action_dispatch/testing/test_request' -require 'fileutils' +require "action_dispatch/testing/test_request" +require "fileutils" module JavaScriptFixturesHelpers include Gitlab::Popen - FIXTURE_PATH = 'spec/javascripts/fixtures'.freeze + FIXTURE_PATH = "spec/javascripts/fixtures".freeze def self.included(base) base.around do |example| @@ -19,7 +19,7 @@ module JavaScriptFixturesHelpers # def clean_frontend_fixtures(directory_name) directory_name = File.expand_path(directory_name, FIXTURE_PATH) - Dir[File.expand_path('*.html.raw', directory_name)].each do |file_name| + Dir[File.expand_path("*.html.raw", directory_name)].each do |file_name| FileUtils.rm(file_name) end end @@ -55,7 +55,7 @@ module JavaScriptFixturesHelpers if response_mime_type.html? doc = Nokogiri::HTML::DocumentFragment.parse(fixture) - link_tags = doc.css('link') + link_tags = doc.css("link") link_tags.remove scripts = doc.css("script:not([type='text/template']):not([type='text/x-template'])") @@ -64,7 +64,7 @@ module JavaScriptFixturesHelpers fixture = doc.to_html # replace relative links - test_host = ActionDispatch::TestRequest::DEFAULT_ENV['HTTP_HOST'] + test_host = ActionDispatch::TestRequest::DEFAULT_ENV["HTTP_HOST"] fixture.gsub!(%r{="/}, "=\"http://#{test_host}/") end diff --git a/spec/support/helpers/jira_service_helper.rb b/spec/support/helpers/jira_service_helper.rb index f4d5343c4ed..b025bc91360 100644 --- a/spec/support/helpers/jira_service_helper.rb +++ b/spec/support/helpers/jira_service_helper.rb @@ -6,10 +6,10 @@ module JiraServiceHelper properties = { title: "JIRA tracker", url: JIRA_URL, - username: 'jira-user', - password: 'my-secret-password', + username: "jira-user", + password: "my-secret-password", project_key: "JIRA", - jira_issue_transition_id: '1' + jira_issue_transition_id: "1", } jira_tracker.update(properties: properties, active: true) diff --git a/spec/support/helpers/key_generator_helper.rb b/spec/support/helpers/key_generator_helper.rb index d55d8312c65..d675484a087 100644 --- a/spec/support/helpers/key_generator_helper.rb +++ b/spec/support/helpers/key_generator_helper.rb @@ -3,7 +3,7 @@ module Spec module Helpers class KeyGeneratorHelper # The components in a openssh .pub / known_host RSA public key. - RSA_COMPONENTS = ['ssh-rsa', :e, :n].freeze + RSA_COMPONENTS = ["ssh-rsa", :e, :n].freeze attr_reader :size @@ -13,12 +13,12 @@ module Spec def generate key = OpenSSL::PKey::RSA.generate(size) - components = RSA_COMPONENTS.map do |component| + components = RSA_COMPONENTS.map { |component| key.respond_to?(component) ? encode_mpi(key.public_send(component)) : component - end + } # Ruby tries to be helpful and adds new lines every 60 bytes :( - 'ssh-rsa ' + [pack_pubkey_components(components)].pack('m').delete("\n") + "ssh-rsa " + [pack_pubkey_components(components)].pack("m").delete("\n") end private @@ -28,12 +28,12 @@ module Spec chars, n = [], n.to_i chars << (n & 0xff) && n >>= 8 while n != 0 chars << 0 if chars.empty? || chars.last >= 0x80 - chars.reverse.pack('C*') + chars.reverse.pack("C*") end # Packs string components into an openssh-encoded pubkey. def pack_pubkey_components(strings) - (strings.map { |s| [s.length].pack('N') }).zip(strings).flatten.join + (strings.map { |s| [s.length].pack("N") }).zip(strings).flatten.join end end end diff --git a/spec/support/helpers/kubernetes_helpers.rb b/spec/support/helpers/kubernetes_helpers.rb index 9dc89b483b2..05d7cae18e4 100644 --- a/spec/support/helpers/kubernetes_helpers.rb +++ b/spec/support/helpers/kubernetes_helpers.rb @@ -2,7 +2,7 @@ module KubernetesHelpers include Gitlab::Kubernetes def kube_response(body) - { body: body.to_json } + {body: body.to_json} end def kube_pods_response @@ -14,10 +14,10 @@ module KubernetesHelpers end def stub_kubeclient_discover(api_url) - WebMock.stub_request(:get, api_url + '/api/v1').to_return(kube_response(kube_v1_discovery_body)) - WebMock.stub_request(:get, api_url + '/apis/extensions/v1beta1').to_return(kube_response(kube_v1beta1_discovery_body)) - WebMock.stub_request(:get, api_url + '/apis/rbac.authorization.k8s.io/v1').to_return(kube_response(kube_v1_rbac_authorization_discovery_body)) - WebMock.stub_request(:get, api_url + '/apis/serving.knative.dev/v1alpha1').to_return(kube_response(kube_v1alpha1_serving_knative_discovery_body)) + WebMock.stub_request(:get, api_url + "/api/v1").to_return(kube_response(kube_v1_discovery_body)) + WebMock.stub_request(:get, api_url + "/apis/extensions/v1beta1").to_return(kube_response(kube_v1beta1_discovery_body)) + WebMock.stub_request(:get, api_url + "/apis/rbac.authorization.k8s.io/v1").to_return(kube_response(kube_v1_rbac_authorization_discovery_body)) + WebMock.stub_request(:get, api_url + "/apis/serving.knative.dev/v1alpha1").to_return(kube_response(kube_v1alpha1_serving_knative_discovery_body)) end def stub_kubeclient_service_pods(response = nil) @@ -60,42 +60,42 @@ module KubernetesHelpers .to_return(kube_response(kube_v1_secret_body(options))) end - def stub_kubeclient_get_secret_error(api_url, name, namespace: 'default', status: 404) + def stub_kubeclient_get_secret_error(api_url, name, namespace: "default", status: 404) WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/secrets/#{name}") .to_return(status: [status, "Internal Server Error"]) end - def stub_kubeclient_get_service_account(api_url, name, namespace: 'default') + def stub_kubeclient_get_service_account(api_url, name, namespace: "default") WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}") .to_return(kube_response({})) end - def stub_kubeclient_get_service_account_error(api_url, name, namespace: 'default', status: 404) + def stub_kubeclient_get_service_account_error(api_url, name, namespace: "default", status: 404) WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}") .to_return(status: [status, "Internal Server Error"]) end - def stub_kubeclient_create_service_account(api_url, namespace: 'default') + def stub_kubeclient_create_service_account(api_url, namespace: "default") WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts") .to_return(kube_response({})) end - def stub_kubeclient_create_service_account_error(api_url, namespace: 'default') + def stub_kubeclient_create_service_account_error(api_url, namespace: "default") WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts") .to_return(status: [500, "Internal Server Error"]) end - def stub_kubeclient_put_service_account(api_url, name, namespace: 'default') + def stub_kubeclient_put_service_account(api_url, name, namespace: "default") WebMock.stub_request(:put, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}") .to_return(kube_response({})) end - def stub_kubeclient_create_secret(api_url, namespace: 'default') + def stub_kubeclient_create_secret(api_url, namespace: "default") WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/secrets") .to_return(kube_response({})) end - def stub_kubeclient_put_secret(api_url, name, namespace: 'default') + def stub_kubeclient_put_secret(api_url, name, namespace: "default") WebMock.stub_request(:put, api_url + "/api/v1/namespaces/#{namespace}/secrets/#{name}") .to_return(kube_response({})) end @@ -106,26 +106,26 @@ module KubernetesHelpers end def stub_kubeclient_create_cluster_role_binding(api_url) - WebMock.stub_request(:post, api_url + '/apis/rbac.authorization.k8s.io/v1/clusterrolebindings') + WebMock.stub_request(:post, api_url + "/apis/rbac.authorization.k8s.io/v1/clusterrolebindings") .to_return(kube_response({})) end - def stub_kubeclient_get_role_binding(api_url, name, namespace: 'default') + def stub_kubeclient_get_role_binding(api_url, name, namespace: "default") WebMock.stub_request(:get, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings/#{name}") .to_return(kube_response({})) end - def stub_kubeclient_get_role_binding_error(api_url, name, namespace: 'default', status: 404) + def stub_kubeclient_get_role_binding_error(api_url, name, namespace: "default", status: 404) WebMock.stub_request(:get, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings/#{name}") .to_return(status: [status, "Internal Server Error"]) end - def stub_kubeclient_create_role_binding(api_url, namespace: 'default') + def stub_kubeclient_create_role_binding(api_url, namespace: "default") WebMock.stub_request(:post, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings") .to_return(kube_response({})) end - def stub_kubeclient_put_role_binding(api_url, name, namespace: 'default') + def stub_kubeclient_put_role_binding(api_url, name, namespace: "default") WebMock.stub_request(:put, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings/#{name}") .to_return(kube_response({})) end @@ -135,7 +135,7 @@ module KubernetesHelpers .to_return(kube_response({})) end - def stub_kubeclient_get_namespace(api_url, namespace: 'default') + def stub_kubeclient_get_namespace(api_url, namespace: "default") WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}") .to_return(kube_response({})) end @@ -143,14 +143,14 @@ module KubernetesHelpers def kube_v1_secret_body(**options) { "kind" => "SecretList", - "apiVersion": "v1", - "metadata": { + :apiVersion => "v1", + :metadata => { "name": options[:metadata_name] || "default-token-1", - "namespace": "kube-system" + "namespace": "kube-system", + }, + :data => { + "token": options[:token] || Base64.encode64("token-sample-123"), }, - "data": { - "token": options[:token] || Base64.encode64('token-sample-123') - } } end @@ -158,13 +158,13 @@ module KubernetesHelpers { "kind" => "APIResourceList", "resources" => [ - { "name" => "pods", "namespaced" => true, "kind" => "Pod" }, - { "name" => "deployments", "namespaced" => true, "kind" => "Deployment" }, - { "name" => "secrets", "namespaced" => true, "kind" => "Secret" }, - { "name" => "serviceaccounts", "namespaced" => true, "kind" => "ServiceAccount" }, - { "name" => "services", "namespaced" => true, "kind" => "Service" }, - { "name" => "namespaces", "namespaced" => true, "kind" => "Namespace" } - ] + {"name" => "pods", "namespaced" => true, "kind" => "Pod"}, + {"name" => "deployments", "namespaced" => true, "kind" => "Deployment"}, + {"name" => "secrets", "namespaced" => true, "kind" => "Secret"}, + {"name" => "serviceaccounts", "namespaced" => true, "kind" => "ServiceAccount"}, + {"name" => "services", "namespaced" => true, "kind" => "Service"}, + {"name" => "namespaces", "namespaced" => true, "kind" => "Namespace"}, + ], } end @@ -172,12 +172,12 @@ module KubernetesHelpers { "kind" => "APIResourceList", "resources" => [ - { "name" => "pods", "namespaced" => true, "kind" => "Pod" }, - { "name" => "deployments", "namespaced" => true, "kind" => "Deployment" }, - { "name" => "secrets", "namespaced" => true, "kind" => "Secret" }, - { "name" => "serviceaccounts", "namespaced" => true, "kind" => "ServiceAccount" }, - { "name" => "services", "namespaced" => true, "kind" => "Service" } - ] + {"name" => "pods", "namespaced" => true, "kind" => "Pod"}, + {"name" => "deployments", "namespaced" => true, "kind" => "Deployment"}, + {"name" => "secrets", "namespaced" => true, "kind" => "Secret"}, + {"name" => "serviceaccounts", "namespaced" => true, "kind" => "ServiceAccount"}, + {"name" => "services", "namespaced" => true, "kind" => "Service"}, + ], } end @@ -185,11 +185,11 @@ module KubernetesHelpers { "kind" => "APIResourceList", "resources" => [ - { "name" => "clusterrolebindings", "namespaced" => false, "kind" => "ClusterRoleBinding" }, - { "name" => "clusterroles", "namespaced" => false, "kind" => "ClusterRole" }, - { "name" => "rolebindings", "namespaced" => true, "kind" => "RoleBinding" }, - { "name" => "roles", "namespaced" => true, "kind" => "Role" } - ] + {"name" => "clusterrolebindings", "namespaced" => false, "kind" => "ClusterRoleBinding"}, + {"name" => "clusterroles", "namespaced" => false, "kind" => "ClusterRole"}, + {"name" => "rolebindings", "namespaced" => true, "kind" => "RoleBinding"}, + {"name" => "roles", "namespaced" => true, "kind" => "Role"}, + ], } end @@ -197,39 +197,39 @@ module KubernetesHelpers { "kind" => "APIResourceList", "resources" => [ - { "name" => "revisions", "namespaced" => true, "kind" => "Revision" }, - { "name" => "services", "namespaced" => true, "kind" => "Service" }, - { "name" => "configurations", "namespaced" => true, "kind" => "Configuration" }, - { "name" => "routes", "namespaced" => true, "kind" => "Route" } - ] + {"name" => "revisions", "namespaced" => true, "kind" => "Revision"}, + {"name" => "services", "namespaced" => true, "kind" => "Service"}, + {"name" => "configurations", "namespaced" => true, "kind" => "Configuration"}, + {"name" => "routes", "namespaced" => true, "kind" => "Route"}, + ], } end def kube_pods_body { "kind" => "PodList", - "items" => [kube_pod] + "items" => [kube_pod], } end def kube_deployments_body { "kind" => "DeploymentList", - "items" => [kube_deployment] + "items" => [kube_deployment], } end def kube_knative_pods_body(name, namespace) { "kind" => "PodList", - "items" => [kube_knative_pod(name: name, namespace: namespace)] + "items" => [kube_knative_pod(name: name, namespace: namespace)], } end def kube_knative_services_body(**options) { "kind" => "List", - "items" => [kube_service(options)] + "items" => [kube_service(options)], } end @@ -243,16 +243,16 @@ module KubernetesHelpers "creationTimestamp" => "2016-11-25T19:55:19Z", "labels" => { "app" => app, - "track" => track - } + "track" => track, + }, }, "spec" => { "containers" => [ - { "name" => "container-0" }, - { "name" => "container-1" } - ] + {"name" => "container-0"}, + {"name" => "container-1"}, + ], }, - "status" => { "phase" => status } + "status" => {"phase" => status}, } end @@ -265,16 +265,16 @@ module KubernetesHelpers "generate_name" => "generated-name-with-suffix", "creationTimestamp" => "2016-11-25T19:55:19Z", "labels" => { - "serving.knative.dev/service" => name - } + "serving.knative.dev/service" => name, + }, }, "spec" => { "containers" => [ - { "name" => "container-0" }, - { "name" => "container-1" } - ] + {"name" => "container-0"}, + {"name" => "container-1"}, + ], }, - "status" => { "phase" => status } + "status" => {"phase" => status}, } end @@ -285,16 +285,16 @@ module KubernetesHelpers "generation" => 4, "labels" => { "app" => app, - "track" => track - }.compact + "track" => track, + }.compact, }, - "spec" => { "replicas" => 3 }, + "spec" => {"replicas" => 3}, "status" => { "observedGeneration" => 4, "replicas" => 3, "updatedReplicas" => 3, - "availableReplicas" => 3 - } + "availableReplicas" => 3, + }, } end @@ -304,18 +304,18 @@ module KubernetesHelpers "creationTimestamp" => "2018-11-21T06:16:33Z", "name" => name, "namespace" => namespace, - "selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}" + "selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}", }, "spec" => { - "generation" => 2 + "generation" => 2, }, "status" => { "domain" => "#{name}.#{namespace}.#{domain}", "domainInternal" => "#{name}.#{namespace}.svc.cluster.local", "latestCreatedRevisionName" => "#{name}-00002", "latestReadyRevisionName" => "#{name}-00002", - "observedGeneration" => 2 - } + "observedGeneration" => 2, + }, } end @@ -327,37 +327,37 @@ module KubernetesHelpers "namespace" => namespace, "selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}", "annotation" => { - "description" => "This is a test description" - } + "description" => "This is a test description", + }, }, "spec" => { "generation" => 2, "build" => { - "template" => "go-1.10.3" - } + "template" => "go-1.10.3", + }, }, "status" => { "domain" => "#{name}.#{namespace}.#{domain}", "domainInternal" => "#{name}.#{namespace}.svc.cluster.local", "latestCreatedRevisionName" => "#{name}-00002", "latestReadyRevisionName" => "#{name}-00002", - "observedGeneration" => 2 - } + "observedGeneration" => 2, + }, } end def kube_terminals(service, pod) - pod_name = pod['metadata']['name'] - containers = pod['spec']['containers'] + pod_name = pod["metadata"]["name"] + containers = pod["spec"]["containers"] containers.map do |container| terminal = { - selectors: { pod: pod_name, container: container['name'] }, - url: container_exec_url(service.api_url, service.actual_namespace, pod_name, container['name']), - subprotocols: ['channel.k8s.io'], - headers: { 'Authorization' => ["Bearer #{service.token}"] }, - created_at: DateTime.parse(pod['metadata']['creationTimestamp']), - max_session_time: 0 + selectors: {pod: pod_name, container: container["name"]}, + url: container_exec_url(service.api_url, service.actual_namespace, pod_name, container["name"]), + subprotocols: ["channel.k8s.io"], + headers: {"Authorization" => ["Bearer #{service.token}"]}, + created_at: DateTime.parse(pod["metadata"]["creationTimestamp"]), + max_session_time: 0, } terminal[:ca_pem] = service.ca_pem if service.ca_pem.present? terminal diff --git a/spec/support/helpers/ldap_helpers.rb b/spec/support/helpers/ldap_helpers.rb index 66ca5d7f0a3..443329d4aaf 100644 --- a/spec/support/helpers/ldap_helpers.rb +++ b/spec/support/helpers/ldap_helpers.rb @@ -1,5 +1,5 @@ module LdapHelpers - def ldap_adapter(provider = 'ldapmain', ldap = double(:ldap)) + def ldap_adapter(provider = "ldapmain", ldap = double(:ldap)) ::Gitlab::Auth::LDAP::Adapter.new(provider, ldap) end @@ -30,14 +30,14 @@ module LdapHelpers # ldap_user_entry = ldap_user_entry('john_doe') # # stub_ldap_person_find_by_uid('john_doe', ldap_user_entry, adapter) - def stub_ldap_person_find_by_uid(uid, entry, provider = 'ldapmain') + def stub_ldap_person_find_by_uid(uid, entry, provider = "ldapmain") return_value = ::Gitlab::Auth::LDAP::Person.new(entry, provider) if entry.present? allow(::Gitlab::Auth::LDAP::Person) .to receive(:find_by_uid).with(uid, any_args).and_return(return_value) end - def stub_ldap_person_find_by_dn(entry, provider = 'ldapmain') + def stub_ldap_person_find_by_dn(entry, provider = "ldapmain") person = ::Gitlab::Auth::LDAP::Person.new(entry, provider) if entry.present? allow(::Gitlab::Auth::LDAP::Person) @@ -45,7 +45,7 @@ module LdapHelpers .and_return(person) end - def stub_ldap_person_find_by_email(email, entry, provider = 'ldapmain') + def stub_ldap_person_find_by_email(email, entry, provider = "ldapmain") person = ::Gitlab::Auth::LDAP::Person.new(entry, provider) if entry.present? allow(::Gitlab::Auth::LDAP::Person) @@ -57,8 +57,8 @@ module LdapHelpers # Create a simple LDAP user entry. def ldap_user_entry(uid) entry = Net::LDAP::Entry.new - entry['dn'] = user_dn(uid) - entry['uid'] = uid + entry["dn"] = user_dn(uid) + entry["uid"] = uid entry end diff --git a/spec/support/helpers/live_debugger.rb b/spec/support/helpers/live_debugger.rb index 911eb48a8ca..659d65f0576 100644 --- a/spec/support/helpers/live_debugger.rb +++ b/spec/support/helpers/live_debugger.rb @@ -1,4 +1,4 @@ -require 'io/console' +require "io/console" module LiveDebugger def live_debug diff --git a/spec/support/helpers/login_helpers.rb b/spec/support/helpers/login_helpers.rb index 3fee6872498..99af5ff4d8e 100644 --- a/spec/support/helpers/login_helpers.rb +++ b/spec/support/helpers/login_helpers.rb @@ -1,4 +1,4 @@ -require_relative 'devise_helpers' +require_relative "devise_helpers" module LoginHelpers include DeviseHelpers @@ -58,7 +58,7 @@ module LoginHelpers click_link "Sign out" @current_user = nil - expect(page).to have_button('Sign in') + expect(page).to have_button("Sign in") end private @@ -72,7 +72,7 @@ module LoginHelpers fill_in "user_login", with: user.email fill_in "user_password", with: "12345678" - check 'user_remember_me' if remember + check "user_remember_me" if remember click_button "Sign in" end @@ -80,9 +80,9 @@ module LoginHelpers def login_via(provider, user, uid, remember_me: false) mock_auth_hash(provider, uid, user.email) visit new_user_session_path - expect(page).to have_content('Sign in with') + expect(page).to have_content("Sign in with") - check 'remember_me' if remember_me + check "remember_me" if remember_me click_link "oauth-login-#{provider}" end @@ -94,51 +94,51 @@ module LoginHelpers provider: provider, uid: uid, info: { - name: 'mockuser', + name: "mockuser", email: email, - image: 'mock_user_thumbnail_url' + image: "mock_user_thumbnail_url", }, credentials: { - token: 'mock_token', - secret: 'mock_secret' + token: "mock_token", + secret: "mock_secret", }, extra: { raw_info: { info: { - name: 'mockuser', + name: "mockuser", email: email, - image: 'mock_user_thumbnail_url' - } + image: "mock_user_thumbnail_url", + }, }, response_object: { - document: saml_xml(saml_response) - } - } + document: saml_xml(saml_response), + }, + }, }) - Rails.application.env_config['omniauth.auth'] = OmniAuth.config.mock_auth[provider.to_sym] + Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[provider.to_sym] end def saml_xml(raw_saml_response) - return '' if raw_saml_response.blank? + return "" if raw_saml_response.blank? XMLSecurity::SignedDocument.new(raw_saml_response, []) end def mock_saml_config - OpenStruct.new(name: 'saml', label: 'saml', args: { - assertion_consumer_service_url: 'https://localhost:3443/users/auth/saml/callback', - idp_cert_fingerprint: '26:43:2C:47:AF:F0:6B:D0:07:9C:AD:A3:74:FE:5D:94:5F:4E:9E:52', - idp_sso_target_url: 'https://idp.example.com/sso/saml', - issuer: 'https://localhost:3443/', - name_identifier_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient' + OpenStruct.new(name: "saml", label: "saml", args: { + assertion_consumer_service_url: "https://localhost:3443/users/auth/saml/callback", + idp_cert_fingerprint: "26:43:2C:47:AF:F0:6B:D0:07:9C:AD:A3:74:FE:5D:94:5F:4E:9E:52", + idp_sso_target_url: "https://idp.example.com/sso/saml", + issuer: "https://localhost:3443/", + name_identifier_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:transient", }) end def mock_saml_config_with_upstream_two_factor_authn_contexts config = mock_saml_config - config.args[:upstream_two_factor_authn_contexts] = %w(urn:oasis:names:tc:SAML:2.0:ac:classes:CertificateProtectedTransport + config.args[:upstream_two_factor_authn_contexts] = %w[urn:oasis:names:tc:SAML:2.0:ac:classes:CertificateProtectedTransport urn:oasis:names:tc:SAML:2.0:ac:classes:SecondFactorOTPSMS - urn:oasis:names:tc:SAML:2.0:ac:classes:SecondFactorIGTOKEN) + urn:oasis:names:tc:SAML:2.0:ac:classes:SecondFactorIGTOKEN] config end @@ -146,15 +146,15 @@ module LoginHelpers env = env_from_context(context) set_devise_mapping(context: context) - env['omniauth.auth'] = OmniAuth.config.mock_auth[provider.to_sym] + env["omniauth.auth"] = OmniAuth.config.mock_auth[provider.to_sym] end def stub_omniauth_failure(strategy, message_key, exception = nil) env = @request.env - env['omniauth.error'] = exception - env['omniauth.error.type'] = message_key.to_sym - env['omniauth.error.strategy'] = strategy + env["omniauth.error"] = exception + env["omniauth.error.type"] = message_key.to_sym + env["omniauth.error.strategy"] = strategy end def stub_omniauth_saml_config(messages, context: Rails.application) @@ -163,7 +163,7 @@ module LoginHelpers routes.disable_clear_and_finalize = true routes.formatter.clear routes.draw do - post '/users/auth/saml' => 'omniauth_callbacks#saml' + post "/users/auth/saml" => "omniauth_callbacks#saml" end saml_config = messages.key?(:providers) ? messages[:providers].first : mock_saml_config allow(Gitlab::Auth::OAuth::Provider).to receive_messages(providers: [:saml], config_for: saml_config) @@ -174,11 +174,11 @@ module LoginHelpers def stub_saml_authorize_path_helpers allow_any_instance_of(ActionDispatch::Routing::RoutesProxy) .to receive(:user_saml_omniauth_authorize_path) - .and_return('/users/auth/saml') + .and_return("/users/auth/saml") allow(Devise::OmniAuth::UrlHelpers) .to receive(:omniauth_authorize_path) .with(:user, "saml") - .and_return('/users/auth/saml') + .and_return("/users/auth/saml") end def stub_omniauth_config(messages) @@ -186,10 +186,10 @@ module LoginHelpers end def stub_basic_saml_config - allow(Gitlab::Auth::Saml::Config).to receive_messages({ options: { name: 'saml', args: {} } }) + allow(Gitlab::Auth::Saml::Config).to receive_messages({options: {name: "saml", args: {}}}) end def stub_saml_group_config(groups) - allow(Gitlab::Auth::Saml::Config).to receive_messages({ options: { name: 'saml', groups_attribute: 'groups', external_groups: groups, args: {} } }) + allow(Gitlab::Auth::Saml::Config).to receive_messages({options: {name: "saml", groups_attribute: "groups", external_groups: groups, args: {}}}) end end diff --git a/spec/support/helpers/markdown_feature.rb b/spec/support/helpers/markdown_feature.rb index 96401379cf0..35e92ca41cb 100644 --- a/spec/support/helpers/markdown_feature.rb +++ b/spec/support/helpers/markdown_feature.rb @@ -12,7 +12,7 @@ class MarkdownFeature attr_reader :fixture_path - def initialize(fixture_path = Rails.root.join('spec/fixtures/markdown.md.erb')) + def initialize(fixture_path = Rails.root.join("spec/fixtures/markdown.md.erb")) @fixture_path = fixture_path end @@ -60,29 +60,29 @@ class MarkdownFeature def commit_range @commit_range ||= begin - commit2 = project.commit('HEAD~3') + commit2 = project.commit("HEAD~3") CommitRange.new("#{commit.id}...#{commit2.id}", project) end end def simple_label - @simple_label ||= create(:label, name: 'gfm', project: project) + @simple_label ||= create(:label, name: "gfm", project: project) end def label - @label ||= create(:label, name: 'awaiting feedback', project: project) + @label ||= create(:label, name: "awaiting feedback", project: project) end def simple_milestone - @simple_milestone ||= create(:milestone, name: 'gfm-milestone', project: project) + @simple_milestone ||= create(:milestone, name: "gfm-milestone", project: project) end def milestone - @milestone ||= create(:milestone, name: 'next goal', project: project) + @milestone ||= create(:milestone, name: "next goal", project: project) end def group_milestone - @group_milestone ||= create(:milestone, name: 'group-milestone', group: group) + @group_milestone ||= create(:milestone, name: "group-milestone", group: group) end # Cross-references ----------------------------------------------------------- @@ -114,7 +114,7 @@ class MarkdownFeature def xcommit_range @xcommit_range ||= begin - xcommit2 = xproject.commit('HEAD~2') + xcommit2 = xproject.commit("HEAD~2") CommitRange.new("#{xcommit.id}...#{xcommit2.id}", xproject) end end diff --git a/spec/support/helpers/merge_request_diff_helpers.rb b/spec/support/helpers/merge_request_diff_helpers.rb index 3b49d0b3319..2c810067aae 100644 --- a/spec/support/helpers/merge_request_diff_helpers.rb +++ b/spec/support/helpers/merge_request_diff_helpers.rb @@ -2,7 +2,7 @@ module MergeRequestDiffHelpers def click_diff_line(line_holder, diff_side = nil) line = get_line_components(line_holder, diff_side) line[:content].hover - line[:num].find('.js-add-diff-note-button', visible: false).send_keys(:return) + line[:num].find(".js-add-diff-note-button", visible: false).send_keys(:return) end def get_line_components(line_holder, diff_side = nil) @@ -14,15 +14,15 @@ module MergeRequestDiffHelpers end def get_inline_line_components(line_holder) - { content: line_holder.find('.line_content', match: :first), num: line_holder.find('.diff-line-num', match: :first) } + {content: line_holder.find(".line_content", match: :first), num: line_holder.find(".diff-line-num", match: :first)} end def get_parallel_line_components(line_holder, diff_side = nil) - side_index = diff_side == 'left' ? 0 : 1 + side_index = diff_side == "left" ? 0 : 1 # Wait for `.line_content` - line_holder.find('.line_content', match: :first) + line_holder.find(".line_content", match: :first) # Wait for `.diff-line-num` - line_holder.find('.diff-line-num', match: :first) - { content: line_holder.all('.line_content')[side_index], num: line_holder.all('.diff-line-num')[side_index] } + line_holder.find(".diff-line-num", match: :first) + {content: line_holder.all(".line_content")[side_index], num: line_holder.all(".diff-line-num")[side_index]} end end diff --git a/spec/support/helpers/merge_request_helpers.rb b/spec/support/helpers/merge_request_helpers.rb index 772adff4626..be3c202b75d 100644 --- a/spec/support/helpers/merge_request_helpers.rb +++ b/spec/support/helpers/merge_request_helpers.rb @@ -4,19 +4,19 @@ module MergeRequestHelpers end def first_merge_request - page.all('ul.mr-list > li').first.text + page.all("ul.mr-list > li").first.text end def last_merge_request - page.all('ul.mr-list > li').last.text + page.all("ul.mr-list > li").last.text end def expect_mr_list_count(open_count, closed_count = 0) all_count = open_count + closed_count expect(page).to have_issuable_counts(open: open_count, closed: closed_count, all: all_count) - page.within '.mr-list' do - expect(page).to have_selector('.merge-request', count: open_count) + page.within ".mr-list" do + expect(page).to have_selector(".merge-request", count: open_count) end end end diff --git a/spec/support/helpers/migrations_helpers.rb b/spec/support/helpers/migrations_helpers.rb index cc1a28cb264..9a30a0ab635 100644 --- a/spec/support/helpers/migrations_helpers.rb +++ b/spec/support/helpers/migrations_helpers.rb @@ -75,7 +75,7 @@ module MigrationsHelpers .to receive(:active?) .and_return(false) - stub_env('IN_MEMORY_APPLICATION_SETTINGS', 'false') + stub_env("IN_MEMORY_APPLICATION_SETTINGS", "false") end def previous_migration @@ -97,7 +97,7 @@ module MigrationsHelpers def schema_migrate_down! disable_migrations_output do ActiveRecord::Migrator.migrate(migrations_paths, - migration_schema_version) + migration_schema_version) end reset_column_in_all_models diff --git a/spec/support/helpers/note_interaction_helpers.rb b/spec/support/helpers/note_interaction_helpers.rb index 79a0aa174b1..b1f4f8d943f 100644 --- a/spec/support/helpers/note_interaction_helpers.rb +++ b/spec/support/helpers/note_interaction_helpers.rb @@ -2,7 +2,7 @@ module NoteInteractionHelpers def open_more_actions_dropdown(note) note_element = find("#note_#{note.id}") - note_element.find('.more-actions-toggle').click - note_element.find('.more-actions .dropdown-menu li', match: :first) + note_element.find(".more-actions-toggle").click + note_element.find(".more-actions .dropdown-menu li", match: :first) end end diff --git a/spec/support/helpers/notification_helpers.rb b/spec/support/helpers/notification_helpers.rb index 8d84510fb73..200a1759521 100644 --- a/spec/support/helpers/notification_helpers.rb +++ b/spec/support/helpers/notification_helpers.rb @@ -2,7 +2,7 @@ module NotificationHelpers extend self def send_notifications(*new_mentions) - mentionable.description = new_mentions.map(&:to_reference).join(' ') + mentionable.description = new_mentions.map(&:to_reference).join(" ") notification.send(notification_method, mentionable, new_mentions, @u_disabled) end diff --git a/spec/support/helpers/project_forks_helper.rb b/spec/support/helpers/project_forks_helper.rb index 9a86560da2a..c27898c3eb5 100644 --- a/spec/support/helpers/project_forks_helper.rb +++ b/spec/support/helpers/project_forks_helper.rb @@ -20,7 +20,7 @@ module ProjectForksHelper # Avoid creating a repository unless create_repository allow(RepositoryForkWorker).to receive(:perform_async).and_return(true) - shell = double('gitlab_shell', fork_repository: true) + shell = double("gitlab_shell", fork_repository: true) allow(service).to receive(:gitlab_shell).and_return(shell) end @@ -46,8 +46,8 @@ module ProjectForksHelper def fork_project_with_submodules(project, user = nil, params = {}) forked_project = fork_project(project, user, params) TestEnv.copy_repo(forked_project, - bare_repo: TestEnv.forked_repo_path_bare, - refs: TestEnv::FORKED_BRANCH_SHA) + bare_repo: TestEnv.forked_repo_path_bare, + refs: TestEnv::FORKED_BRANCH_SHA) forked_project.repository.after_import forked_project end diff --git a/spec/support/helpers/prometheus_helpers.rb b/spec/support/helpers/prometheus_helpers.rb index ce1f9fce10d..0b68c3f4887 100644 --- a/spec/support/helpers/prometheus_helpers.rb +++ b/spec/support/helpers/prometheus_helpers.rb @@ -8,19 +8,19 @@ module PrometheusHelpers end def prometheus_ping_url(prometheus_query) - query = { query: prometheus_query }.to_query + query = {query: prometheus_query}.to_query "https://prometheus.example.com/api/v1/query?#{query}" end def prometheus_query_url(prometheus_query) - query = { query: prometheus_query }.to_query + query = {query: prometheus_query}.to_query "https://prometheus.example.com/api/v1/query?#{query}" end def prometheus_query_with_time_url(prometheus_query, time) - query = { query: prometheus_query, time: time.to_f }.to_query + query = {query: prometheus_query, time: time.to_f}.to_query "https://prometheus.example.com/api/v1/query?#{query}" end @@ -30,7 +30,7 @@ module PrometheusHelpers query: prometheus_query, start: start.to_f, end: stop, - step: 1.minute.to_i + step: 1.minute.to_i, }.to_query "https://prometheus.example.com/api/v1/query_range?#{query}" @@ -44,7 +44,7 @@ module PrometheusHelpers query = { match: matches, start: start.to_f, - end: stop.to_f + end: stop.to_f, }.to_query "https://prometheus.example.com/api/v1/series?#{query}" end @@ -53,8 +53,8 @@ module PrometheusHelpers WebMock.stub_request(:get, url) .to_return({ status: status, - headers: { 'Content-Type' => 'application/json' }.merge(headers), - body: body.to_json + headers: {"Content-Type" => "application/json"}.merge(headers), + body: body.to_json, }) end @@ -99,12 +99,12 @@ module PrometheusHelpers { success: true, data: { - memory_values: prometheus_values_body('matrix').dig(:data, :result), - memory_current: prometheus_value_body('vector').dig(:data, :result), - cpu_values: prometheus_values_body('matrix').dig(:data, :result), - cpu_current: prometheus_value_body('vector').dig(:data, :result) + memory_values: prometheus_values_body("matrix").dig(:data, :result), + memory_current: prometheus_value_body("vector").dig(:data, :result), + cpu_values: prometheus_values_body("matrix").dig(:data, :result), + cpu_current: prometheus_value_body("vector").dig(:data, :result), }, - last_update: last_update + last_update: last_update, } end @@ -112,12 +112,12 @@ module PrometheusHelpers { success: true, metrics: { - memory_values: prometheus_values_body('matrix').dig(:data, :result), - memory_current: prometheus_value_body('vector').dig(:data, :result), - cpu_values: prometheus_values_body('matrix').dig(:data, :result), - cpu_current: prometheus_value_body('vector').dig(:data, :result) + memory_values: prometheus_values_body("matrix").dig(:data, :result), + memory_current: prometheus_value_body("vector").dig(:data, :result), + cpu_values: prometheus_values_body("matrix").dig(:data, :result), + cpu_current: prometheus_value_body("vector").dig(:data, :result), }, - last_update: last_update + last_update: last_update, } end @@ -126,12 +126,12 @@ module PrometheusHelpers "status": "success", "data": { "resultType": type, - "result": [] - } + "result": [], + }, } end - def prometheus_value_body(type = 'vector') + def prometheus_value_body(type = "vector") { "status": "success", "data": { @@ -141,15 +141,15 @@ module PrometheusHelpers "metric": {}, "value": [ 1488772511.004, - "0.000041021495238095323" - ] - } - ] - } + "0.000041021495238095323", + ], + }, + ], + }, } end - def prometheus_values_body(type = 'matrix') + def prometheus_values_body(type = "matrix") { "status": "success", "data": { @@ -159,44 +159,44 @@ module PrometheusHelpers "metric": {}, "values": [ [1488758662.506, "0.00002996364761904785"], - [1488758722.506, "0.00003090239047619091"] - ] - } - ] - } + [1488758722.506, "0.00003090239047619091"], + ], + }, + ], + }, } end def prometheus_label_values { - 'status': 'success', - 'data': %w(job_adds job_controller_rate_limiter_use job_depth job_queue_latency job_work_duration_sum up) + 'status': "success", + 'data': %w[job_adds job_controller_rate_limiter_use job_depth job_queue_latency job_work_duration_sum up], } end def prometheus_series(name) { - 'status': 'success', + 'status': "success", 'data': [ { '__name__': name, - 'container_name': 'gitlab', - 'environment': 'mattermost', - 'id': '/docker/9953982f95cf5010dfc59d7864564d5f188aaecddeda343699783009f89db667', - 'image': 'gitlab/gitlab-ce:8.15.4-ce.1', - 'instance': 'minikube', - 'job': 'kubernetes-nodes', - 'name': 'k8s_gitlab.e6611886_mattermost-4210310111-77z8r_gitlab_2298ae6b-da24-11e6-baee-8e7f67d0eb3a_43536cb6', - 'namespace': 'gitlab', - 'pod_name': 'mattermost-4210310111-77z8r' + 'container_name': "gitlab", + 'environment': "mattermost", + 'id': "/docker/9953982f95cf5010dfc59d7864564d5f188aaecddeda343699783009f89db667", + 'image': "gitlab/gitlab-ce:8.15.4-ce.1", + 'instance': "minikube", + 'job': "kubernetes-nodes", + 'name': "k8s_gitlab.e6611886_mattermost-4210310111-77z8r_gitlab_2298ae6b-da24-11e6-baee-8e7f67d0eb3a_43536cb6", + 'namespace': "gitlab", + 'pod_name': "mattermost-4210310111-77z8r", }, { '__name__': name, - 'id': '/docker', - 'instance': 'minikube', - 'job': 'kubernetes-nodes' - } - ] + 'id': "/docker", + 'instance': "minikube", + 'job': "kubernetes-nodes", + }, + ], } end end diff --git a/spec/support/helpers/query_recorder.rb b/spec/support/helpers/query_recorder.rb index 7ce63375d34..5772c081866 100644 --- a/spec/support/helpers/query_recorder.rb +++ b/spec/support/helpers/query_recorder.rb @@ -6,7 +6,7 @@ module ActiveRecord @log = [] @cached = [] @skip_cached = skip_cached - ActiveSupport::Notifications.subscribed(method(:callback), 'sql.active_record', &block) + ActiveSupport::Notifications.subscribed(method(:callback), "sql.active_record", &block) end def show_backtrace(values) @@ -15,7 +15,7 @@ module ActiveRecord end def callback(name, start, finish, message_id, values) - show_backtrace(values) if ENV['QUERY_RECORDER_DEBUG'] + show_backtrace(values) if ENV["QUERY_RECORDER_DEBUG"] if values[:name]&.include?("CACHE") && skip_cached @cached << values[:sql] diff --git a/spec/support/helpers/quick_actions_helpers.rb b/spec/support/helpers/quick_actions_helpers.rb index 361190aa352..6c3a6343d9a 100644 --- a/spec/support/helpers/quick_actions_helpers.rb +++ b/spec/support/helpers/quick_actions_helpers.rb @@ -1,9 +1,9 @@ module QuickActionsHelpers def write_note(text) Sidekiq::Testing.fake! do - page.within('.js-main-target-form') do - fill_in 'note[note]', with: text - find('.js-comment-submit-button').click + page.within(".js-main-target-form") do + fill_in "note[note]", with: text + find(".js-comment-submit-button").click end end end diff --git a/spec/support/helpers/rake_helpers.rb b/spec/support/helpers/rake_helpers.rb index 7d8d7750bf3..ddcd1143960 100644 --- a/spec/support/helpers/rake_helpers.rb +++ b/spec/support/helpers/rake_helpers.rb @@ -1,7 +1,7 @@ module RakeHelpers def run_rake_task(task_name, *args) Rake::Task[task_name].reenable - Rake.application.invoke_task("#{task_name}[#{args.join(',')}]") + Rake.application.invoke_task("#{task_name}[#{args.join(",")}]") end def stub_warn_user_is_not_gitlab @@ -18,6 +18,6 @@ module RakeHelpers end def main_object - @main_object ||= TOPLEVEL_BINDING.eval('self') + @main_object ||= TOPLEVEL_BINDING.eval("self") end end diff --git a/spec/support/helpers/reactive_caching_helpers.rb b/spec/support/helpers/reactive_caching_helpers.rb index b76b53db0b9..59e30731473 100644 --- a/spec/support/helpers/reactive_caching_helpers.rb +++ b/spec/support/helpers/reactive_caching_helpers.rb @@ -1,10 +1,10 @@ module ReactiveCachingHelpers def reactive_cache_key(subject, *qualifiers) - ([subject.class.reactive_cache_key.call(subject)].flatten + qualifiers).join(':') + ([subject.class.reactive_cache_key.call(subject)].flatten + qualifiers).join(":") end def alive_reactive_cache_key(subject, *qualifiers) - reactive_cache_key(subject, *(qualifiers + ['alive'])) + reactive_cache_key(subject, *(qualifiers + ["alive"])) end def stub_reactive_cache(subject = nil, data = nil, *qualifiers) diff --git a/spec/support/helpers/reference_parser_helpers.rb b/spec/support/helpers/reference_parser_helpers.rb index 9f27502aa52..5598e4f1d2c 100644 --- a/spec/support/helpers/reference_parser_helpers.rb +++ b/spec/support/helpers/reference_parser_helpers.rb @@ -1,10 +1,10 @@ module ReferenceParserHelpers def empty_html_link - Nokogiri::HTML.fragment('<a></a>').children[0] + Nokogiri::HTML.fragment("<a></a>").children[0] end - shared_examples 'no project N+1 queries' do - it 'avoids N+1 queries in #nodes_visible_to_user', :request_store do + shared_examples "no project N+1 queries" do + it "avoids N+1 queries in #nodes_visible_to_user", :request_store do context = Banzai::RenderContext.new(project, user) record_queries = lambda do |links| @@ -21,10 +21,10 @@ module ReferenceParserHelpers end end - shared_examples 'no N+1 queries' do - it_behaves_like 'no project N+1 queries' + shared_examples "no N+1 queries" do + it_behaves_like "no project N+1 queries" - it 'avoids N+1 queries in #records_for_nodes', :request_store do + it "avoids N+1 queries in #records_for_nodes", :request_store do context = Banzai::RenderContext.new(project, user) record_queries = lambda do |links| diff --git a/spec/support/helpers/repo_helpers.rb b/spec/support/helpers/repo_helpers.rb index 3c6956cf5e0..e586982bf2f 100644 --- a/spec/support/helpers/repo_helpers.rb +++ b/spec/support/helpers/repo_helpers.rb @@ -13,52 +13,52 @@ module RepoHelpers # def sample_blob OpenStruct.new( - oid: '5f53439ca4b009096571d3c8bc3d09d30e7431b3', + oid: "5f53439ca4b009096571d3c8bc3d09d30e7431b3", path: "files/js/commit.js.coffee", - data: <<eos -class Commit - constructor: -> - $('.files .diff-file').each -> - new CommitFile(this) + data: <<~eos + class Commit + constructor: -> + $('.files .diff-file').each -> + new CommitFile(this) -@Commit = Commit -eos + @Commit = Commit + eos ) end def sample_commit OpenStruct.new( id: "570e7b2abdd848b95f2f578043fc23bd6f6fd24d", - parent_id: '6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9', + parent_id: "6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9", author_full_name: "Dmitriy Zaporozhets", author_email: "dmitriy.zaporozhets@gmail.com", files_changed_count: 2, - line_code: '2f6fcd96b88b36ce98c38da085c795a27d92a3dd_15_14', - line_code_path: 'files/ruby/popen.rb', - del_line_code: '2f6fcd96b88b36ce98c38da085c795a27d92a3dd_13_13', - message: <<eos -Change some files -Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com> -eos + line_code: "2f6fcd96b88b36ce98c38da085c795a27d92a3dd_15_14", + line_code_path: "files/ruby/popen.rb", + del_line_code: "2f6fcd96b88b36ce98c38da085c795a27d92a3dd_13_13", + message: <<~eos + Change some files + Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com> + eos ) end def another_sample_commit OpenStruct.new( id: "e56497bb5f03a90a51293fc6d516788730953899", - parent_id: '4cd80ccab63c82b4bad16faa5193fbd2aa06df40', + parent_id: "4cd80ccab63c82b4bad16faa5193fbd2aa06df40", author_full_name: "Sytse Sijbrandij", author_email: "sytse@gitlab.com", files_changed_count: 1, - message: <<eos -Add directory structure for tree_helper spec + message: <<~eos + Add directory structure for tree_helper spec -This directory structure is needed for a testing the method flatten_tree(tree) in the TreeHelper module + This directory structure is needed for a testing the method flatten_tree(tree) in the TreeHelper module -See [merge request #275](https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/275#note_732774) + See [merge request #275](https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/275#note_732774) -See merge request !2 -eos + See merge request !2 + eos ) end @@ -67,10 +67,10 @@ eos id: "913c66a37b4a45b9769037c55c2d238bd0942d2e", author_full_name: "Dmitriy Zaporozhets", author_email: "dmitriy.zaporozhets@gmail.com", - message: <<eos -Files, encoding and much more -Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com> -eos + message: <<~eos + Files, encoding and much more + Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com> + eos ) end @@ -79,38 +79,38 @@ eos id: "2f63565e7aac07bcdadb654e253078b727143ec4", author_full_name: "Dmitriy Zaporozhets", author_email: "dmitriy.zaporozhets@gmail.com", - old_blob_id: '33f3729a45c02fc67d00adb1b8bca394b0e761d9', - new_blob_id: '2f63565e7aac07bcdadb654e253078b727143ec4', - message: <<eos -Modified image -Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com> -eos + old_blob_id: "33f3729a45c02fc67d00adb1b8bca394b0e761d9", + new_blob_id: "2f63565e7aac07bcdadb654e253078b727143ec4", + message: <<~eos + Modified image + Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com> + eos ) end def sample_compare changes = [ { - line_code: 'a5cc2925ca8258af241be7e5b0381edf30266302_20_20', - file_path: '.gitignore' + line_code: "a5cc2925ca8258af241be7e5b0381edf30266302_20_20", + file_path: ".gitignore", }, { - line_code: '7445606fbf8f3683cd42bdc54b05d7a0bc2dfc44_4_6', - file_path: '.gitmodules' - } + line_code: "7445606fbf8f3683cd42bdc54b05d7a0bc2dfc44_4_6", + file_path: ".gitmodules", + }, ] - commits = %w( + commits = %w[ 5937ac0a7beb003549fc5fd26fc247adbce4a52e 570e7b2abdd848b95f2f578043fc23bd6f6fd24d 6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9 d14d6c0abdd253381df51a723d58691b2ee1ab08 c1acaa58bbcbc3eafe538cb8274ba387047b69f8 - ).reverse # last commit is recent one + ].reverse # last commit is recent one OpenStruct.new( - source_branch: 'master', - target_branch: 'feature', + source_branch: "master", + target_branch: "feature", changes: changes, commits: commits ) diff --git a/spec/support/helpers/seed_helper.rb b/spec/support/helpers/seed_helper.rb index 90d7f60fdeb..a06795fe07c 100644 --- a/spec/support/helpers/seed_helper.rb +++ b/spec/support/helpers/seed_helper.rb @@ -1,18 +1,18 @@ # frozen_string_literal: true -require_relative 'test_env' +require_relative "test_env" # This file is specific to specs in spec/lib/gitlab/git/ SEED_STORAGE_PATH = TestEnv.repos_path -TEST_REPO_PATH = 'gitlab-git-test.git' -TEST_NORMAL_REPO_PATH = 'not-bare-repo.git' -TEST_MUTABLE_REPO_PATH = 'mutable-repo.git' -TEST_BROKEN_REPO_PATH = 'broken-repo.git' -TEST_GITATTRIBUTES_REPO_PATH = 'with-git-attributes.git' +TEST_REPO_PATH = "gitlab-git-test.git" +TEST_NORMAL_REPO_PATH = "not-bare-repo.git" +TEST_MUTABLE_REPO_PATH = "mutable-repo.git" +TEST_BROKEN_REPO_PATH = "broken-repo.git" +TEST_GITATTRIBUTES_REPO_PATH = "with-git-attributes.git" module SeedHelper - GITLAB_GIT_TEST_REPO_URL = File.expand_path('../gitlab-git-test.git', __dir__) + GITLAB_GIT_TEST_REPO_URL = File.expand_path("../gitlab-git-test.git", __dir__) def ensure_seeds if File.exist?(SEED_STORAGE_PATH) @@ -30,85 +30,85 @@ module SeedHelper end def create_bare_seeds - system(git_env, *%W(#{Gitlab.config.git.bin_path} clone --bare #{GITLAB_GIT_TEST_REPO_URL}), - chdir: SEED_STORAGE_PATH, - out: '/dev/null', - err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "clone", "--bare", GITLAB_GIT_TEST_REPO_URL.to_s, + chdir: SEED_STORAGE_PATH, + out: "/dev/null", + err: "/dev/null") end def create_normal_seeds - system(git_env, *%W(#{Gitlab.config.git.bin_path} clone #{TEST_REPO_PATH} #{TEST_NORMAL_REPO_PATH}), - chdir: SEED_STORAGE_PATH, - out: '/dev/null', - err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "clone", TEST_REPO_PATH.to_s, TEST_NORMAL_REPO_PATH.to_s, + chdir: SEED_STORAGE_PATH, + out: "/dev/null", + err: "/dev/null") end def create_mutable_seeds - system(git_env, *%W(#{Gitlab.config.git.bin_path} clone --bare #{TEST_REPO_PATH} #{TEST_MUTABLE_REPO_PATH}), - chdir: SEED_STORAGE_PATH, - out: '/dev/null', - err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "clone", "--bare", TEST_REPO_PATH.to_s, TEST_MUTABLE_REPO_PATH.to_s, + chdir: SEED_STORAGE_PATH, + out: "/dev/null", + err: "/dev/null") mutable_repo_full_path = File.join(SEED_STORAGE_PATH, TEST_MUTABLE_REPO_PATH) - system(git_env, *%W(#{Gitlab.config.git.bin_path} branch -t feature origin/feature), - chdir: mutable_repo_full_path, out: '/dev/null', err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "branch", "-t", "feature", "origin/feature", + chdir: mutable_repo_full_path, out: "/dev/null", err: "/dev/null") - system(git_env, *%W(#{Gitlab.config.git.bin_path} remote add expendable #{GITLAB_GIT_TEST_REPO_URL}), - chdir: mutable_repo_full_path, out: '/dev/null', err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "remote", "add", "expendable", GITLAB_GIT_TEST_REPO_URL.to_s, + chdir: mutable_repo_full_path, out: "/dev/null", err: "/dev/null") end def create_broken_seeds - system(git_env, *%W(#{Gitlab.config.git.bin_path} clone --bare #{TEST_REPO_PATH} #{TEST_BROKEN_REPO_PATH}), - chdir: SEED_STORAGE_PATH, - out: '/dev/null', - err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "clone", "--bare", TEST_REPO_PATH.to_s, TEST_BROKEN_REPO_PATH.to_s, + chdir: SEED_STORAGE_PATH, + out: "/dev/null", + err: "/dev/null") - refs_path = File.join(SEED_STORAGE_PATH, TEST_BROKEN_REPO_PATH, 'refs') + refs_path = File.join(SEED_STORAGE_PATH, TEST_BROKEN_REPO_PATH, "refs") FileUtils.rm_r(refs_path) end def create_git_attributes - system(git_env, *%W(#{Gitlab.config.git.bin_path} clone --bare #{TEST_REPO_PATH} #{TEST_GITATTRIBUTES_REPO_PATH}), - chdir: SEED_STORAGE_PATH, - out: '/dev/null', - err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "clone", "--bare", TEST_REPO_PATH.to_s, TEST_GITATTRIBUTES_REPO_PATH.to_s, + chdir: SEED_STORAGE_PATH, + out: "/dev/null", + err: "/dev/null") - dir = File.join(SEED_STORAGE_PATH, 'with-git-attributes.git', 'info') + dir = File.join(SEED_STORAGE_PATH, "with-git-attributes.git", "info") FileUtils.mkdir_p(dir) - File.open(File.join(dir, 'attributes'), 'w') do |handle| - handle.write <<-EOF.strip -# This is a comment, it should be ignored. - -*.txt text -*.jpg -text -*.sh eol=lf gitlab-language=shell -*.haml.* gitlab-language=haml -foo/bar.* foo -*.cgi key=value?p1=v1&p2=v2 -/*.png gitlab-language=png -*.binary binary -/custom-highlighting/*.gitlab-custom gitlab-language=ruby -/custom-highlighting/*.gitlab-cgi gitlab-language=erb?parent=json - -# This uses a tab instead of spaces to ensure the parser also supports this. -*.md\tgitlab-language=markdown -bla/bla.txt + File.open(File.join(dir, "attributes"), "w") do |handle| + handle.write <<~EOF.strip + # This is a comment, it should be ignored. + + *.txt text + *.jpg -text + *.sh eol=lf gitlab-language=shell + *.haml.* gitlab-language=haml + foo/bar.* foo + *.cgi key=value?p1=v1&p2=v2 + /*.png gitlab-language=png + *.binary binary + /custom-highlighting/*.gitlab-custom gitlab-language=ruby + /custom-highlighting/*.gitlab-cgi gitlab-language=erb?parent=json + + # This uses a tab instead of spaces to ensure the parser also supports this. + *.md\tgitlab-language=markdown + bla/bla.txt EOF end end def create_invalid_git_attributes - dir = File.join(SEED_STORAGE_PATH, 'with-invalid-git-attributes.git', 'info') + dir = File.join(SEED_STORAGE_PATH, "with-invalid-git-attributes.git", "info") FileUtils.mkdir_p(dir) enc = Encoding::UTF_16 - File.open(File.join(dir, 'attributes'), 'w', encoding: enc) do |handle| - handle.write('# hello'.encode(enc)) + File.open(File.join(dir, "attributes"), "w", encoding: enc) do |handle| + handle.write("# hello".encode(enc)) end end end diff --git a/spec/support/helpers/seed_repo.rb b/spec/support/helpers/seed_repo.rb index 71f1a86b0c1..add58658f52 100644 --- a/spec/support/helpers/seed_repo.rb +++ b/spec/support/helpers/seed_repo.rb @@ -45,7 +45,7 @@ module SeedRepo FILES_COUNT = 2 C_FILE_PATH = "files/ruby".freeze C_FILES = ["popen.rb", "regex.rb", "version_info.rb"].freeze - BLOB_FILE = %{%h3= @key.title\n%hr\n%pre= @key.key\n.actions\n = link_to 'Remove', @key, :confirm => 'Are you sure?', :method => :delete, :class => \"btn danger delete-key\"\n\n\n}.freeze + BLOB_FILE = %(%h3= @key.title\n%hr\n%pre= @key.key\n.actions\n = link_to 'Remove', @key, :confirm => 'Are you sure?', :method => :delete, :class => \"btn danger delete-key\"\n\n\n).freeze BLOB_FILE_PATH = "app/views/keys/show.html.haml".freeze end @@ -111,44 +111,44 @@ module SeedRepo module RubyBlob ID = "7e3e39ebb9b2bf433b4ad17313770fbe4051649c".freeze NAME = "popen.rb".freeze - CONTENT = <<-eos.freeze -require 'fileutils' -require 'open3' + CONTENT = <<~eos.freeze + require 'fileutils' + require 'open3' -module Popen - extend self + module Popen + extend self - def popen(cmd, path=nil) - unless cmd.is_a?(Array) - raise RuntimeError, "System commands must be given as an array of strings" - end + def popen(cmd, path=nil) + unless cmd.is_a?(Array) + raise RuntimeError, "System commands must be given as an array of strings" + end - path ||= Dir.pwd + path ||= Dir.pwd - vars = { - "PWD" => path - } + vars = { + "PWD" => path + } - options = { - chdir: path - } + options = { + chdir: path + } - unless File.directory?(path) - FileUtils.mkdir_p(path) - end + unless File.directory?(path) + FileUtils.mkdir_p(path) + end - @cmd_output = "" - @cmd_status = 0 + @cmd_output = "" + @cmd_status = 0 - Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| - @cmd_output << stdout.read - @cmd_output << stderr.read - @cmd_status = wait_thr.value.exitstatus - end + Open3.popen3(vars, *cmd, options) do |stdin, stdout, stderr, wait_thr| + @cmd_output << stdout.read + @cmd_output << stderr.read + @cmd_status = wait_thr.value.exitstatus + end - return @cmd_output, @cmd_status - end -end + return @cmd_output, @cmd_status + end + end eos end end diff --git a/spec/support/helpers/select2_helper.rb b/spec/support/helpers/select2_helper.rb index f4f0415985c..49aee851b8d 100644 --- a/spec/support/helpers/select2_helper.rb +++ b/spec/support/helpers/select2_helper.rb @@ -1,4 +1,4 @@ -require_relative 'wait_for_requests' +require_relative "wait_for_requests" # Select2 ajax programmatic helper # It allows you to select value from select2 @@ -16,7 +16,7 @@ module Select2Helper include WaitForRequests def select2(value, options = {}) - raise ArgumentError, 'options must be a Hash' unless options.is_a?(Hash) + raise ArgumentError, "options must be a Hash" unless options.is_a?(Hash) wait_for_requests unless options[:async] diff --git a/spec/support/helpers/sorting_helper.rb b/spec/support/helpers/sorting_helper.rb index e505a6b7258..1a98328bcb6 100644 --- a/spec/support/helpers/sorting_helper.rb +++ b/spec/support/helpers/sorting_helper.rb @@ -10,8 +10,8 @@ # module SortingHelper def sorting_by(value) - find('.filter-dropdown-container button.dropdown-menu-toggle').click - page.within('.content ul.dropdown-menu.dropdown-menu-right li') do + find(".filter-dropdown-container button.dropdown-menu-toggle").click + page.within(".content ul.dropdown-menu.dropdown-menu-right li") do click_link value end end diff --git a/spec/support/helpers/stub_configuration.rb b/spec/support/helpers/stub_configuration.rb index ff21bbe28ca..40e3bcfcbd6 100644 --- a/spec/support/helpers/stub_configuration.rb +++ b/spec/support/helpers/stub_configuration.rb @@ -1,8 +1,8 @@ -require 'active_support/core_ext/hash/transform_values' -require 'active_support/hash_with_indifferent_access' -require 'active_support/dependencies' +require "active_support/core_ext/hash/transform_values" +require "active_support/hash_with_indifferent_access" +require "active_support/dependencies" -require_dependency 'gitlab' +require_dependency "gitlab" module StubConfiguration def stub_application_setting(messages) @@ -20,7 +20,8 @@ module StubConfiguration def stub_not_protect_default_branch stub_application_setting( - default_branch_protection: Gitlab::Access::PROTECTION_NONE) + default_branch_protection: Gitlab::Access::PROTECTION_NONE + ) end def stub_config_setting(messages) @@ -28,7 +29,7 @@ module StubConfiguration end def stub_default_url_options(host: "localhost", protocol: "http") - url_options = { host: host, protocol: protocol } + url_options = {host: host, protocol: protocol} allow(Rails.application.routes).to receive(:default_url_options).and_return(url_options) end @@ -68,10 +69,10 @@ module StubConfiguration messages.deep_stringify_keys! # Default storage is always required - messages['default'] ||= Gitlab.config.repositories.storages.default + messages["default"] ||= Gitlab.config.repositories.storages.default messages.each do |storage_name, storage_hash| - if !storage_hash.key?('path') || storage_hash['path'] == Gitlab::GitalyClient::StorageSettings::Deprecated - storage_hash['path'] = TestEnv.repos_path + if !storage_hash.key?("path") || storage_hash["path"] == Gitlab::GitalyClient::StorageSettings::Deprecated + storage_hash["path"] = TestEnv.repos_path end messages[storage_name] = Gitlab::GitalyClient::StorageSettings.new(storage_hash.to_h) @@ -97,10 +98,10 @@ module StubConfiguration # # => {signup_enabled? false} def add_predicates(messages) # Only modify keys that aren't already predicates - keys = messages.keys.map(&:to_s).reject { |k| k.end_with?('?') } + keys = messages.keys.map(&:to_s).reject { |k| k.end_with?("?") } keys.each do |key| - predicate = key + '?' + predicate = key + "?" messages[predicate.to_sym] = messages[key.to_sym] end end diff --git a/spec/support/helpers/stub_env.rb b/spec/support/helpers/stub_env.rb index 1c2f474a015..2f58eb35a1e 100644 --- a/spec/support/helpers/stub_env.rb +++ b/spec/support/helpers/stub_env.rb @@ -12,7 +12,7 @@ module StubENV private - STUBBED_KEY = '__STUBBED__'.freeze + STUBBED_KEY = "__STUBBED__".freeze def add_stubbed_value(key, value) allow(ENV).to receive(:[]).with(key).and_return(value) diff --git a/spec/support/helpers/stub_gitlab_calls.rb b/spec/support/helpers/stub_gitlab_calls.rb index 4cb3b18df85..b01e4c178fc 100644 --- a/spec/support/helpers/stub_gitlab_calls.rb +++ b/spec/support/helpers/stub_gitlab_calls.rb @@ -20,7 +20,7 @@ module StubGitlabCalls allow_any_instance_of(Ci::Pipeline).to receive(:ci_yaml_file) { ci_yaml } end - def stub_repository_ci_yaml_file(sha:, path: '.gitlab-ci.yml') + def stub_repository_ci_yaml_file(sha:, path: ".gitlab-ci.yml") allow_any_instance_of(Repository) .to receive(:gitlab_ci_yml_for).with(sha, path) .and_return(gitlab_ci_yaml) @@ -33,7 +33,7 @@ module StubGitlabCalls def stub_container_registry_config(registry_settings) allow(Gitlab.config.registry).to receive_messages(registry_settings) allow(Auth::ContainerRegistryAuthenticationService) - .to receive(:full_access_token).and_return('token') + .to receive(:full_access_token).and_return("token") end def stub_container_registry_tags(repository: :any, tags: [], with_manifest: false) @@ -41,15 +41,15 @@ module StubGitlabCalls allow_any_instance_of(ContainerRegistry::Client) .to receive(:repository_tags).with(repository) - .and_return({ 'tags' => tags }) + .and_return({"tags" => tags}) if with_manifest tags.each do |tag| allow_any_instance_of(ContainerRegistry::Client) .to receive(:repository_tag_digest) .with(repository, tag) - .and_return('sha256:4c8e63ca4cb663ce6c688cb06f1c3' \ - '72b088dac5b6d7ad7d49cd620d85cf72a15') + .and_return("sha256:4c8e63ca4cb663ce6c688cb06f1c3" \ + "72b088dac5b6d7ad7d49cd620d85cf72a15") end allow_any_instance_of(ContainerRegistry::Client) @@ -57,7 +57,7 @@ module StubGitlabCalls .and_return(stub_container_registry_tag_manifest_content) allow_any_instance_of(ContainerRegistry::Client) - .to receive(:blob).with(repository, anything, 'application/octet-stream') + .to receive(:blob).with(repository, anything, "application/octet-stream") .and_return(stub_container_registry_blob_content) end end @@ -71,13 +71,13 @@ module StubGitlabCalls private def stub_container_registry_tag_manifest_content - fixture_path = 'spec/fixtures/container_registry/tag_manifest.json' + fixture_path = "spec/fixtures/container_registry/tag_manifest.json" JSON.parse(File.read(Rails.root + fixture_path)) end def stub_container_registry_blob_content - fixture_path = 'spec/fixtures/container_registry/config_blob.json' + fixture_path = "spec/fixtures/container_registry/config_blob.json" File.read(Rails.root + fixture_path) end @@ -87,49 +87,49 @@ module StubGitlabCalls end def stub_user - f = File.read(Rails.root.join('spec/support/gitlab_stubs/user.json')) + f = File.read(Rails.root.join("spec/support/gitlab_stubs/user.json")) stub_request(:get, "#{gitlab_url}api/v4/user?private_token=Wvjy2Krpb7y8xi93owUz") - .with(headers: { 'Content-Type' => 'application/json' }) - .to_return(status: 200, body: f, headers: { 'Content-Type' => 'application/json' }) + .with(headers: {"Content-Type" => "application/json"}) + .to_return(status: 200, body: f, headers: {"Content-Type" => "application/json"}) stub_request(:get, "#{gitlab_url}api/v4/user?access_token=some_token") - .with(headers: { 'Content-Type' => 'application/json' }) - .to_return(status: 200, body: f, headers: { 'Content-Type' => 'application/json' }) + .with(headers: {"Content-Type" => "application/json"}) + .to_return(status: 200, body: f, headers: {"Content-Type" => "application/json"}) end def stub_project_8 - data = File.read(Rails.root.join('spec/support/gitlab_stubs/project_8.json')) + data = File.read(Rails.root.join("spec/support/gitlab_stubs/project_8.json")) allow_any_instance_of(Network).to receive(:project).and_return(JSON.parse(data)) end def stub_project_8_hooks - data = File.read(Rails.root.join('spec/support/gitlab_stubs/project_8_hooks.json')) + data = File.read(Rails.root.join("spec/support/gitlab_stubs/project_8_hooks.json")) allow_any_instance_of(Network).to receive(:project_hooks).and_return(JSON.parse(data)) end def stub_projects - f = File.read(Rails.root.join('spec/support/gitlab_stubs/projects.json')) + f = File.read(Rails.root.join("spec/support/gitlab_stubs/projects.json")) stub_request(:get, "#{gitlab_url}api/v4/projects.json?archived=false&ci_enabled_first=true&private_token=Wvjy2Krpb7y8xi93owUz") - .with(headers: { 'Content-Type' => 'application/json' }) - .to_return(status: 200, body: f, headers: { 'Content-Type' => 'application/json' }) + .with(headers: {"Content-Type" => "application/json"}) + .to_return(status: 200, body: f, headers: {"Content-Type" => "application/json"}) end def stub_projects_owned stub_request(:get, "#{gitlab_url}api/v4/projects?owned=true&archived=false&ci_enabled_first=true&private_token=Wvjy2Krpb7y8xi93owUz") - .with(headers: { 'Content-Type' => 'application/json' }) + .with(headers: {"Content-Type" => "application/json"}) .to_return(status: 200, body: "", headers: {}) end def stub_ci_enable stub_request(:put, "#{gitlab_url}api/v4/projects/2/services/gitlab-ci.json?private_token=Wvjy2Krpb7y8xi93owUz") - .with(headers: { 'Content-Type' => 'application/json' }) + .with(headers: {"Content-Type" => "application/json"}) .to_return(status: 200, body: "", headers: {}) end def project_hash_array - f = File.read(Rails.root.join('spec/support/gitlab_stubs/projects.json')) + f = File.read(Rails.root.join("spec/support/gitlab_stubs/projects.json")) JSON.parse f end end diff --git a/spec/support/helpers/stub_gitlab_data.rb b/spec/support/helpers/stub_gitlab_data.rb index fa402f35b95..ca1beecdbe9 100644 --- a/spec/support/helpers/stub_gitlab_data.rb +++ b/spec/support/helpers/stub_gitlab_data.rb @@ -1,5 +1,5 @@ module StubGitlabData def gitlab_ci_yaml - File.read(Rails.root.join('spec/support/gitlab_stubs/gitlab_ci.yml')) + File.read(Rails.root.join("spec/support/gitlab_stubs/gitlab_ci.yml")) end end diff --git a/spec/support/helpers/stub_object_storage.rb b/spec/support/helpers/stub_object_storage.rb index e0c50e533a6..9928ed0f77b 100644 --- a/spec/support/helpers/stub_object_storage.rb +++ b/spec/support/helpers/stub_object_storage.rb @@ -1,12 +1,12 @@ module StubObjectStorage def stub_object_storage_uploader( - config:, - uploader:, - remote_directory:, - enabled: true, - proxy_download: false, - background_upload: false, - direct_upload: false + config:, + uploader:, + remote_directory:, + enabled: true, + proxy_download: false, + background_upload: false, + direct_upload: false ) allow(config).to receive(:enabled) { enabled } allow(config).to receive(:proxy_download) { proxy_download } @@ -23,43 +23,41 @@ module StubObjectStorage Fog.mock! ::Fog::Storage.new(connection_params).tap do |connection| - begin - connection.directories.create(key: remote_directory) + connection.directories.create(key: remote_directory) - # Cleanup remaining files - connection.directories.each do |directory| - directory.files.map(&:destroy) - end - rescue Excon::Error::Conflict + # Cleanup remaining files + connection.directories.each do |directory| + directory.files.map(&:destroy) end + rescue Excon::Error::Conflict end end def stub_artifacts_object_storage(**params) stub_object_storage_uploader(config: Gitlab.config.artifacts.object_store, uploader: JobArtifactUploader, - remote_directory: 'artifacts', + remote_directory: "artifacts", **params) end def stub_external_diffs_object_storage(uploader = described_class, **params) stub_object_storage_uploader(config: Gitlab.config.external_diffs.object_store, uploader: uploader, - remote_directory: 'external_diffs', + remote_directory: "external_diffs", **params) end def stub_lfs_object_storage(**params) stub_object_storage_uploader(config: Gitlab.config.lfs.object_store, uploader: LfsObjectUploader, - remote_directory: 'lfs-objects', + remote_directory: "lfs-objects", **params) end def stub_uploads_object_storage(uploader = described_class, **params) stub_object_storage_uploader(config: Gitlab.config.uploads.object_store, uploader: uploader, - remote_directory: 'uploads', + remote_directory: "uploads", **params) end diff --git a/spec/support/helpers/terms_helper.rb b/spec/support/helpers/terms_helper.rb index a00ec14138b..d5eb3238a82 100644 --- a/spec/support/helpers/terms_helper.rb +++ b/spec/support/helpers/terms_helper.rb @@ -1,9 +1,9 @@ module TermsHelper def enforce_terms - stub_env('IN_MEMORY_APPLICATION_SETTINGS', 'false') + stub_env("IN_MEMORY_APPLICATION_SETTINGS", "false") settings = Gitlab::CurrentSettings.current_application_settings ApplicationSettings::UpdateService.new( - settings, nil, terms: 'These are the terms', enforce_terms: true + settings, nil, terms: "These are the terms", enforce_terms: true ).execute end @@ -14,6 +14,6 @@ module TermsHelper def expect_to_be_on_terms_page expect(current_path).to eq terms_path - expect(page).to have_content('Please accept the Terms of Service before continuing.') + expect(page).to have_content("Please accept the Terms of Service before continuing.") end end diff --git a/spec/support/helpers/test_env.rb b/spec/support/helpers/test_env.rb index 80a22134021..39cc2141ca6 100644 --- a/spec/support/helpers/test_env.rb +++ b/spec/support/helpers/test_env.rb @@ -1,5 +1,5 @@ -require 'rspec/mocks' -require 'toml-rb' +require "rspec/mocks" +require "toml-rb" module TestEnv extend self @@ -8,77 +8,77 @@ module TestEnv # When developing the seed repository, comment out the branch you will modify. BRANCH_SHA = { - 'signed-commits' => '6101e87', - 'not-merged-branch' => 'b83d6e3', - 'branch-merged' => '498214d', - 'empty-branch' => '7efb185', - 'ends-with.json' => '98b0d8b', - 'flatten-dir' => 'e56497b', - 'feature' => '0b4bc9a', - 'feature_conflict' => 'bb5206f', - 'fix' => '48f0be4', - 'improve/awesome' => '5937ac0', - 'merged-target' => '21751bf', - 'markdown' => '0ed8c6c', - 'lfs' => '55bc176', - 'master' => 'b83d6e3', - 'merge-test' => '5937ac0', - "'test'" => 'e56497b', - 'orphaned-branch' => '45127a9', - 'binary-encoding' => '7b1cf43', - 'gitattributes' => '5a62481', - 'expand-collapse-diffs' => '4842455', - 'symlink-expand-diff' => '81e6355', - 'expand-collapse-files' => '025db92', - 'expand-collapse-lines' => '238e82d', - 'pages-deploy' => '7897d5b', - 'pages-deploy-target' => '7975be0', - 'video' => '8879059', - 'add-balsamiq-file' => 'b89b56d', - 'crlf-diff' => '5938907', - 'conflict-start' => '824be60', - 'conflict-resolvable' => '1450cd6', - 'conflict-binary-file' => '259a6fb', - 'conflict-contains-conflict-markers' => '78a3086', - 'conflict-missing-side' => 'eb227b3', - 'conflict-non-utf8' => 'd0a293c', - 'conflict-too-large' => '39fa04f', - 'deleted-image-test' => '6c17798', - 'wip' => 'b9238ee', - 'csv' => '3dd0896', - 'v1.1.0' => 'b83d6e3', - 'add-ipython-files' => '93ee732', - 'add-pdf-file' => 'e774ebd', - 'squash-large-files' => '54cec52', - 'add-pdf-text-binary' => '79faa7b', - 'add_images_and_changes' => '010d106', - 'update-gitlab-shell-v-6-0-1' => '2f61d70', - 'update-gitlab-shell-v-6-0-3' => 'de78448', - 'merge-commit-analyze-before' => '1adbdef', - 'merge-commit-analyze-side-branch' => '8a99451', - 'merge-commit-analyze-after' => '646ece5', - '2-mb-file' => 'bf12d25', - 'before-create-delete-modify-move' => '845009f', - 'between-create-delete-modify-move' => '3f5f443', - 'after-create-delete-modify-move' => 'ba3faa7', - 'with-codeowners' => '219560e', - 'submodule_inside_folder' => 'b491b92', - 'png-lfs' => 'fe42f41', - 'sha-starting-with-large-number' => '8426165' + "signed-commits" => "6101e87", + "not-merged-branch" => "b83d6e3", + "branch-merged" => "498214d", + "empty-branch" => "7efb185", + "ends-with.json" => "98b0d8b", + "flatten-dir" => "e56497b", + "feature" => "0b4bc9a", + "feature_conflict" => "bb5206f", + "fix" => "48f0be4", + "improve/awesome" => "5937ac0", + "merged-target" => "21751bf", + "markdown" => "0ed8c6c", + "lfs" => "55bc176", + "master" => "b83d6e3", + "merge-test" => "5937ac0", + "'test'" => "e56497b", + "orphaned-branch" => "45127a9", + "binary-encoding" => "7b1cf43", + "gitattributes" => "5a62481", + "expand-collapse-diffs" => "4842455", + "symlink-expand-diff" => "81e6355", + "expand-collapse-files" => "025db92", + "expand-collapse-lines" => "238e82d", + "pages-deploy" => "7897d5b", + "pages-deploy-target" => "7975be0", + "video" => "8879059", + "add-balsamiq-file" => "b89b56d", + "crlf-diff" => "5938907", + "conflict-start" => "824be60", + "conflict-resolvable" => "1450cd6", + "conflict-binary-file" => "259a6fb", + "conflict-contains-conflict-markers" => "78a3086", + "conflict-missing-side" => "eb227b3", + "conflict-non-utf8" => "d0a293c", + "conflict-too-large" => "39fa04f", + "deleted-image-test" => "6c17798", + "wip" => "b9238ee", + "csv" => "3dd0896", + "v1.1.0" => "b83d6e3", + "add-ipython-files" => "93ee732", + "add-pdf-file" => "e774ebd", + "squash-large-files" => "54cec52", + "add-pdf-text-binary" => "79faa7b", + "add_images_and_changes" => "010d106", + "update-gitlab-shell-v-6-0-1" => "2f61d70", + "update-gitlab-shell-v-6-0-3" => "de78448", + "merge-commit-analyze-before" => "1adbdef", + "merge-commit-analyze-side-branch" => "8a99451", + "merge-commit-analyze-after" => "646ece5", + "2-mb-file" => "bf12d25", + "before-create-delete-modify-move" => "845009f", + "between-create-delete-modify-move" => "3f5f443", + "after-create-delete-modify-move" => "ba3faa7", + "with-codeowners" => "219560e", + "submodule_inside_folder" => "b491b92", + "png-lfs" => "fe42f41", + "sha-starting-with-large-number" => "8426165", }.freeze # gitlab-test-fork is a fork of gitlab-fork, but we don't necessarily # need to keep all the branches in sync. # We currently only need a subset of the branches FORKED_BRANCH_SHA = { - 'add-submodule-version-bump' => '3f547c0', - 'master' => '5937ac0', - 'remove-submodule' => '2a33e0c', - 'conflict-resolvable-fork' => '404fa3f' + "add-submodule-version-bump" => "3f547c0", + "master" => "5937ac0", + "remove-submodule" => "2a33e0c", + "conflict-resolvable-fork" => "404fa3f", }.freeze - TMP_TEST_PATH = Rails.root.join('tmp', 'tests', '**') - REPOS_STORAGE = 'default'.freeze + TMP_TEST_PATH = Rails.root.join("tmp", "tests", "**") + REPOS_STORAGE = "default".freeze # Test environment # @@ -122,7 +122,7 @@ module TestEnv # Keeps gitlab-shell and gitlab-test def clean_test_path Dir[TMP_TEST_PATH].each do |entry| - unless File.basename(entry) =~ /\A(gitaly|gitlab-(shell|test|test_bare|test-fork|test-fork_bare))\z/ + unless /\A(gitaly|gitlab-(shell|test|test_bare|test-fork|test-fork_bare))\z/.match?(File.basename(entry)) FileUtils.rm_rf(entry) end end @@ -135,17 +135,17 @@ module TestEnv def clean_gitlab_test_path Dir[TMP_TEST_PATH].each do |entry| - if File.basename(entry) =~ /\A(gitlab-(test|test_bare|test-fork|test-fork_bare))\z/ + if /\A(gitlab-(test|test_bare|test-fork|test-fork_bare))\z/.match?(File.basename(entry)) FileUtils.rm_rf(entry) end end end def setup_gitlab_shell - component_timed_setup('GitLab Shell', + component_timed_setup("GitLab Shell", install_dir: Gitlab.config.gitlab_shell.path, version: Gitlab::Shell.version_required, - task: 'gitlab:shell:install') + task: "gitlab:shell:install") # gitlab-shell hooks don't work in our test environment because they try to make internal API calls sabotage_gitlab_shell_hooks @@ -157,39 +157,39 @@ module TestEnv def create_fake_git_hooks(hooks_dir) %w[pre-receive post-receive update].each do |hook| - File.open(File.join(hooks_dir, hook), 'w', 0755) { |f| f.puts '#!/bin/sh' } + File.open(File.join(hooks_dir, hook), "w", 0o755) { |f| f.puts "#!/bin/sh" } end end def setup_gitaly - socket_path = Gitlab::GitalyClient.address('default').sub(/\Aunix:/, '') + socket_path = Gitlab::GitalyClient.address("default").sub(/\Aunix:/, "") gitaly_dir = File.dirname(socket_path) - install_gitaly_args = [gitaly_dir, repos_path, gitaly_url].compact.join(',') + install_gitaly_args = [gitaly_dir, repos_path, gitaly_url].compact.join(",") - component_timed_setup('Gitaly', + component_timed_setup("Gitaly", install_dir: gitaly_dir, version: Gitlab::GitalyClient.expected_server_version, task: "gitlab:gitaly:install[#{install_gitaly_args}]") do - Gitlab::SetupHelper.create_gitaly_configuration(gitaly_dir, { 'default' => repos_path }, force: true) - create_fake_git_hooks(File.join(gitaly_dir, 'ruby/git-hooks')) + Gitlab::SetupHelper.create_gitaly_configuration(gitaly_dir, {"default" => repos_path}, force: true) + create_fake_git_hooks(File.join(gitaly_dir, "ruby/git-hooks")) start_gitaly(gitaly_dir) end end def start_gitaly(gitaly_dir) - if ENV['CI'].present? + if ENV["CI"].present? # Gitaly has been spawned outside this process already return end FileUtils.mkdir_p("tmp/tests/second_storage") unless File.exist?("tmp/tests/second_storage") - spawn_script = Rails.root.join('scripts/gitaly-test-spawn').to_s + spawn_script = Rails.root.join("scripts/gitaly-test-spawn").to_s Bundler.with_original_env do raise "gitaly spawn failed" unless system(spawn_script) end - @gitaly_pid = Integer(File.read('tmp/tests/gitaly.pid')) + @gitaly_pid = Integer(File.read("tmp/tests/gitaly.pid")) Kernel.at_exit { stop_gitaly } @@ -199,15 +199,13 @@ module TestEnv def wait_gitaly sleep_time = 10 sleep_interval = 0.1 - socket = Gitlab::GitalyClient.address('default').sub('unix:', '') + socket = Gitlab::GitalyClient.address("default").sub("unix:", "") Integer(sleep_time / sleep_interval).times do - begin - Socket.unix(socket) - return - rescue - sleep sleep_interval - end + Socket.unix(socket) + return + rescue + sleep sleep_interval end raise "could not connect to gitaly at #{socket.inspect} after #{sleep_time} seconds" @@ -216,39 +214,39 @@ module TestEnv def stop_gitaly return unless @gitaly_pid - Process.kill('KILL', @gitaly_pid) + Process.kill("KILL", @gitaly_pid) rescue Errno::ESRCH # The process can already be gone if the test run was INTerrupted. end def gitaly_url - ENV.fetch('GITALY_REPO_URL', nil) + ENV.fetch("GITALY_REPO_URL", nil) end def setup_factory_repo setup_repo(factory_repo_path, factory_repo_path_bare, factory_repo_name, - BRANCH_SHA) + BRANCH_SHA) end # This repo has a submodule commit that is not present in the main test # repository. def setup_forked_repo setup_repo(forked_repo_path, forked_repo_path_bare, forked_repo_name, - FORKED_BRANCH_SHA) + FORKED_BRANCH_SHA) end def setup_repo(repo_path, repo_path_bare, repo_name, refs) clone_url = "https://gitlab.com/gitlab-org/#{repo_name}.git" unless File.directory?(repo_path) - system(*%W(#{Gitlab.config.git.bin_path} clone -q #{clone_url} #{repo_path})) + system(Gitlab.config.git.bin_path.to_s, "clone", "-q", clone_url.to_s, repo_path.to_s) end set_repo_refs(repo_path, refs) unless File.directory?(repo_path_bare) # We must copy bare repositories because we will push to them. - system(git_env, *%W(#{Gitlab.config.git.bin_path} clone -q --bare #{repo_path} #{repo_path_bare})) + system(git_env, Gitlab.config.git.bin_path.to_s, "clone", "-q", "--bare", repo_path.to_s, repo_path_bare.to_s) end end @@ -257,16 +255,16 @@ module TestEnv FileUtils.mkdir_p(target_repo_path) FileUtils.cp_r("#{File.expand_path(bare_repo)}/.", target_repo_path) - FileUtils.chmod_R 0755, target_repo_path + FileUtils.chmod_R 0o755, target_repo_path set_repo_refs(target_repo_path, refs) end def create_bare_repository(path) FileUtils.mkdir_p(path) - system(git_env, *%W(#{Gitlab.config.git.bin_path} -C #{path} init --bare), - out: '/dev/null', - err: '/dev/null') + system(git_env, Gitlab.config.git.bin_path.to_s, "-C", path.to_s, "init", "--bare", + out: "/dev/null", + err: "/dev/null") end def repos_path @@ -293,7 +291,7 @@ module TestEnv return unless defined?(Capybara) puts "Starting the Capybara driver server..." - Capybara.current_session.visit '/' + Capybara.current_session.visit "/" end def factory_repo_path_bare @@ -305,7 +303,7 @@ module TestEnv end def with_empty_bare_repository(name = nil) - path = Rails.root.join('tmp/tests', name || 'empty-bare-repository').to_s + path = Rails.root.join("tmp/tests", name || "empty-bare-repository").to_s yield(Rugged::Repository.init_at(path, :bare)) ensure @@ -315,30 +313,30 @@ module TestEnv private def factory_repo_path - @factory_repo_path ||= Rails.root.join('tmp', 'tests', factory_repo_name) + @factory_repo_path ||= Rails.root.join("tmp", "tests", factory_repo_name) end def factory_repo_name - 'gitlab-test' + "gitlab-test" end def forked_repo_path - @forked_repo_path ||= Rails.root.join('tmp', 'tests', forked_repo_name) + @forked_repo_path ||= Rails.root.join("tmp", "tests", forked_repo_name) end def forked_repo_name - 'gitlab-test-fork' + "gitlab-test-fork" end # Prevent developer git configurations from being persisted to test # repositories def git_env - { 'GIT_TEMPLATE_DIR' => '' } + {"GIT_TEMPLATE_DIR" => ""} end def set_repo_refs(repo_path, branch_sha) instructions = branch_sha.map { |branch, sha| "update refs/heads/#{branch}\x00#{sha}\x00" }.join("\x00") << "\x00" - update_refs = %W(#{Gitlab.config.git.bin_path} update-ref --stdin -z) + update_refs = %W[#{Gitlab.config.git.bin_path} update-ref --stdin -z] reset = proc do Dir.chdir(repo_path) do IO.popen(update_refs, "w") { |io| io.write(instructions) } @@ -348,7 +346,7 @@ module TestEnv # Try to reset without fetching to avoid using the network. unless reset.call - raise 'Could not fetch test seed repository.' unless system(*%W(#{Gitlab.config.git.bin_path} -C #{repo_path} fetch origin)) + raise "Could not fetch test seed repository." unless system(Gitlab.config.git.bin_path.to_s, "-C", repo_path.to_s, "fetch", "origin") # Before we used Git clone's --mirror option, bare repos could end up # with missing refs, clearing them and retrying should fix the issue. @@ -363,19 +361,18 @@ module TestEnv ensure_component_dir_name_is_correct!(component, install_dir) # On CI, once installed, components never need update - return if File.exist?(install_dir) && ENV['CI'] + return if File.exist?(install_dir) && ENV["CI"] if component_needs_update?(install_dir, version) # Cleanup the component entirely to ensure we start fresh FileUtils.rm_rf(install_dir) - unless system('rake', task) + unless system("rake", task) raise ComponentFailedToInstallError end end yield if block_given? - rescue ComponentFailedToInstallError puts "\n#{component} failed to install, cleaning up #{install_dir}!\n" FileUtils.rm_rf(install_dir) @@ -398,7 +395,7 @@ module TestEnv # Allow local overrides of the component for tests during development return false if Rails.env.test? && File.symlink?(component_folder) - version = File.read(File.join(component_folder, 'VERSION')).strip + version = File.read(File.join(component_folder, "VERSION")).strip # Notice that this will always yield true when using branch versions # (`=branch_name`), but that actually makes sure the server is always based diff --git a/spec/support/helpers/test_request_helpers.rb b/spec/support/helpers/test_request_helpers.rb index 5a84d67bdfc..0424ca5906f 100644 --- a/spec/support/helpers/test_request_helpers.rb +++ b/spec/support/helpers/test_request_helpers.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module TestRequestHelpers - def test_request(remote_ip: '127.0.0.1') - ActionController::TestRequest.new({ remote_ip: remote_ip }, ActionController::TestSession.new) + def test_request(remote_ip: "127.0.0.1") + ActionController::TestRequest.new({remote_ip: remote_ip}, ActionController::TestSession.new) end end diff --git a/spec/support/helpers/upload_helpers.rb b/spec/support/helpers/upload_helpers.rb index 5eead80c935..cc75945e0c6 100644 --- a/spec/support/helpers/upload_helpers.rb +++ b/spec/support/helpers/upload_helpers.rb @@ -1,12 +1,12 @@ -require 'fileutils' +require "fileutils" module UploadHelpers extend self def uploaded_image_temp_path - basename = 'banana_sample.gif' - orig_path = File.join(Rails.root, 'spec', 'fixtures', basename) - tmp_path = File.join(Rails.root, 'tmp', 'tests', basename) + basename = "banana_sample.gif" + orig_path = File.join(Rails.root, "spec", "fixtures", basename) + tmp_path = File.join(Rails.root, "tmp", "tests", basename) # Because we use 'move_to_store' on all uploaders, we create a new # tempfile on each call: the file we return here will be renamed in most # cases. diff --git a/spec/support/helpers/user_login_helper.rb b/spec/support/helpers/user_login_helper.rb index 36c002f53af..47c13820db5 100644 --- a/spec/support/helpers/user_login_helper.rb +++ b/spec/support/helpers/user_login_helper.rb @@ -17,10 +17,10 @@ module UserLoginHelper end def ensure_one_active_tab - expect(page).to have_selector('ul.new-session-tabs > li > a.active', count: 1) + expect(page).to have_selector("ul.new-session-tabs > li > a.active", count: 1) end def ensure_one_active_pane - expect(page).to have_selector('.tab-pane.active', count: 1) + expect(page).to have_selector(".tab-pane.active", count: 1) end end diff --git a/spec/support/helpers/wait_for_requests.rb b/spec/support/helpers/wait_for_requests.rb index c7f878b7371..f39f55f19f7 100644 --- a/spec/support/helpers/wait_for_requests.rb +++ b/spec/support/helpers/wait_for_requests.rb @@ -24,14 +24,14 @@ module WaitForRequests # Wait for client-side AJAX requests def wait_for_requests - wait_for('JS requests complete', max_wait_time: 2 * Capybara.default_max_wait_time) do + wait_for("JS requests complete", max_wait_time: 2 * Capybara.default_max_wait_time) do finished_all_js_requests? end end # Wait for active Rack requests and client-side AJAX requests def wait_for_all_requests - wait_for('pending requests complete') do + wait_for("pending requests complete") do finished_all_rack_reqiests? && finished_all_js_requests? end @@ -65,13 +65,13 @@ module WaitForRequests end def finished_all_vue_resource_requests? - Capybara.page.evaluate_script('window.activeVueResources || 0').zero? + Capybara.page.evaluate_script("window.activeVueResources || 0").zero? end def finished_all_ajax_requests? return true if Capybara.page.evaluate_script('typeof jQuery === "undefined"') - Capybara.page.evaluate_script('jQuery.active').zero? + Capybara.page.evaluate_script("jQuery.active").zero? end def javascript_test? diff --git a/spec/support/helpers/wiki_helpers.rb b/spec/support/helpers/wiki_helpers.rb index 8165403cb60..0e19a960abf 100644 --- a/spec/support/helpers/wiki_helpers.rb +++ b/spec/support/helpers/wiki_helpers.rb @@ -4,10 +4,10 @@ module WikiHelpers def upload_file_to_wiki(project, user, file_name) opts = { file_name: file_name, - file_content: File.read(expand_fixture_path(file_name)) - } + file_content: File.read(expand_fixture_path(file_name)), + } ::Wikis::CreateAttachmentService.new(project, user, opts) - .execute[:result][:file_path] + .execute[:result][:file_path] end end diff --git a/spec/support/helpers/workhorse_helpers.rb b/spec/support/helpers/workhorse_helpers.rb index ef1f9f68671..d585d0e6337 100644 --- a/spec/support/helpers/workhorse_helpers.rb +++ b/spec/support/helpers/workhorse_helpers.rb @@ -4,18 +4,18 @@ module WorkhorseHelpers def workhorse_send_data @_workhorse_send_data ||= begin header = response.headers[Gitlab::Workhorse::SEND_DATA_HEADER] - split_header = header.split(':') + split_header = header.split(":") type = split_header.shift - header = split_header.join(':') + header = split_header.join(":") [ type, - JSON.parse(Base64.urlsafe_decode64(header)) + JSON.parse(Base64.urlsafe_decode64(header)), ] end end def workhorse_internal_api_request_header - jwt_token = JWT.encode({ 'iss' => 'gitlab-workhorse' }, Gitlab::Workhorse.secret, 'HS256') - { 'HTTP_' + Gitlab::Workhorse::INTERNAL_API_REQUEST_HEADER.upcase.tr('-', '_') => jwt_token } + jwt_token = JWT.encode({"iss" => "gitlab-workhorse"}, Gitlab::Workhorse.secret, "HS256") + {"HTTP_" + Gitlab::Workhorse::INTERNAL_API_REQUEST_HEADER.upcase.tr("-", "_") => jwt_token} end end diff --git a/spec/support/http_io/http_io_helpers.rb b/spec/support/http_io/http_io_helpers.rb index 42144870eb5..7f2b0bf1928 100644 --- a/spec/support/http_io/http_io_helpers.rb +++ b/spec/support/http_io/http_io_helpers.rb @@ -15,7 +15,7 @@ module HttpIOHelpers end def remote_url_response(file_path, request, response_status) - range = request.headers['Range'].match(/bytes=(\d+)-(\d+)/) + range = request.headers["Range"].match(/bytes=(\d+)-(\d+)/) body = File.read(file_path).force_encoding(Encoding::BINARY) size = body.bytesize @@ -23,14 +23,14 @@ module HttpIOHelpers { status: response_status, headers: remote_url_response_headers(response_status, range[1].to_i, range[2].to_i, size), - body: body[range[1].to_i..range[2].to_i] + body: body[range[1].to_i..range[2].to_i], } end def remote_url_response_headers(response_status, from, to, size) - { 'Content-Type' => 'text/plain' }.tap do |headers| + {"Content-Type" => "text/plain"}.tap do |headers| if response_status == 206 - headers.merge('Content-Range' => "bytes #{from}-#{to}/#{size}") + headers.merge("Content-Range" => "bytes #{from}-#{to}/#{size}") end end end diff --git a/spec/support/import_export/common_util.rb b/spec/support/import_export/common_util.rb index 2542a59bb00..ce3b5cbdb97 100644 --- a/spec/support/import_export/common_util.rb +++ b/spec/support/import_export/common_util.rb @@ -3,7 +3,7 @@ module ImportExport def setup_symlink(tmpdir, symlink_name) allow_any_instance_of(Gitlab::ImportExport).to receive(:storage_path).and_return(tmpdir) - File.open("#{tmpdir}/test", 'w') { |file| file.write("test") } + File.open("#{tmpdir}/test", "w") { |file| file.write("test") } FileUtils.ln_s("#{tmpdir}/test", "#{tmpdir}/#{symlink_name}") end end diff --git a/spec/support/import_export/configuration_helper.rb b/spec/support/import_export/configuration_helper.rb index b4164cff922..9b41bf5fe68 100644 --- a/spec/support/import_export/configuration_helper.rb +++ b/spec/support/import_export/configuration_helper.rb @@ -14,11 +14,11 @@ module ConfigurationHelper end def parsed_attributes(relation_name, attributes) - excluded_attributes = config_hash['excluded_attributes'][relation_name] - included_attributes = config_hash['included_attributes'][relation_name] + excluded_attributes = config_hash["excluded_attributes"][relation_name] + included_attributes = config_hash["included_attributes"][relation_name] - attributes = attributes - JSON[excluded_attributes.to_json] if excluded_attributes - attributes = attributes & JSON[included_attributes.to_json] if included_attributes + attributes -= JSON[excluded_attributes.to_json] if excluded_attributes + attributes &= JSON[included_attributes.to_json] if included_attributes attributes end diff --git a/spec/support/import_export/export_file_helper.rb b/spec/support/import_export/export_file_helper.rb index ac320934f5a..bc6b219a8f2 100644 --- a/spec/support/import_export/export_file_helper.rb +++ b/spec/support/import_export/export_file_helper.rb @@ -1,4 +1,4 @@ -require './spec/support/import_export/configuration_helper' +require "./spec/support/import_export/configuration_helper" module ExportFileHelper include ConfigurationHelper @@ -20,10 +20,10 @@ module ExportFileHelper create(:label_link, label: label, target: issue) ci_pipeline = create(:ci_pipeline, - project: project, - sha: merge_request.diff_head_sha, - ref: merge_request.source_branch, - statuses: [commit_status]) + project: project, + sha: merge_request.diff_head_sha, + ref: merge_request.source_branch, + statuses: [commit_status]) create(:ci_build, pipeline: ci_pipeline, project: project) create(:milestone, project: project) @@ -31,9 +31,9 @@ module ExportFileHelper create(:note, noteable: merge_request, project: project) create(:note, noteable: snippet, project: project) create(:note_on_commit, - author: user, - project: project, - commit_id: ci_pipeline.sha) + author: user, + project: project, + commit_id: ci_pipeline.sha) event = create(:event, :created, target: milestone, project: project, author: user, action: 5) create(:push_event_payload, event: event) @@ -43,7 +43,7 @@ module ExportFileHelper key = create(:deploy_key) key.projects << project create(:service, project: project) - create(:project_hook, project: project, token: 'token') + create(:project_hook, project: project, token: "token") create(:protected_branch, project: project) project @@ -53,7 +53,7 @@ module ExportFileHelper def in_directory_with_expanded_export(project) Dir.mktmpdir do |tmpdir| export_file = project.export_file.path - _output, exit_status = Gitlab::Popen.popen(%W{tar -zxf #{export_file} -C #{tmpdir}}) + _output, exit_status = Gitlab::Popen.popen(%W[tar -zxf #{export_file} -C #{tmpdir}]) yield(exit_status, tmpdir) end @@ -91,7 +91,7 @@ module ExportFileHelper loop do object_with_parent = deep_find_with_parent(sensitive_word, project_hash) - return nil unless object_with_parent && object_with_parent.object + return nil unless object_with_parent&.object if is_safe_hash?(object_with_parent.parent, sensitive_word) # It's in the safe list, remove hash and keep looking @@ -109,7 +109,7 @@ module ExportFileHelper return false unless parent && safe_list[sensitive_word.to_sym] # Extra attributes that appear in a model but not in the exported hash. - excluded_attributes = ['type'] + excluded_attributes = ["type"] safe_list[sensitive_word.to_sym].each do |model| # Check whether this is a hash attribute inside a model @@ -133,6 +133,6 @@ module ExportFileHelper end def file_permissions(file) - File.lstat(file).mode & 0777 + File.lstat(file).mode & 0o777 end end diff --git a/spec/support/issuables_requiring_filter_shared_examples.rb b/spec/support/issuables_requiring_filter_shared_examples.rb index 71bcc82ee58..caf6b61452a 100644 --- a/spec/support/issuables_requiring_filter_shared_examples.rb +++ b/spec/support/issuables_requiring_filter_shared_examples.rb @@ -1,4 +1,4 @@ -shared_examples 'issuables requiring filter' do |action| +shared_examples "issuables requiring filter" do |action| it "doesn't load any issuables if no filter is set" do expect_any_instance_of(described_class).not_to receive(:issuables_collection) @@ -10,6 +10,6 @@ shared_examples 'issuables requiring filter' do |action| it "loads issuables if at least one filter is set" do expect_any_instance_of(described_class).to receive(:issuables_collection).and_call_original - get action, params: { author_id: user.id } + get action, params: {author_id: user.id} end end diff --git a/spec/support/json_response.rb b/spec/support/json_response.rb index 210b0e6d867..d7645191654 100644 --- a/spec/support/json_response.rb +++ b/spec/support/json_response.rb @@ -1,5 +1,5 @@ RSpec.configure do |config| - config.include_context 'JSON response' - config.include_context 'JSON response', type: :request - config.include_context 'JSON response', :api + config.include_context "JSON response" + config.include_context "JSON response", type: :request + config.include_context "JSON response", :api end diff --git a/spec/support/matchers/access_matchers.rb b/spec/support/matchers/access_matchers.rb index 3e4ca8b7ab0..13522c42848 100644 --- a/spec/support/matchers/access_matchers.rb +++ b/spec/support/matchers/access_matchers.rb @@ -58,7 +58,7 @@ module AccessMatchers @membership = membership end - description { description_for(user, 'allowed') } + description { description_for(user, "allowed") } end matcher :be_denied_for do |user| @@ -73,6 +73,6 @@ module AccessMatchers @membership = membership end - description { description_for(user, 'denied') } + description { description_for(user, "denied") } end end diff --git a/spec/support/matchers/access_matchers_for_controller.rb b/spec/support/matchers/access_matchers_for_controller.rb index 429401a5da8..508af948490 100644 --- a/spec/support/matchers/access_matchers_for_controller.rb +++ b/spec/support/matchers/access_matchers_for_controller.rb @@ -48,7 +48,7 @@ module AccessMatchersForController end def description_for(role, type, expected, result) - "be #{type} for #{role}. Expected: #{expected.join(',')} Got: #{result}" + "be #{type} for #{role}. Expected: #{expected.join(",")} Got: #{result}" end def update_owner(objects, user) @@ -82,7 +82,7 @@ module AccessMatchersForController @objects = objects end - description { description_for(role, 'allowed', EXPECTED_STATUS_CODE_ALLOWED, response.status) } + description { description_for(role, "allowed", EXPECTED_STATUS_CODE_ALLOWED, response.status) } supports_block_expectations end @@ -103,7 +103,7 @@ module AccessMatchersForController @objects = objects end - description { description_for(role, 'denied', EXPECTED_STATUS_CODE_DENIED, response.status) } + description { description_for(role, "denied", EXPECTED_STATUS_CODE_DENIED, response.status) } supports_block_expectations end end diff --git a/spec/support/matchers/background_migrations_matchers.rb b/spec/support/matchers/background_migrations_matchers.rb index f4127efc6ae..82cfa92f16f 100644 --- a/spec/support/matchers/background_migrations_matchers.rb +++ b/spec/support/matchers/background_migrations_matchers.rb @@ -1,21 +1,21 @@ RSpec::Matchers.define :be_scheduled_delayed_migration do |delay, *expected| match do |migration| BackgroundMigrationWorker.jobs.any? do |job| - job['args'] == [migration, expected] && - job['at'].to_i == (delay.to_i + Time.now.to_i) + job["args"] == [migration, expected] && + job["at"].to_i == (delay.to_i + Time.now.to_i) end end failure_message do |migration| "Migration `#{migration}` with args `#{expected.inspect}` " \ - 'not scheduled in expected time!' + "not scheduled in expected time!" end end RSpec::Matchers.define :be_scheduled_migration do |*expected| match do |migration| BackgroundMigrationWorker.jobs.any? do |job| - args = job['args'].size == 1 ? [BackgroundMigrationWorker.jobs[0]['args'][0], []] : job['args'] + args = job["args"].size == 1 ? [BackgroundMigrationWorker.jobs[0]["args"][0], []] : job["args"] args == [migration, expected] end end diff --git a/spec/support/matchers/be_a_binary_string.rb b/spec/support/matchers/be_a_binary_string.rb index f041ae76167..5463136fa92 100644 --- a/spec/support/matchers/be_a_binary_string.rb +++ b/spec/support/matchers/be_a_binary_string.rb @@ -1,6 +1,6 @@ RSpec::Matchers.define :be_a_binary_string do |_| match do |actual| - actual.is_a?(String) && actual.encoding == Encoding.find('ASCII-8BIT') + actual.is_a?(String) && actual.encoding == Encoding.find("ASCII-8BIT") end description do diff --git a/spec/support/matchers/be_url.rb b/spec/support/matchers/be_url.rb index f8096af1b22..7393f39df58 100644 --- a/spec/support/matchers/be_url.rb +++ b/spec/support/matchers/be_url.rb @@ -1,5 +1,7 @@ RSpec::Matchers.define :be_url do |_| match do |actual| - URI.parse(actual) rescue false + URI.parse(actual) + rescue + false end end diff --git a/spec/support/matchers/be_utf8.rb b/spec/support/matchers/be_utf8.rb index ea806352422..582d3b5de36 100644 --- a/spec/support/matchers/be_utf8.rb +++ b/spec/support/matchers/be_utf8.rb @@ -1,6 +1,6 @@ RSpec::Matchers.define :be_utf8 do |_| match do |actual| - actual.is_a?(String) && actual.encoding == Encoding.find('UTF-8') + actual.is_a?(String) && actual.encoding == Encoding.find("UTF-8") end description do diff --git a/spec/support/matchers/disallow_request_matchers.rb b/spec/support/matchers/disallow_request_matchers.rb index db4d90e4fd0..7ee6f30603f 100644 --- a/spec/support/matchers/disallow_request_matchers.rb +++ b/spec/support/matchers/disallow_request_matchers.rb @@ -1,15 +1,15 @@ RSpec::Matchers.define :disallow_request do match do |middleware| - alert = middleware.env['rack.session'].to_hash - .dig('flash', 'flashes', 'alert') + alert = middleware.env["rack.session"].to_hash + .dig("flash", "flashes", "alert") - alert&.include?('You cannot perform write operations') + alert&.include?("You cannot perform write operations") end end RSpec::Matchers.define :disallow_request_in_json do match do |response| json_response = JSON.parse(response.body) - response.body.include?('You cannot perform write operations') && json_response.key?('message') + response.body.include?("You cannot perform write operations") && json_response.key?("message") end end diff --git a/spec/support/matchers/exceed_query_limit.rb b/spec/support/matchers/exceed_query_limit.rb index cd042401f3a..cb2e71ab020 100644 --- a/spec/support/matchers/exceed_query_limit.rb +++ b/spec/support/matchers/exceed_query_limit.rb @@ -23,10 +23,10 @@ module ExceedQueryLimitHelpers def actual_count @actual_count ||= if @query - recorder.log.select { |recorded| recorded =~ @query }.size - else - recorder.count - end + recorder.log.select { |recorded| recorded =~ @query }.size + else + recorder.count + end end def recorder @@ -43,7 +43,7 @@ module ExceedQueryLimitHelpers extra_queries = @recorder.log.reject { |query| counts[query] -= 1 unless counts[query].zero? } extra_queries_display = count_queries(extra_queries).map { |query, count| "[#{count}] #{query}" } - (['Extra queries:'] + extra_queries_display).join("\n\n") + (["Extra queries:"] + extra_queries_display).join("\n\n") else @recorder.log_message end @@ -59,7 +59,7 @@ module ExceedQueryLimitHelpers end def failure_message - threshold_message = threshold > 0 ? " (+#{@threshold})" : '' + threshold_message = threshold > 0 ? " (+#{@threshold})" : "" counts = "#{expected_count}#{threshold_message}" "Expected a maximum of #{counts} queries, got #{actual_count}:\n\n#{log_message}" end diff --git a/spec/support/matchers/execute_check.rb b/spec/support/matchers/execute_check.rb index 7232fad52fb..72982acbdcd 100644 --- a/spec/support/matchers/execute_check.rb +++ b/spec/support/matchers/execute_check.rb @@ -14,10 +14,10 @@ RSpec::Matchers.define :execute_check do |expected| end failure_message do |actual| - 'This matcher must be used with SystemCheck' unless actual == SystemCheck + "This matcher must be used with SystemCheck" unless actual == SystemCheck end failure_message_when_negated do |actual| - 'This matcher must be used with SystemCheck' unless actual == SystemCheck + "This matcher must be used with SystemCheck" unless actual == SystemCheck end end diff --git a/spec/support/matchers/graphql_matchers.rb b/spec/support/matchers/graphql_matchers.rb index 7894484f590..11d6d83dd87 100644 --- a/spec/support/matchers/graphql_matchers.rb +++ b/spec/support/matchers/graphql_matchers.rb @@ -69,7 +69,7 @@ end RSpec::Matchers.define :expose_permissions_using do |expected| match do |type| - permission_field = type.fields['userPermissions'] + permission_field = type.fields["userPermissions"] expect(permission_field).not_to be_nil expect(permission_field.type).to be_non_null diff --git a/spec/support/matchers/have_issuable_counts.rb b/spec/support/matchers/have_issuable_counts.rb index 92cf3de5448..b532fb5887a 100644 --- a/spec/support/matchers/have_issuable_counts.rb +++ b/spec/support/matchers/have_issuable_counts.rb @@ -1,10 +1,10 @@ RSpec::Matchers.define :have_issuable_counts do |opts| - expected_counts = opts.map do |state, count| + expected_counts = opts.map { |state, count| "#{state.to_s.humanize} #{count}" - end + } match do |actual| - actual.within '.issues-state-filters' do + actual.within ".issues-state-filters" do expected_counts.each do |expected_count| expect(actual).to have_content(expected_count) end diff --git a/spec/support/matchers/markdown_matchers.rb b/spec/support/matchers/markdown_matchers.rb index ec4ec6f4038..606ef843aae 100644 --- a/spec/support/matchers/markdown_matchers.rb +++ b/spec/support/matchers/markdown_matchers.rb @@ -16,8 +16,8 @@ module MarkdownMatchers link = actual.at_css('a:contains("Relative Link")') image = actual.at_css('img[alt="Relative Image"]') - expect(link['href']).to end_with('master/doc/README.md') - expect(image['data-src']).to end_with('master/app/assets/images/touch-icon-ipad.png') + expect(link["href"]).to end_with("master/doc/README.md") + expect(image["data-src"]).to end_with("master/app/assets/images/touch-icon-ipad.png") end end @@ -26,11 +26,11 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('gl-emoji', count: 10) + expect(actual).to have_selector("gl-emoji", count: 10) - emoji_element = actual.at_css('gl-emoji') - expect(emoji_element['data-name'].to_s).not_to be_empty - expect(emoji_element['data-unicode-version'].to_s).not_to be_empty + emoji_element = actual.at_css("gl-emoji") + expect(emoji_element["data-name"].to_s).not_to be_empty + expect(emoji_element["data-unicode-version"].to_s).not_to be_empty end end @@ -39,9 +39,9 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('h1 a#user-content-gitlab-markdown') - expect(actual).to have_selector('h2 a#user-content-markdown') - expect(actual).to have_selector('h3 a#user-content-autolinkfilter') + expect(actual).to have_selector("h1 a#user-content-gitlab-markdown") + expect(actual).to have_selector("h2 a#user-content-markdown") + expect(actual).to have_selector("h3 a#user-content-autolinkfilter") end end @@ -54,14 +54,14 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_autolink('http://about.gitlab.com/') - expect(actual).to have_autolink('https://google.com/') - expect(actual).to have_autolink('ftp://ftp.us.debian.org/debian/') - expect(actual).to have_autolink('smb://foo/bar/baz') - expect(actual).to have_autolink('irc://irc.freenode.net/git') - expect(actual).to have_autolink('http://localhost:3000') + expect(actual).to have_autolink("http://about.gitlab.com/") + expect(actual).to have_autolink("https://google.com/") + expect(actual).to have_autolink("ftp://ftp.us.debian.org/debian/") + expect(actual).to have_autolink("smb://foo/bar/baz") + expect(actual).to have_autolink("irc://irc.freenode.net/git") + expect(actual).to have_autolink("http://localhost:3000") - %w(code a kbd).each do |elem| + %w[code a kbd].each do |elem| expect(body).not_to have_selector("#{elem} a") end end @@ -73,16 +73,16 @@ module MarkdownMatchers have_css("img[data-src$='#{src}']") end - prefix = '/namespace1/gitlabhq/wikis' + prefix = "/namespace1/gitlabhq/wikis" set_default_markdown_messages match do |actual| - expect(actual).to have_link('linked-resource', href: "#{prefix}/linked-resource") - expect(actual).to have_link('link-text', href: "#{prefix}/linked-resource") - expect(actual).to have_link('http://example.com', href: 'http://example.com') - expect(actual).to have_link('link-text', href: 'http://example.com/pdfs/gollum.pdf') + expect(actual).to have_link("linked-resource", href: "#{prefix}/linked-resource") + expect(actual).to have_link("link-text", href: "#{prefix}/linked-resource") + expect(actual).to have_link("http://example.com", href: "http://example.com") + expect(actual).to have_link("link-text", href: "http://example.com/pdfs/gollum.pdf") expect(actual).to have_image("#{prefix}/images/example.jpg") - expect(actual).to have_image('http://example.com/images/example.jpg') + expect(actual).to have_image("http://example.com/images/example.jpg") end end @@ -91,7 +91,7 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-project_member', count: 4) + expect(actual).to have_selector("a.gfm.gfm-project_member", count: 4) end end @@ -100,7 +100,7 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-issue', count: 6) + expect(actual).to have_selector("a.gfm.gfm-issue", count: 6) end end @@ -109,8 +109,8 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-merge_request', count: 6) - expect(actual).to have_selector('em a.gfm-merge_request') + expect(actual).to have_selector("a.gfm.gfm-merge_request", count: 6) + expect(actual).to have_selector("em a.gfm-merge_request") end end @@ -119,7 +119,7 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-snippet', count: 5) + expect(actual).to have_selector("a.gfm.gfm-snippet", count: 5) end end @@ -128,7 +128,7 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-commit_range', count: 5) + expect(actual).to have_selector("a.gfm.gfm-commit_range", count: 5) end end @@ -137,7 +137,7 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-commit', count: 5) + expect(actual).to have_selector("a.gfm.gfm-commit", count: 5) end end @@ -146,7 +146,7 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-label', count: 4) + expect(actual).to have_selector("a.gfm.gfm-label", count: 4) end end @@ -155,7 +155,7 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('a.gfm.gfm-milestone', count: 8) + expect(actual).to have_selector("a.gfm.gfm-milestone", count: 8) end end @@ -164,9 +164,9 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('ul.task-list', count: 2) - expect(actual).to have_selector('li.task-list-item', count: 7) - expect(actual).to have_selector('input[checked]', count: 3) + expect(actual).to have_selector("ul.task-list", count: 2) + expect(actual).to have_selector("li.task-list-item", count: 7) + expect(actual).to have_selector("input[checked]", count: 3) end end @@ -175,8 +175,8 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - expect(actual).to have_selector('span.idiff.addition', count: 2) - expect(actual).to have_selector('span.idiff.deletion', count: 2) + expect(actual).to have_selector("span.idiff.addition", count: 2) + expect(actual).to have_selector("span.idiff.deletion", count: 2) end end @@ -185,9 +185,9 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - video = actual.at_css('video') + video = actual.at_css("video") - expect(video['src']).to end_with('/assets/videos/gitlab-demo.mp4') + expect(video["src"]).to end_with("/assets/videos/gitlab-demo.mp4") end end @@ -196,17 +196,17 @@ module MarkdownMatchers set_default_markdown_messages match do |actual| - color_chips = actual.css('code > span.gfm-color_chip > span') + color_chips = actual.css("code > span.gfm-color_chip > span") expect(color_chips.count).to eq(9) [ - '#F00', '#F00A', '#FF0000', '#FF0000AA', 'RGB(0,255,0)', - 'RGB(0%,100%,0%)', 'RGBA(0,255,0,0.7)', 'HSL(540,70%,50%)', - 'HSLA(540,70%,50%,0.7)' + "#F00", "#F00A", "#FF0000", "#FF0000AA", "RGB(0,255,0)", + "RGB(0%,100%,0%)", "RGBA(0,255,0,0.7)", "HSL(540,70%,50%)", + "HSLA(540,70%,50%,0.7)", ].each_with_index do |color, i| parsed_color = Banzai::ColorParser.parse(color) - expect(color_chips[i]['style']).to match("background-color: #{parsed_color};") + expect(color_chips[i]["style"]).to match("background-color: #{parsed_color};") expect(color_chips[i].parent.parent.content).to match(color) end end diff --git a/spec/support/matchers/match_ids.rb b/spec/support/matchers/match_ids.rb index 1cb6b74acac..b7faad433b1 100644 --- a/spec/support/matchers/match_ids.rb +++ b/spec/support/matchers/match_ids.rb @@ -7,7 +7,7 @@ RSpec::Matchers.define :match_ids do |*expected| end description do - 'matches elements by ids' + "matches elements by ids" end failure_message do diff --git a/spec/support/matchers/navigation_matcher.rb b/spec/support/matchers/navigation_matcher.rb index 63f59b9654c..4c4b54630a3 100644 --- a/spec/support/matchers/navigation_matcher.rb +++ b/spec/support/matchers/navigation_matcher.rb @@ -1,12 +1,12 @@ RSpec::Matchers.define :have_active_navigation do |expected| match do |page| - expect(page).to have_selector('.sidebar-top-level-items > li.active', count: 1) - expect(page.find('.sidebar-top-level-items > li.active')).to have_content(expected) + expect(page).to have_selector(".sidebar-top-level-items > li.active", count: 1) + expect(page.find(".sidebar-top-level-items > li.active")).to have_content(expected) end end RSpec::Matchers.define :have_active_sub_navigation do |expected| match do |page| - expect(page.find('.sidebar-sub-level-items > li.active:not(.fly-out-top-item)')).to have_content(expected) + expect(page.find(".sidebar-sub-level-items > li.active:not(.fly-out-top-item)")).to have_content(expected) end end diff --git a/spec/support/matchers/pagination_matcher.rb b/spec/support/matchers/pagination_matcher.rb index 9a7697e2bfc..7034d2be8e1 100644 --- a/spec/support/matchers/pagination_matcher.rb +++ b/spec/support/matchers/pagination_matcher.rb @@ -1,11 +1,11 @@ RSpec::Matchers.define :include_pagination_headers do |expected| match do |actual| - expect(actual.headers).to include('X-Total', 'X-Total-Pages', 'X-Per-Page', 'X-Page', 'X-Next-Page', 'X-Prev-Page', 'Link') + expect(actual.headers).to include("X-Total", "X-Total-Pages", "X-Per-Page", "X-Page", "X-Next-Page", "X-Prev-Page", "Link") end end RSpec::Matchers.define :include_limited_pagination_headers do |expected| match do |actual| - expect(actual.headers).to include('X-Per-Page', 'X-Page', 'X-Next-Page', 'X-Prev-Page', 'Link') + expect(actual.headers).to include("X-Per-Page", "X-Page", "X-Next-Page", "X-Prev-Page", "Link") end end diff --git a/spec/support/matchers/security_header_matcher.rb b/spec/support/matchers/security_header_matcher.rb index f8518d13ebb..816da3de129 100644 --- a/spec/support/matchers/security_header_matcher.rb +++ b/spec/support/matchers/security_header_matcher.rb @@ -1,5 +1,5 @@ RSpec::Matchers.define :include_security_headers do |expected| match do |actual| - expect(actual.headers).to include('X-Content-Type-Options') + expect(actual.headers).to include("X-Content-Type-Options") end end diff --git a/spec/support/migrations_helpers/cluster_helpers.rb b/spec/support/migrations_helpers/cluster_helpers.rb index b54af15c29e..3e3aedd505e 100644 --- a/spec/support/migrations_helpers/cluster_helpers.rb +++ b/spec/support/migrations_helpers/cluster_helpers.rb @@ -4,7 +4,7 @@ module MigrationHelpers module ClusterHelpers # Creates a list of cluster projects. def create_cluster_project_list(quantity) - group = namespaces_table.create(name: 'gitlab-org', path: 'gitlab-org') + group = namespaces_table.create(name: "gitlab-org", path: "gitlab-org") quantity.times do |id| create_cluster_project(group, id) @@ -26,7 +26,7 @@ module MigrationHelpers ) cluster = clusters_table.create( - name: 'test-cluster', + name: "test-cluster", cluster_type: 3, provider_type: :gcp, platform_type: :kubernetes @@ -36,18 +36,18 @@ module MigrationHelpers provider_gcp_table.create!( gcp_project_id: "test-gcp-project-#{id}", - endpoint: '111.111.111.111', + endpoint: "111.111.111.111", cluster_id: cluster.id, status: 3, num_nodes: 1, - zone: 'us-central1-a' + zone: "us-central1-a" ) platform_kubernetes_table.create( cluster_id: cluster.id, - api_url: 'https://kubernetes.example.com', - encrypted_token: 'a' * 40, - encrypted_token_iv: 'a' * 40 + api_url: "https://kubernetes.example.com", + encrypted_token: "a" * 40, + encrypted_token_iv: "a" * 40 ) end diff --git a/spec/support/migrations_helpers/track_untracked_uploads_helpers.rb b/spec/support/migrations_helpers/track_untracked_uploads_helpers.rb index 016bcfa9b1b..7c0e3d35b89 100644 --- a/spec/support/migrations_helpers/track_untracked_uploads_helpers.rb +++ b/spec/support/migrations_helpers/track_untracked_uploads_helpers.rb @@ -1,17 +1,17 @@ module MigrationsHelpers module TrackUntrackedUploadsHelpers - PUBLIC_DIR = File.join(Rails.root, 'tmp', 'tests', 'public') - UPLOADS_DIR = File.join(PUBLIC_DIR, 'uploads') - SYSTEM_DIR = File.join(UPLOADS_DIR, '-', 'system') - UPLOAD_FILENAME = 'image.png'.freeze - FIXTURE_FILE_PATH = File.join(Rails.root, 'spec', 'fixtures', 'dk.png') - FIXTURE_CHECKSUM = 'b804383982bb89b00e828e3f44c038cc991d3d1768009fc39ba8e2c081b9fb75'.freeze + PUBLIC_DIR = File.join(Rails.root, "tmp", "tests", "public") + UPLOADS_DIR = File.join(PUBLIC_DIR, "uploads") + SYSTEM_DIR = File.join(UPLOADS_DIR, "-", "system") + UPLOAD_FILENAME = "image.png".freeze + FIXTURE_FILE_PATH = File.join(Rails.root, "spec", "fixtures", "dk.png") + FIXTURE_CHECKSUM = "b804383982bb89b00e828e3f44c038cc991d3d1768009fc39ba8e2c081b9fb75".freeze def create_or_update_appearance(logo: false, header_logo: false) - appearance = appearances.first_or_create(title: 'foo', description: 'bar', logo: (UPLOAD_FILENAME if logo), header_logo: (UPLOAD_FILENAME if header_logo)) + appearance = appearances.first_or_create(title: "foo", description: "bar", logo: (UPLOAD_FILENAME if logo), header_logo: (UPLOAD_FILENAME if header_logo)) - add_upload(appearance, 'Appearance', 'logo', 'AttachmentUploader') if logo - add_upload(appearance, 'Appearance', 'header_logo', 'AttachmentUploader') if header_logo + add_upload(appearance, "Appearance", "logo", "AttachmentUploader") if logo + add_upload(appearance, "Appearance", "header_logo", "AttachmentUploader") if header_logo appearance end @@ -20,7 +20,7 @@ module MigrationsHelpers index = unique_index(:group) group = namespaces.create(name: "group#{index}", path: "group#{index}", avatar: (UPLOAD_FILENAME if avatar)) - add_upload(group, 'Group', 'avatar', 'AvatarUploader') if avatar + add_upload(group, "Group", "avatar", "AvatarUploader") if avatar group end @@ -28,7 +28,7 @@ module MigrationsHelpers def create_note(attachment: false) note = notes.create(attachment: (UPLOAD_FILENAME if attachment)) - add_upload(note, 'Note', 'attachment', 'AttachmentUploader') if attachment + add_upload(note, "Note", "attachment", "AttachmentUploader") if attachment note end @@ -36,9 +36,9 @@ module MigrationsHelpers def create_project(avatar: false) group = create_group project = projects.create(namespace_id: group.id, path: "project#{unique_index(:project)}", avatar: (UPLOAD_FILENAME if avatar)) - routes.create(path: "#{group.path}/#{project.path}", source_id: project.id, source_type: 'Project') # so Project.find_by_full_path works + routes.create(path: "#{group.path}/#{project.path}", source_id: project.id, source_type: "Project") # so Project.find_by_full_path works - add_upload(project, 'Project', 'avatar', 'AvatarUploader') if avatar + add_upload(project, "Project", "avatar", "AvatarUploader") if avatar project end @@ -46,7 +46,7 @@ module MigrationsHelpers def create_user(avatar: false) user = users.create(email: "foo#{unique_index(:user)}@bar.com", avatar: (UPLOAD_FILENAME if avatar), projects_limit: 100) - add_upload(user, 'User', 'avatar', 'AvatarUploader') if avatar + add_upload(user, "User", "avatar", "AvatarUploader") if avatar user end @@ -59,14 +59,14 @@ module MigrationsHelpers def add_upload(model, model_type, attachment_type, uploader) file_path = upload_file_path(model, model_type, attachment_type) - path_relative_to_public = file_path.sub("#{PUBLIC_DIR}/", '') + path_relative_to_public = file_path.sub("#{PUBLIC_DIR}/", "") create_file(file_path) uploads.create!( size: 1062, path: path_relative_to_public, model_id: model.id, - model_type: model_type == 'Group' ? 'Namespace' : model_type, + model_type: model_type == "Group" ? "Namespace" : model_type, uploader: uploader, checksum: FIXTURE_CHECKSUM ) @@ -76,15 +76,15 @@ module MigrationsHelpers project_dir = hashed_storage ? hashed_project_uploads_dir(project) : legacy_project_uploads_dir(project) attachment_dir = File.join(project_dir, SecureRandom.hex) attachment_file_path = File.join(attachment_dir, UPLOAD_FILENAME) - project_attachment_path_relative_to_project = attachment_file_path.sub("#{project_dir}/", '') + project_attachment_path_relative_to_project = attachment_file_path.sub("#{project_dir}/", "") create_file(attachment_file_path) uploads.create!( size: 1062, path: project_attachment_path_relative_to_project, model_id: project.id, - model_type: 'Project', - uploader: 'FileUploader', + model_type: "Project", + uploader: "FileUploader", checksum: FIXTURE_CHECKSUM ) end @@ -95,7 +95,7 @@ module MigrationsHelpers end def hashed_project_uploads_dir(project) - File.join(UPLOADS_DIR, '@hashed', 'aa', 'aaaaaaaaaaaa') + File.join(UPLOADS_DIR, "@hashed", "aa", "aaaaaaaaaaaa") end def upload_file_path(model, model_type, attachment_type) @@ -118,7 +118,7 @@ module MigrationsHelpers end def get_full_path(project) - routes.find_by(source_id: project.id, source_type: 'Project').path + routes.find_by(source_id: project.id, source_type: "Project").path end def ensure_temporary_tracking_table_exists diff --git a/spec/support/prepare-gitlab-git-test-for-commit b/spec/support/prepare-gitlab-git-test-for-commit index d08e3ba5481..72a11449877 100755 --- a/spec/support/prepare-gitlab-git-test-for-commit +++ b/spec/support/prepare-gitlab-git-test-for-commit @@ -1,11 +1,11 @@ #!/usr/bin/env ruby abort unless [ - system('spec/support/generate-seed-repo-rb', out: 'spec/support/helpers/seed_repo.rb'), - system('spec/support/unpack-gitlab-git-test') + system("spec/support/generate-seed-repo-rb", out: "spec/support/helpers/seed_repo.rb"), + system("spec/support/unpack-gitlab-git-test"), ].all? -exit if ARGV.first != '--check-for-changes' +exit if ARGV.first != "--check-for-changes" git_status = IO.popen(%w[git status --porcelain], &:read) abort unless $?.success? diff --git a/spec/support/prometheus/additional_metrics_shared_examples.rb b/spec/support/prometheus/additional_metrics_shared_examples.rb index 0fd67531c3b..668ec60d1a3 100644 --- a/spec/support/prometheus/additional_metrics_shared_examples.rb +++ b/spec/support/prometheus/additional_metrics_shared_examples.rb @@ -1,36 +1,36 @@ -RSpec.shared_examples 'additional metrics query' do +RSpec.shared_examples "additional metrics query" do include Prometheus::MetricBuilders let(:metric_group_class) { Gitlab::Prometheus::MetricGroup } let(:metric_class) { Gitlab::Prometheus::Metric } - let(:metric_names) { %w{metric_a metric_b} } + let(:metric_names) { %w[metric_a metric_b] } let(:query_range_result) do - [{ 'metric': {}, 'values': [[1488758662.506, '0.00002996364761904785'], [1488758722.506, '0.00003090239047619091']] }] + [{'metric': {}, 'values': [[1488758662.506, "0.00002996364761904785"], [1488758722.506, "0.00003090239047619091"]]}] end - let(:client) { double('prometheus_client') } + let(:client) { double("prometheus_client") } let(:query_result) { described_class.new(client).query(*query_params) } let(:project) { create(:project) } - let(:environment) { create(:environment, slug: 'environment-slug', project: project) } + let(:environment) { create(:environment, slug: "environment-slug", project: project) } before do allow(client).to receive(:label_values).and_return(metric_names) allow(metric_group_class).to receive(:common_metrics).and_return([simple_metric_group(metrics: [simple_metric])]) end - context 'metrics query context' do + context "metrics query context" do subject! { described_class.new(client) } - shared_examples 'query context containing environment slug and filter' do - it 'contains ci_environment_slug' do + shared_examples "query context containing environment slug and filter" do + it "contains ci_environment_slug" do expect(subject).to receive(:query_metrics).with(project, environment, hash_including(ci_environment_slug: environment.slug)) subject.query(*query_params) end - it 'contains environment filter' do + it "contains environment filter" do expect(subject).to receive(:query_metrics).with( project, environment, @@ -43,102 +43,103 @@ RSpec.shared_examples 'additional metrics query' do end end - describe 'project has Kubernetes service' do - shared_examples 'same behavior between KubernetesService and Platform::Kubernetes' do - let(:environment) { create(:environment, slug: 'environment-slug', project: project) } + describe "project has Kubernetes service" do + shared_examples "same behavior between KubernetesService and Platform::Kubernetes" do + let(:environment) { create(:environment, slug: "environment-slug", project: project) } let(:kube_namespace) { project.deployment_platform.actual_namespace } - it_behaves_like 'query context containing environment slug and filter' + it_behaves_like "query context containing environment slug and filter" - it 'query context contains kube_namespace' do + it "query context contains kube_namespace" do expect(subject).to receive(:query_metrics).with(project, environment, hash_including(kube_namespace: kube_namespace)) subject.query(*query_params) end end - context 'when user configured kubernetes from Integration > Kubernetes' do + context "when user configured kubernetes from Integration > Kubernetes" do let(:project) { create(:kubernetes_project) } - it_behaves_like 'same behavior between KubernetesService and Platform::Kubernetes' + it_behaves_like "same behavior between KubernetesService and Platform::Kubernetes" end - context 'when user configured kubernetes from CI/CD > Clusters' do + context "when user configured kubernetes from CI/CD > Clusters" do let!(:cluster) { create(:cluster, :project, :provided_by_gcp) } let(:project) { cluster.project } - it_behaves_like 'same behavior between KubernetesService and Platform::Kubernetes' + it_behaves_like "same behavior between KubernetesService and Platform::Kubernetes" end end - describe 'project without Kubernetes service' do - it_behaves_like 'query context containing environment slug and filter' + describe "project without Kubernetes service" do + it_behaves_like "query context containing environment slug and filter" - it 'query context contains empty kube_namespace' do - expect(subject).to receive(:query_metrics).with(project, environment, hash_including(kube_namespace: '')) + it "query context contains empty kube_namespace" do + expect(subject).to receive(:query_metrics).with(project, environment, hash_including(kube_namespace: "")) subject.query(*query_params) end end end - context 'with one group where two metrics is found' do + context "with one group where two metrics is found" do before do allow(metric_group_class).to receive(:common_metrics).and_return([simple_metric_group]) end - context 'some queries return results' do + context "some queries return results" do before do - allow(client).to receive(:query_range).with('query_range_a', any_args).and_return(query_range_result) - allow(client).to receive(:query_range).with('query_range_b', any_args).and_return(query_range_result) - allow(client).to receive(:query_range).with('query_range_empty', any_args).and_return([]) + allow(client).to receive(:query_range).with("query_range_a", any_args).and_return(query_range_result) + allow(client).to receive(:query_range).with("query_range_b", any_args).and_return(query_range_result) + allow(client).to receive(:query_range).with("query_range_empty", any_args).and_return([]) end - it 'return group data only for queries with results' do + it "return group data only for queries with results" do expected = [ { - group: 'name', + group: "name", priority: 1, metrics: [ { - title: 'title', weight: 1, y_label: 'Values', queries: [ - { query_range: 'query_range_a', result: query_range_result }, - { query_range: 'query_range_b', label: 'label', unit: 'unit', result: query_range_result } - ] - } - ] - } + title: "title", weight: 1, y_label: "Values", queries: [ + {query_range: "query_range_a", result: query_range_result}, + {query_range: "query_range_b", label: "label", unit: "unit", result: query_range_result}, + ], + }, + ], + }, ] - expect(query_result).to match_schema('prometheus/additional_metrics_query_result') + expect(query_result).to match_schema("prometheus/additional_metrics_query_result") expect(query_result).to eq(expected) end end end - context 'with two groups with one metric each' do + context "with two groups with one metric each" do let(:metrics) { [simple_metric(queries: [simple_query])] } before do allow(metric_group_class).to receive(:common_metrics).and_return( [ - simple_metric_group(name: 'group_a', metrics: [simple_metric(queries: [simple_query])]), - simple_metric_group(name: 'group_b', metrics: [simple_metric(title: 'title_b', queries: [simple_query('b')])]) - ]) + simple_metric_group(name: "group_a", metrics: [simple_metric(queries: [simple_query])]), + simple_metric_group(name: "group_b", metrics: [simple_metric(title: "title_b", queries: [simple_query("b")])]), + ] + ) allow(client).to receive(:label_values).and_return(metric_names) end - context 'both queries return results' do + context "both queries return results" do before do - allow(client).to receive(:query_range).with('query_range_a', any_args).and_return(query_range_result) - allow(client).to receive(:query_range).with('query_range_b', any_args).and_return(query_range_result) + allow(client).to receive(:query_range).with("query_range_a", any_args).and_return(query_range_result) + allow(client).to receive(:query_range).with("query_range_b", any_args).and_return(query_range_result) end - it 'return group data both queries' do - queries_with_result_a = { queries: [{ query_range: 'query_range_a', result: query_range_result }] } - queries_with_result_b = { queries: [{ query_range: 'query_range_b', result: query_range_result }] } + it "return group data both queries" do + queries_with_result_a = {queries: [{query_range: "query_range_a", result: query_range_result}]} + queries_with_result_b = {queries: [{query_range: "query_range_b", result: query_range_result}]} - expect(query_result).to match_schema('prometheus/additional_metrics_query_result') + expect(query_result).to match_schema("prometheus/additional_metrics_query_result") expect(query_result.count).to eq(2) expect(query_result).to all(satisfy { |r| r[:metrics].count == 1 }) @@ -148,16 +149,16 @@ RSpec.shared_examples 'additional metrics query' do end end - context 'one query returns result' do + context "one query returns result" do before do - allow(client).to receive(:query_range).with('query_range_a', any_args).and_return(query_range_result) - allow(client).to receive(:query_range).with('query_range_b', any_args).and_return([]) + allow(client).to receive(:query_range).with("query_range_a", any_args).and_return(query_range_result) + allow(client).to receive(:query_range).with("query_range_b", any_args).and_return([]) end - it 'return group data only for query with results' do - queries_with_result = { queries: [{ query_range: 'query_range_a', result: query_range_result }] } + it "return group data only for query with results" do + queries_with_result = {queries: [{query_range: "query_range_a", result: query_range_result}]} - expect(query_result).to match_schema('prometheus/additional_metrics_query_result') + expect(query_result).to match_schema("prometheus/additional_metrics_query_result") expect(query_result.count).to eq(1) expect(query_result).to all(satisfy { |r| r[:metrics].count == 1 }) diff --git a/spec/support/prometheus/metric_builders.rb b/spec/support/prometheus/metric_builders.rb index c8d056d3fc8..8c64e6af4ff 100644 --- a/spec/support/prometheus/metric_builders.rb +++ b/spec/support/prometheus/metric_builders.rb @@ -1,26 +1,26 @@ module Prometheus module MetricBuilders - def simple_query(suffix = 'a', **opts) - { query_range: "query_range_#{suffix}" }.merge(opts) + def simple_query(suffix = "a", **opts) + {query_range: "query_range_#{suffix}"}.merge(opts) end def simple_queries - [simple_query, simple_query('b', label: 'label', unit: 'unit')] + [simple_query, simple_query("b", label: "label", unit: "unit")] end - def simple_metric(title: 'title', required_metrics: [], queries: [simple_query]) + def simple_metric(title: "title", required_metrics: [], queries: [simple_query]) Gitlab::Prometheus::Metric.new(title: title, required_metrics: required_metrics, weight: 1, queries: queries) end - def simple_metrics(added_metric_name: 'metric_a') + def simple_metrics(added_metric_name: "metric_a") [ - simple_metric(required_metrics: %W(#{added_metric_name} metric_b), queries: simple_queries), - simple_metric(required_metrics: [added_metric_name], queries: [simple_query('empty')]), - simple_metric(required_metrics: %w{metric_c}) + simple_metric(required_metrics: %W[#{added_metric_name} metric_b], queries: simple_queries), + simple_metric(required_metrics: [added_metric_name], queries: [simple_query("empty")]), + simple_metric(required_metrics: %w[metric_c]), ] end - def simple_metric_group(name: 'name', metrics: simple_metrics) + def simple_metric_group(name: "name", metrics: simple_metrics) Gitlab::Prometheus::MetricGroup.new(name: name, priority: 1, metrics: metrics) end end diff --git a/spec/support/protected_tags/access_control_ce_shared_examples.rb b/spec/support/protected_tags/access_control_ce_shared_examples.rb index 71eec9f3217..ba587a9edc1 100644 --- a/spec/support/protected_tags/access_control_ce_shared_examples.rb +++ b/spec/support/protected_tags/access_control_ce_shared_examples.rb @@ -3,15 +3,15 @@ RSpec.shared_examples "protected tags > access control > CE" do it "allows creating protected tags that #{access_type_name} can create" do visit project_protected_tags_path(project) - set_protected_tag_name('master') + set_protected_tag_name("master") - within('.js-new-protected-tag') do + within(".js-new-protected-tag") do allowed_to_create_button = find(".js-allowed-to-create") unless allowed_to_create_button.text == access_type_name allowed_to_create_button.click - find('.create_access_levels-container .dropdown-menu li', match: :first) - within('.create_access_levels-container .dropdown-menu') { click_on access_type_name } + find(".create_access_levels-container .dropdown-menu li", match: :first) + within(".create_access_levels-container .dropdown-menu") { click_on access_type_name } end end @@ -24,7 +24,7 @@ RSpec.shared_examples "protected tags > access control > CE" do it "allows updating protected tags so that #{access_type_name} can create them" do visit project_protected_tags_path(project) - set_protected_tag_name('master') + set_protected_tag_name("master") click_on "Protect" @@ -33,7 +33,7 @@ RSpec.shared_examples "protected tags > access control > CE" do within(".protected-tags-list") do find(".js-allowed-to-create").click - within('.js-allowed-to-create-container') do + within(".js-allowed-to-create-container") do expect(first("li")).to have_content("Roles") click_on access_type_name end diff --git a/spec/support/redis/redis_shared_examples.rb b/spec/support/redis/redis_shared_examples.rb index a8b00004fe7..073c8e1b7de 100644 --- a/spec/support/redis/redis_shared_examples.rb +++ b/spec/support/redis/redis_shared_examples.rb @@ -12,10 +12,10 @@ RSpec.shared_examples "redis_shared_examples" do clear_raw_config end - describe '.params' do + describe ".params" do subject { described_class.params } - it 'withstands mutation' do + it "withstands mutation" do params1 = described_class.params params2 = described_class.params params1[:foo] = :bar @@ -23,78 +23,78 @@ RSpec.shared_examples "redis_shared_examples" do expect(params2).not_to have_key(:foo) end - context 'when url contains unix socket reference' do - context 'with old format' do + context "when url contains unix socket reference" do + context "with old format" do let(:config_file_name) { config_old_format_socket } - it 'returns path key instead' do + it "returns path key instead" do is_expected.to include(path: old_socket_path) is_expected.not_to have_key(:url) end end - context 'with new format' do + context "with new format" do let(:config_file_name) { config_new_format_socket } - it 'returns path key instead' do + it "returns path key instead" do is_expected.to include(path: new_socket_path) is_expected.not_to have_key(:url) end end end - context 'when url is host based' do - context 'with old format' do + context "when url is host based" do + context "with old format" do let(:config_file_name) { config_old_format_host } - it 'returns hash with host, port, db, and password' do - is_expected.to include(host: 'localhost', password: 'mypassword', port: redis_port, db: redis_database) + it "returns hash with host, port, db, and password" do + is_expected.to include(host: "localhost", password: "mypassword", port: redis_port, db: redis_database) is_expected.not_to have_key(:url) end end - context 'with new format' do + context "with new format" do let(:config_file_name) { config_new_format_host } - it 'returns hash with host, port, db, and password' do - is_expected.to include(host: 'localhost', password: 'mynewpassword', port: redis_port, db: redis_database) + it "returns hash with host, port, db, and password" do + is_expected.to include(host: "localhost", password: "mynewpassword", port: redis_port, db: redis_database) is_expected.not_to have_key(:url) end end end end - describe '.url' do - it 'withstands mutation' do + describe ".url" do + it "withstands mutation" do url1 = described_class.url url2 = described_class.url - url1 << 'foobar' unless url1.frozen? + url1 << "foobar" unless url1.frozen? - expect(url2).not_to end_with('foobar') + expect(url2).not_to end_with("foobar") end - context 'when yml file with env variable' do + context "when yml file with env variable" do let(:config_file_name) { config_with_environment_variable_inside } before do stub_env(config_env_variable_url, test_redis_url) end - it 'reads redis url from env variable' do + it "reads redis url from env variable" do expect(described_class.url).to eq test_redis_url end end end - describe '._raw_config' do + describe "._raw_config" do subject { described_class._raw_config } - let(:config_file_name) { '/var/empty/doesnotexist' } + let(:config_file_name) { "/var/empty/doesnotexist" } - it 'should be frozen' do + it "should be frozen" do expect(subject).to be_frozen end - it 'returns false when the file does not exist' do + it "returns false when the file does not exist" do expect(subject).to eq(false) end @@ -105,7 +105,7 @@ RSpec.shared_examples "redis_shared_examples" do end end - describe '.with' do + describe ".with" do before do clear_pool end @@ -113,25 +113,25 @@ RSpec.shared_examples "redis_shared_examples" do clear_pool end - context 'when running not on sidekiq workers' do + context "when running not on sidekiq workers" do before do allow(Sidekiq).to receive(:server?).and_return(false) end - it 'instantiates a connection pool with size 5' do + it "instantiates a connection pool with size 5" do expect(ConnectionPool).to receive(:new).with(size: 5).and_call_original described_class.with { |_redis_shared_example| true } end end - context 'when running on sidekiq workers' do + context "when running on sidekiq workers" do before do allow(Sidekiq).to receive(:server?).and_return(true) - allow(Sidekiq).to receive(:options).and_return({ concurrency: 18 }) + allow(Sidekiq).to receive(:options).and_return({concurrency: 18}) end - it 'instantiates a connection pool with a size based on the concurrency of the worker' do + it "instantiates a connection pool with a size based on the concurrency of the worker" do expect(ConnectionPool).to receive(:new).with(size: 18 + 5).and_call_original described_class.with { |_redis_shared_example| true } @@ -139,68 +139,68 @@ RSpec.shared_examples "redis_shared_examples" do end end - describe '#sentinels' do + describe "#sentinels" do subject { described_class.new(Rails.env).sentinels } - context 'when sentinels are defined' do + context "when sentinels are defined" do let(:config_file_name) { config_new_format_host } - it 'returns an array of hashes with host and port keys' do - is_expected.to include(host: 'localhost', port: sentinel_port) - is_expected.to include(host: 'slave2', port: sentinel_port) + it "returns an array of hashes with host and port keys" do + is_expected.to include(host: "localhost", port: sentinel_port) + is_expected.to include(host: "slave2", port: sentinel_port) end end - context 'when sentinels are not defined' do + context "when sentinels are not defined" do let(:config_file_name) { config_old_format_host } - it 'returns nil' do + it "returns nil" do is_expected.to be_nil end end end - describe '#sentinels?' do + describe "#sentinels?" do subject { described_class.new(Rails.env).sentinels? } - context 'when sentinels are defined' do + context "when sentinels are defined" do let(:config_file_name) { config_new_format_host } - it 'returns true' do + it "returns true" do is_expected.to be_truthy end end - context 'when sentinels are not defined' do + context "when sentinels are not defined" do let(:config_file_name) { config_old_format_host } - it 'returns false' do + it "returns false" do is_expected.to be_falsey end end end - describe '#raw_config_hash' do - it 'returns default redis url when no config file is present' do + describe "#raw_config_hash" do + it "returns default redis url when no config file is present" do expect(subject).to receive(:fetch_config) { false } - expect(subject.send(:raw_config_hash)).to eq(url: class_redis_url ) + expect(subject.send(:raw_config_hash)).to eq(url: class_redis_url) end - it 'returns old-style single url config in a hash' do + it "returns old-style single url config in a hash" do expect(subject).to receive(:fetch_config) { test_redis_url } expect(subject.send(:raw_config_hash)).to eq(url: test_redis_url) end end - describe '#fetch_config' do - it 'returns false when no config file is present' do + describe "#fetch_config" do + it "returns false when no config file is present" do allow(described_class).to receive(:_raw_config) { false } expect(subject.send(:fetch_config)).to eq false end - it 'returns false when config file is present but has invalid YAML' do + it "returns false when config file is present but has invalid YAML" do allow(described_class).to receive(:_raw_config) { "# development: true" } expect(subject.send(:fetch_config)).to eq false diff --git a/spec/support/services/clusters/create_service_shared.rb b/spec/support/services/clusters/create_service_shared.rb index b0bf942aa09..6e16943932e 100644 --- a/spec/support/services/clusters/create_service_shared.rb +++ b/spec/support/services/clusters/create_service_shared.rb @@ -1,57 +1,57 @@ -shared_context 'valid cluster create params' do +shared_context "valid cluster create params" do let(:params) do { - name: 'test-cluster', + name: "test-cluster", provider_type: :gcp, provider_gcp_attributes: { - gcp_project_id: 'gcp-project', - zone: 'us-central1-a', + gcp_project_id: "gcp-project", + zone: "us-central1-a", num_nodes: 1, - machine_type: 'machine_type-a', - legacy_abac: 'true' - } + machine_type: "machine_type-a", + legacy_abac: "true", + }, } end end -shared_context 'invalid cluster create params' do +shared_context "invalid cluster create params" do let(:params) do { - name: 'test-cluster', + name: "test-cluster", provider_type: :gcp, provider_gcp_attributes: { - gcp_project_id: '!!!!!!!', - zone: 'us-central1-a', + gcp_project_id: "!!!!!!!", + zone: "us-central1-a", num_nodes: 1, - machine_type: 'machine_type-a' - } + machine_type: "machine_type-a", + }, } end end -shared_examples 'create cluster service success' do - it 'creates a cluster object and performs a worker' do +shared_examples "create cluster service success" do + it "creates a cluster object and performs a worker" do expect(ClusterProvisionWorker).to receive(:perform_async) expect { subject } .to change { Clusters::Cluster.count }.by(1) .and change { Clusters::Providers::Gcp.count }.by(1) - expect(subject.name).to eq('test-cluster') + expect(subject.name).to eq("test-cluster") expect(subject.user).to eq(user) expect(subject.project).to eq(project) - expect(subject.provider.gcp_project_id).to eq('gcp-project') - expect(subject.provider.zone).to eq('us-central1-a') + expect(subject.provider.gcp_project_id).to eq("gcp-project") + expect(subject.provider.zone).to eq("us-central1-a") expect(subject.provider.num_nodes).to eq(1) - expect(subject.provider.machine_type).to eq('machine_type-a') + expect(subject.provider.machine_type).to eq("machine_type-a") expect(subject.provider.access_token).to eq(access_token) expect(subject.provider).to be_legacy_abac expect(subject.platform).to be_nil end end -shared_examples 'create cluster service error' do - it 'returns an error' do +shared_examples "create cluster service error" do + it "returns an error" do expect(ClusterProvisionWorker).not_to receive(:perform_async) expect { subject }.to change { Clusters::Cluster.count }.by(0) expect(subject.errors[:"provider_gcp.gcp_project_id"]).to be_present diff --git a/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb b/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb index 8b4cffaac19..ef92fa63e41 100644 --- a/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb +++ b/spec/support/services/issuable_create_service_slash_commands_shared_examples.rb @@ -1,13 +1,13 @@ # Specifications for behavior common to all objects with executable attributes. # It can take a `default_params`. -shared_examples 'new issuable record that supports quick actions' do +shared_examples "new issuable record that supports quick actions" do let!(:project) { create(:project, :repository) } let(:user) { create(:user).tap { |u| project.add_maintainer(u) } } let(:assignee) { create(:user) } let!(:milestone) { create(:milestone, project: project) } let!(:labels) { create_list(:label, 3, project: project) } - let(:base_params) { { title: 'My issuable title' } } + let(:base_params) { {title: "My issuable title"} } let(:params) { base_params.merge(defined?(default_params) ? default_params : {}).merge(example_params) } let(:issuable) { described_class.new(project, user, params).execute } @@ -15,55 +15,55 @@ shared_examples 'new issuable record that supports quick actions' do project.add_maintainer(assignee) end - context 'with labels in command only' do + context "with labels in command only" do let(:example_params) do { - description: "/label ~#{labels.first.name} ~#{labels.second.name}\n/unlabel ~#{labels.third.name}" + description: "/label ~#{labels.first.name} ~#{labels.second.name}\n/unlabel ~#{labels.third.name}", } end - it 'attaches labels to issuable' do + it "attaches labels to issuable" do expect(issuable).to be_persisted expect(issuable.label_ids).to match_array([labels.first.id, labels.second.id]) end end - context 'with labels in params and command' do + context "with labels in params and command" do let(:example_params) do { label_ids: [labels.second.id], - description: "/label ~#{labels.first.name}\n/unlabel ~#{labels.third.name}" + description: "/label ~#{labels.first.name}\n/unlabel ~#{labels.third.name}", } end - it 'attaches all labels to issuable' do + it "attaches all labels to issuable" do expect(issuable).to be_persisted expect(issuable.label_ids).to match_array([labels.first.id, labels.second.id]) end end - context 'with assignee and milestone in command only' do + context "with assignee and milestone in command only" do let(:example_params) do { - description: %(/assign @#{assignee.username}\n/milestone %"#{milestone.name}") + description: %(/assign @#{assignee.username}\n/milestone %"#{milestone.name}"), } end - it 'assigns and sets milestone to issuable' do + it "assigns and sets milestone to issuable" do expect(issuable).to be_persisted expect(issuable.assignees).to eq([assignee]) expect(issuable.milestone).to eq(milestone) end end - describe '/close' do + describe "/close" do let(:example_params) do { - description: '/close' + description: "/close", } end - it 'returns an open issue' do + it "returns an open issue" do expect(issuable).to be_persisted expect(issuable).to be_open end diff --git a/spec/support/services/issuable_update_service_shared_examples.rb b/spec/support/services/issuable_update_service_shared_examples.rb index ffbce6c42bf..f17a3aadaf5 100644 --- a/spec/support/services/issuable_update_service_shared_examples.rb +++ b/spec/support/services/issuable_update_service_shared_examples.rb @@ -1,22 +1,22 @@ -shared_examples 'issuable update service' do +shared_examples "issuable update service" do def update_issuable(opts) described_class.new(project, user, opts).execute(open_issuable) end - context 'changing state' do + context "changing state" do before do expect(project).to receive(:execute_hooks).once end - context 'to reopened' do - it 'executes hooks only once' do - described_class.new(project, user, state_event: 'reopen').execute(closed_issuable) + context "to reopened" do + it "executes hooks only once" do + described_class.new(project, user, state_event: "reopen").execute(closed_issuable) end end - context 'to closed' do - it 'executes hooks only once' do - described_class.new(project, user, state_event: 'close').execute(open_issuable) + context "to closed" do + it "executes hooks only once" do + described_class.new(project, user, state_event: "close").execute(open_issuable) end end end diff --git a/spec/support/services/migrate_to_ghost_user_service_shared_examples.rb b/spec/support/services/migrate_to_ghost_user_service_shared_examples.rb index 62ae95df8c0..12beff681ca 100644 --- a/spec/support/services/migrate_to_ghost_user_service_shared_examples.rb +++ b/spec/support/services/migrate_to_ghost_user_service_shared_examples.rb @@ -49,7 +49,7 @@ shared_examples "migrating a deleted user's associated records to the ghost user .to receive(:update_all).and_raise(ActiveRecord::Rollback) end - it 'rolls back the user block' do + it "rolls back the user block" do service.execute expect(user.reload).not_to be_blocked @@ -70,8 +70,12 @@ shared_examples "migrating a deleted user's associated records to the ghost user .to receive(:update_all).and_raise(ArgumentError) end - it 'rolls back the user block' do - service.execute rescue nil + it "rolls back the user block" do + begin + service.execute + rescue + nil + end expect(user.reload).not_to be_blocked end @@ -79,14 +83,18 @@ shared_examples "migrating a deleted user's associated records to the ghost user it "doesn't unblock an previously-blocked user" do user.block - service.execute rescue nil + begin + service.execute + rescue + nil + end expect(user.reload).to be_blocked end end it "blocks the user before #{record_class_name} migration begins" do - expect(service).to receive("migrate_#{record_class_name.parameterize(separator: '_').pluralize}".to_sym) do + expect(service).to receive("migrate_#{record_class_name.parameterize(separator: "_").pluralize}".to_sym) do expect(user.reload).to be_blocked end diff --git a/spec/support/setup_builds_storage.rb b/spec/support/setup_builds_storage.rb index 1d2a4856724..b2386e6bef1 100644 --- a/spec/support/setup_builds_storage.rb +++ b/spec/support/setup_builds_storage.rb @@ -1,10 +1,10 @@ RSpec.configure do |config| def builds_path - Rails.root.join('tmp/tests/builds') + Rails.root.join("tmp/tests/builds") end config.before(:suite) do - Settings.gitlab_ci['builds_path'] = builds_path + Settings.gitlab_ci["builds_path"] = builds_path end config.before(:all) do diff --git a/spec/support/shared_contexts/change_access_checks_shared_context.rb b/spec/support/shared_contexts/change_access_checks_shared_context.rb index aca18b0c73b..df5594e0379 100644 --- a/spec/support/shared_contexts/change_access_checks_shared_context.rb +++ b/spec/support/shared_contexts/change_access_checks_shared_context.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true -shared_context 'change access checks context' do +shared_context "change access checks context" do let(:user) { create(:user) } let(:project) { create(:project, :repository) } let(:user_access) { Gitlab::UserAccess.new(user, project: project) } - let(:oldrev) { 'be93687618e4b132087f430a4d8fc3a609c9b77c' } - let(:newrev) { '54fcc214b94e78d7a41a9a8fe6d87a5e59500e51' } - let(:ref) { 'refs/heads/master' } - let(:changes) { { oldrev: oldrev, newrev: newrev, ref: ref } } - let(:protocol) { 'ssh' } + let(:oldrev) { "be93687618e4b132087f430a4d8fc3a609c9b77c" } + let(:newrev) { "54fcc214b94e78d7a41a9a8fe6d87a5e59500e51" } + let(:ref) { "refs/heads/master" } + let(:changes) { {oldrev: oldrev, newrev: newrev, ref: ref} } + let(:protocol) { "ssh" } let(:timeout) { Gitlab::GitAccess::INTERNAL_TIMEOUT } let(:logger) { Gitlab::Checks::TimedLogger.new(timeout: timeout) } let(:change_access) do diff --git a/spec/support/shared_contexts/email_shared_context.rb b/spec/support/shared_contexts/email_shared_context.rb index 9d806fc524d..99121d7bc2b 100644 --- a/spec/support/shared_contexts/email_shared_context.rb +++ b/spec/support/shared_contexts/email_shared_context.rb @@ -1,4 +1,4 @@ -require 'gitlab/email/receiver' +require "gitlab/email/receiver" shared_context :email_shared_context do let(:mail_key) { "59d8df8370b7e95c5a49fbf86aeb2c93" } @@ -11,8 +11,8 @@ shared_context :email_shared_context do { url: "uploads/image.png", alt: "image", - markdown: markdown - } + markdown: markdown, + }, ] ) end diff --git a/spec/support/shared_contexts/json_response_shared_context.rb b/spec/support/shared_contexts/json_response_shared_context.rb index df5fc288089..3ff5b9bfd5f 100644 --- a/spec/support/shared_contexts/json_response_shared_context.rb +++ b/spec/support/shared_contexts/json_response_shared_context.rb @@ -1,3 +1,3 @@ -shared_context 'JSON response' do +shared_context "JSON response" do let(:json_response) { JSON.parse(response.body) } end diff --git a/spec/support/shared_contexts/merge_requests_allowing_collaboration.rb b/spec/support/shared_contexts/merge_requests_allowing_collaboration.rb index 05424d08b9d..11e6b1eeea5 100644 --- a/spec/support/shared_contexts/merge_requests_allowing_collaboration.rb +++ b/spec/support/shared_contexts/merge_requests_allowing_collaboration.rb @@ -1,4 +1,4 @@ -shared_context 'merge request allowing collaboration' do +shared_context "merge request allowing collaboration" do include ProjectForksHelper let(:canonical) { create(:project, :public, :repository) } @@ -7,9 +7,9 @@ shared_context 'merge request allowing collaboration' do before do canonical.add_maintainer(user) create(:merge_request, - target_project: canonical, - source_project: forked_project, - source_branch: 'feature', - allow_collaboration: true) + target_project: canonical, + source_project: forked_project, + source_branch: "feature", + allow_collaboration: true) end end diff --git a/spec/support/shared_contexts/services_shared_context.rb b/spec/support/shared_contexts/services_shared_context.rb index d92e8318fa0..c272d9af975 100644 --- a/spec/support/shared_contexts/services_shared_context.rb +++ b/spec/support/shared_contexts/services_shared_context.rb @@ -8,18 +8,18 @@ Service.available_services_names.each do |service| let(:service_attrs_list) { service_fields.inject([]) {|arr, hash| arr << hash[:name].to_sym } } let(:service_attrs) do service_attrs_list.inject({}) do |hash, k| - if k =~ /^(token*|.*_token|.*_key)/ - hash.merge!(k => 'secrettoken') - elsif k =~ /^(.*_url|url|webhook)/ + if /^(token*|.*_token|.*_key)/.match?(k) + hash.merge!(k => "secrettoken") + elsif /^(.*_url|url|webhook)/.match?(k) hash.merge!(k => "http://example.com") elsif service_klass.method_defined?("#{k}?") hash.merge!(k => true) - elsif service == 'irker' && k == :recipients - hash.merge!(k => 'irc://irc.network.net:666/#channel') - elsif service == 'irker' && k == :server_port + elsif service == "irker" && k == :recipients + hash.merge!(k => "irc://irc.network.net:666/#channel") + elsif service == "irker" && k == :server_port hash.merge!(k => 1234) - elsif service == 'jira' && k == :jira_issue_transition_id - hash.merge!(k => '1,2,3') + elsif service == "jira" && k == :jira_issue_transition_id + hash.merge!(k => "1,2,3") else hash.merge!(k => "someword") end diff --git a/spec/support/shared_contexts/url_shared_context.rb b/spec/support/shared_contexts/url_shared_context.rb index 1b1f67daac3..db971c5f612 100644 --- a/spec/support/shared_contexts/url_shared_context.rb +++ b/spec/support/shared_contexts/url_shared_context.rb @@ -1,4 +1,4 @@ -shared_context 'invalid urls' do +shared_context "invalid urls" do let(:urls_with_CRLF) do ["http://127.0.0.1:333/pa\rth", "http://127.0.0.1:333/pa\nth", @@ -12,6 +12,6 @@ shared_context 'invalid urls' do "http://127.0.0.1:333/pa%0D%0Ath", "http://127.0.0.1:333/path?param=foo%0Abar", "http://127.0.0.1:333/path?param=foo%0Dbar", - "http://127.0.0.1:333/path?param=foo%0D%0Abar"] + "http://127.0.0.1:333/path?param=foo%0D%0Abar",] end end diff --git a/spec/support/shared_examples/chat_slash_commands_shared_examples.rb b/spec/support/shared_examples/chat_slash_commands_shared_examples.rb index dc97a39f051..6e42de4db6e 100644 --- a/spec/support/shared_examples/chat_slash_commands_shared_examples.rb +++ b/spec/support/shared_examples/chat_slash_commands_shared_examples.rb @@ -1,51 +1,51 @@ -RSpec.shared_examples 'chat slash commands service' do +RSpec.shared_examples "chat slash commands service" do describe "Associations" do it { is_expected.to respond_to :token } it { is_expected.to have_many :chat_names } end - describe '#valid_token?' do + describe "#valid_token?" do subject { described_class.new } - context 'when the token is empty' do - it 'is false' do - expect(subject.valid_token?('wer')).to be_falsey + context "when the token is empty" do + it "is false" do + expect(subject.valid_token?("wer")).to be_falsey end end - context 'when there is a token' do + context "when there is a token" do before do - subject.token = '123' + subject.token = "123" end - it 'accepts equal tokens' do - expect(subject.valid_token?('123')).to be_truthy + it "accepts equal tokens" do + expect(subject.valid_token?("123")).to be_truthy end end end - describe '#trigger' do + describe "#trigger" do subject { described_class.new } - context 'no token is passed' do - let(:params) { Hash.new } + context "no token is passed" do + let(:params) { {} } - it 'returns nil' do + it "returns nil" do expect(subject.trigger(params)).to be_nil end end - context 'with a token passed' do + context "with a token passed" do let(:project) { create(:project) } - let(:params) { { token: 'token' } } + let(:params) { {token: "token"} } before do - allow(subject).to receive(:token).and_return('token') + allow(subject).to receive(:token).and_return("token") end - context 'no user can be found' do - context 'when no url can be generated' do - it 'responds with the authorize url' do + context "no user can be found" do + context "when no url can be generated" do + it "responds with the authorize url" do response = subject.trigger(params) expect(response[:response_type]).to eq :ephemeral @@ -53,40 +53,40 @@ RSpec.shared_examples 'chat slash commands service' do end end - context 'when an auth url can be generated' do + context "when an auth url can be generated" do let(:params) do { - team_domain: 'http://domain.tld', - team_id: 'T3423423', - user_id: 'U234234', - user_name: 'mepmep', - token: 'token' + team_domain: "http://domain.tld", + team_id: "T3423423", + user_id: "U234234", + user_name: "mepmep", + token: "token", } end let(:service) do project.create_mattermost_slash_commands_service( - properties: { token: 'token' } + properties: {token: "token"} ) end - it 'generates the url' do + it "generates the url" do response = service.trigger(params) - expect(response[:text]).to start_with(':wave: Hi there!') + expect(response[:text]).to start_with(":wave: Hi there!") end end end - context 'when the user is authenticated' do + context "when the user is authenticated" do let!(:chat_name) { create(:chat_name, service: subject) } - let(:params) { { token: 'token', team_id: chat_name.team_id, user_id: chat_name.chat_id } } + let(:params) { {token: "token", team_id: chat_name.team_id, user_id: chat_name.chat_id} } subject do - described_class.create(project: project, properties: { token: 'token' }) + described_class.create(project: project, properties: {token: "token"}) end - it 'triggers the command' do + it "triggers the command" do expect_any_instance_of(Gitlab::SlashCommands::Command).to receive(:execute) subject.trigger(params) diff --git a/spec/support/shared_examples/ci_trace_shared_examples.rb b/spec/support/shared_examples/ci_trace_shared_examples.rb index c603421d748..82170c03b78 100644 --- a/spec/support/shared_examples/ci_trace_shared_examples.rb +++ b/spec/support/shared_examples/ci_trace_shared_examples.rb @@ -1,5 +1,5 @@ -shared_examples_for 'common trace features' do - describe '#html' do +shared_examples_for "common trace features" do + describe "#html" do before do trace.set("12\n34") end @@ -13,7 +13,7 @@ shared_examples_for 'common trace features' do end end - describe '#raw' do + describe "#raw" do before do trace.set("12\n34") end @@ -27,12 +27,12 @@ shared_examples_for 'common trace features' do end end - describe '#extract_coverage' do + describe "#extract_coverage" do let(:regex) { '\(\d+.\d+\%\) covered' } - context 'matching coverage' do + context "matching coverage" do before do - trace.set('Coverage 1033 / 1051 LOC (98.29%) covered') + trace.set("Coverage 1033 / 1051 LOC (98.29%) covered") end it "returns valid coverage" do @@ -40,50 +40,50 @@ shared_examples_for 'common trace features' do end end - context 'no coverage' do + context "no coverage" do before do - trace.set('No coverage') + trace.set("No coverage") end - it 'returs nil' do + it "returs nil" do expect(trace.extract_coverage(regex)).to be_nil end end end - describe '#extract_sections' do - let(:log) { 'No sections' } + describe "#extract_sections" do + let(:log) { "No sections" } let(:sections) { trace.extract_sections } before do trace.set(log) end - context 'no sections' do - it 'returs []' do + context "no sections" do + it "returs []" do expect(trace.extract_sections).to eq([]) end end - context 'multiple sections available' do - let(:log) { File.read(expand_fixture_path('trace/trace_with_sections')) } + context "multiple sections available" do + let(:log) { File.read(expand_fixture_path("trace/trace_with_sections")) } let(:sections_data) do [ - { name: 'prepare_script', lines: 2, duration: 3.seconds }, - { name: 'get_sources', lines: 4, duration: 1.second }, - { name: 'restore_cache', lines: 0, duration: 0.seconds }, - { name: 'download_artifacts', lines: 0, duration: 0.seconds }, - { name: 'build_script', lines: 2, duration: 1.second }, - { name: 'after_script', lines: 0, duration: 0.seconds }, - { name: 'archive_cache', lines: 0, duration: 0.seconds }, - { name: 'upload_artifacts', lines: 0, duration: 0.seconds } + {name: "prepare_script", lines: 2, duration: 3.seconds}, + {name: "get_sources", lines: 4, duration: 1.second}, + {name: "restore_cache", lines: 0, duration: 0.seconds}, + {name: "download_artifacts", lines: 0, duration: 0.seconds}, + {name: "build_script", lines: 2, duration: 1.second}, + {name: "after_script", lines: 0, duration: 0.seconds}, + {name: "archive_cache", lines: 0, duration: 0.seconds}, + {name: "upload_artifacts", lines: 0, duration: 0.seconds}, ] end it "returns valid sections" do expect(sections).not_to be_empty expect(sections.size).to eq(sections_data.size), - "expected #{sections_data.size} sections, got #{sections.size}" + "expected #{sections_data.size} sections, got #{sections.size}" buff = StringIO.new(log) sections.each_with_index do |s, i| @@ -108,12 +108,12 @@ shared_examples_for 'common trace features' do expect(sections.size).to eq(1) section = sections[0] - expect(section[:name]).to eq('a_section') + expect(section[:name]).to eq("a_section") expect(section[:byte_start]).not_to eq(section[:byte_end]), "got an empty section" end end - context 'missing section_end' do + context "missing section_end" do let(:log) { "section_start:1506417476:a_section\r\033[0KSome logs\nNo section_end\n"} it "returns no sections" do @@ -121,7 +121,7 @@ shared_examples_for 'common trace features' do end end - context 'missing section_start' do + context "missing section_start" do let(:log) { "Some logs\nNo section_start\nsection_end:1506417476:a_section\r\033[0K"} it "returns no sections" do @@ -129,7 +129,7 @@ shared_examples_for 'common trace features' do end end - context 'inverted section_start section_end' do + context "inverted section_start section_end" do let(:log) { "section_end:1506417476:a_section\r\033[0Klooks like a section_start:invalid\nsection_start:1506417477:a_section\r\033[0K"} it "returns no sections" do @@ -138,29 +138,29 @@ shared_examples_for 'common trace features' do end end - describe '#write' do + describe "#write" do subject { trace.send(:write, mode) { } } - let(:mode) { 'wb' } + let(:mode) { "wb" } - context 'when arhicved trace does not exist yet' do - it 'does not raise an error' do + context "when arhicved trace does not exist yet" do + it "does not raise an error" do expect { subject }.not_to raise_error end end - context 'when arhicved trace already exists' do + context "when arhicved trace already exists" do before do create(:ci_job_artifact, :trace, job: build) end - it 'raises an error' do + it "raises an error" do expect { subject }.to raise_error(Gitlab::Ci::Trace::AlreadyArchivedError) end end end - describe '#set' do + describe "#set" do before do trace.set("12") end @@ -169,7 +169,7 @@ shared_examples_for 'common trace features' do expect(trace.raw).to eq("12") end - context 'overwrite trace' do + context "overwrite trace" do before do trace.set("34") end @@ -179,7 +179,7 @@ shared_examples_for 'common trace features' do end end - context 'runners token' do + context "runners token" do let(:token) { build.project.runners_token } before do @@ -191,7 +191,7 @@ shared_examples_for 'common trace features' do end end - context 'hides build token' do + context "hides build token" do let(:token) { build.token } before do @@ -204,7 +204,7 @@ shared_examples_for 'common trace features' do end end - describe '#append' do + describe "#append" do before do trace.set("1234") end @@ -214,15 +214,15 @@ shared_examples_for 'common trace features' do expect(trace.raw).to eq("123456") end - context 'tries to append trace at different offset' do + context "tries to append trace at different offset" do it "fails with append" do expect(trace.append("56", 2)).to eq(4) expect(trace.raw).to eq("1234") end end - context 'runners token' do - let(:token) { 'my_secret_token' } + context "runners token" do + let(:token) { "my_secret_token" } before do build.project.update(runners_token: token) @@ -234,8 +234,8 @@ shared_examples_for 'common trace features' do end end - context 'build token' do - let(:token) { 'my_secret_token' } + context "build token" do + let(:token) { "my_secret_token" } before do build.update(token: token) @@ -248,32 +248,32 @@ shared_examples_for 'common trace features' do end end - describe '#archive!' do + describe "#archive!" do subject { trace.archive! } - context 'when build status is success' do + context "when build status is success" do let!(:build) { create(:ci_build, :success, :trace_live) } - it 'does not have an archived trace yet' do + it "does not have an archived trace yet" do expect(build.job_artifacts_trace).to be_nil end - context 'when archives' do - it 'has an archived trace' do + context "when archives" do + it "has an archived trace" do subject build.reload expect(build.job_artifacts_trace).to be_exist end - context 'when another process has already been archiving', :clean_gitlab_redis_shared_state do + context "when another process has already been archiving", :clean_gitlab_redis_shared_state do include ExclusiveLeaseHelpers before do stub_exclusive_lease_taken("trace:write:lock:#{trace.job.id}", timeout: 1.minute) end - it 'blocks concurrent archiving' do + it "blocks concurrent archiving" do expect { subject }.to raise_error(::Gitlab::ExclusiveLeaseHelpers::FailedToObtainLockError) end end @@ -282,12 +282,12 @@ shared_examples_for 'common trace features' do end end -shared_examples_for 'trace with disabled live trace feature' do - it_behaves_like 'common trace features' +shared_examples_for "trace with disabled live trace feature" do + it_behaves_like "common trace features" - describe '#read' do - shared_examples 'read successfully with IO' do - it 'yields with source' do + describe "#read" do + shared_examples "read successfully with IO" do + it "yields with source" do trace.read do |stream| expect(stream).to be_a(Gitlab::Ci::Trace::Stream) expect(stream.stream).to be_a(IO) @@ -295,8 +295,8 @@ shared_examples_for 'trace with disabled live trace feature' do end end - shared_examples 'read successfully with StringIO' do - it 'yields with source' do + shared_examples "read successfully with StringIO" do + it "yields with source" do trace.read do |stream| expect(stream).to be_a(Gitlab::Ci::Trace::Stream) expect(stream.stream).to be_a(StringIO) @@ -304,8 +304,8 @@ shared_examples_for 'trace with disabled live trace feature' do end end - shared_examples 'failed to read' do - it 'yields without source' do + shared_examples "failed to read" do + it "yields without source" do trace.read do |stream| expect(stream).to be_a(Gitlab::Ci::Trace::Stream) expect(stream.stream).to be_nil @@ -313,71 +313,71 @@ shared_examples_for 'trace with disabled live trace feature' do end end - context 'when trace artifact exists' do + context "when trace artifact exists" do before do create(:ci_job_artifact, :trace, job: build) end - it_behaves_like 'read successfully with IO' + it_behaves_like "read successfully with IO" end - context 'when current_path (with project_id) exists' do + context "when current_path (with project_id) exists" do before do - expect(trace).to receive(:default_path) { expand_fixture_path('trace/sample_trace') } + expect(trace).to receive(:default_path) { expand_fixture_path("trace/sample_trace") } end - it_behaves_like 'read successfully with IO' + it_behaves_like "read successfully with IO" end - context 'when current_path (with project_ci_id) exists' do + context "when current_path (with project_ci_id) exists" do before do - expect(trace).to receive(:deprecated_path) { expand_fixture_path('trace/sample_trace') } + expect(trace).to receive(:deprecated_path) { expand_fixture_path("trace/sample_trace") } end - it_behaves_like 'read successfully with IO' + it_behaves_like "read successfully with IO" end - context 'when db trace exists' do + context "when db trace exists" do before do build.send(:write_attribute, :trace, "data") end - it_behaves_like 'read successfully with StringIO' + it_behaves_like "read successfully with StringIO" end - context 'when no sources exist' do - it_behaves_like 'failed to read' + context "when no sources exist" do + it_behaves_like "failed to read" end end - describe 'trace handling' do + describe "trace handling" do subject { trace.exist? } - context 'trace does not exist' do + context "trace does not exist" do it { expect(trace.exist?).to be(false) } end - context 'when trace artifact exists' do + context "when trace artifact exists" do before do create(:ci_job_artifact, :trace, job: build) end it { is_expected.to be_truthy } - context 'when the trace artifact has been erased' do + context "when the trace artifact has been erased" do before do trace.erase! end it { is_expected.to be_falsy } - it 'removes associations' do + it "removes associations" do expect(Ci::JobArtifact.exists?(job_id: build.id, file_type: :trace)).to be_falsy end end end - context 'new trace path is used' do + context "new trace path is used" do before do trace.send(:ensure_directory) @@ -396,10 +396,10 @@ shared_examples_for 'trace with disabled live trace feature' do end end - context 'deprecated path' do + context "deprecated path" do let(:path) { trace.send(:deprecated_path) } - context 'with valid ci_id' do + context "with valid ci_id" do before do build.project.update(ci_id: 1000) @@ -420,14 +420,14 @@ shared_examples_for 'trace with disabled live trace feature' do end end - context 'without valid ci_id' do + context "without valid ci_id" do it "does not return deprecated path" do expect(path).to be_nil end end end - context 'stored in database' do + context "stored in database" do before do build.send(:write_attribute, :trace, "data") end @@ -447,17 +447,17 @@ shared_examples_for 'trace with disabled live trace feature' do end end - describe '#archive!' do + describe "#archive!" do subject { trace.archive! } - shared_examples 'archive trace file' do + shared_examples "archive trace file" do it do expect { subject }.to change { Ci::JobArtifact.count }.by(1) build.reload expect(build.trace.exist?).to be_truthy expect(build.job_artifacts_trace.file.exists?).to be_truthy - expect(build.job_artifacts_trace.file.filename).to eq('job.log') + expect(build.job_artifacts_trace.file.filename).to eq("job.log") expect(File.exist?(src_path)).to be_falsy expect(src_checksum) .to eq(Digest::SHA256.file(build.job_artifacts_trace.file.path).hexdigest) @@ -465,7 +465,7 @@ shared_examples_for 'trace with disabled live trace feature' do end end - shared_examples 'source trace file stays intact' do |error:| + shared_examples "source trace file stays intact" do |error:| it do expect { subject }.to raise_error(error) @@ -476,14 +476,14 @@ shared_examples_for 'trace with disabled live trace feature' do end end - shared_examples 'archive trace in database' do + shared_examples "archive trace in database" do it do expect { subject }.to change { Ci::JobArtifact.count }.by(1) build.reload expect(build.trace.exist?).to be_truthy expect(build.job_artifacts_trace.file.exists?).to be_truthy - expect(build.job_artifacts_trace.file.filename).to eq('job.log') + expect(build.job_artifacts_trace.file.filename).to eq("job.log") expect(build.old_trace).to be_nil expect(src_checksum) .to eq(Digest::SHA256.file(build.job_artifacts_trace.file.path).hexdigest) @@ -491,7 +491,7 @@ shared_examples_for 'trace with disabled live trace feature' do end end - shared_examples 'source trace in database stays intact' do |error:| + shared_examples "source trace in database stays intact" do |error:| it do expect { subject }.to raise_error(error) @@ -502,63 +502,63 @@ shared_examples_for 'trace with disabled live trace feature' do end end - context 'when job does not have trace artifact' do - context 'when trace file stored in default path' do + context "when job does not have trace artifact" do + context "when trace file stored in default path" do let!(:build) { create(:ci_build, :success, :trace_live) } let!(:src_path) { trace.read { |s| s.path } } let!(:src_checksum) { Digest::SHA256.file(src_path).hexdigest } - it_behaves_like 'archive trace file' + it_behaves_like "archive trace file" - context 'when failed to create clone file' do + context "when failed to create clone file" do before do allow(IO).to receive(:copy_stream).and_return(0) end - it_behaves_like 'source trace file stays intact', error: Gitlab::Ci::Trace::ArchiveError + it_behaves_like "source trace file stays intact", error: Gitlab::Ci::Trace::ArchiveError end - context 'when failed to create job artifact record' do + context "when failed to create job artifact record" do before do allow_any_instance_of(Ci::JobArtifact).to receive(:save).and_return(false) allow_any_instance_of(Ci::JobArtifact).to receive_message_chain(:errors, :full_messages) .and_return(%w[Error Error]) end - it_behaves_like 'source trace file stays intact', error: ActiveRecord::RecordInvalid + it_behaves_like "source trace file stays intact", error: ActiveRecord::RecordInvalid end end - context 'when trace is stored in database' do + context "when trace is stored in database" do let(:build) { create(:ci_build, :success) } - let(:trace_content) { 'Sample trace' } + let(:trace_content) { "Sample trace" } let(:src_checksum) { Digest::SHA256.hexdigest(trace_content) } before do build.update_column(:trace, trace_content) end - it_behaves_like 'archive trace in database' + it_behaves_like "archive trace in database" - context 'when failed to create clone file' do + context "when failed to create clone file" do before do allow(IO).to receive(:copy_stream).and_return(0) end - it_behaves_like 'source trace in database stays intact', error: Gitlab::Ci::Trace::ArchiveError + it_behaves_like "source trace in database stays intact", error: Gitlab::Ci::Trace::ArchiveError end - context 'when failed to create job artifact record' do + context "when failed to create job artifact record" do before do allow_any_instance_of(Ci::JobArtifact).to receive(:save).and_return(false) allow_any_instance_of(Ci::JobArtifact).to receive_message_chain(:errors, :full_messages) .and_return(%w[Error Error]) end - it_behaves_like 'source trace in database stays intact', error: ActiveRecord::RecordInvalid + it_behaves_like "source trace in database stays intact", error: ActiveRecord::RecordInvalid end - context 'when there is a validation error on Ci::Build' do + context "when there is a validation error on Ci::Build" do before do allow_any_instance_of(Ci::Build).to receive(:save).and_return(false) allow_any_instance_of(Ci::Build).to receive_message_chain(:errors, :full_messages) @@ -571,49 +571,49 @@ shared_examples_for 'trace with disabled live trace feature' do build.save end - it 'old trace is not deleted' do + it "old trace is not deleted" do build.reload expect(build.trace.raw).to eq(trace_content) end end - it_behaves_like 'archive trace in database' + it_behaves_like "archive trace in database" end end end - context 'when job has trace artifact' do + context "when job has trace artifact" do before do create(:ci_job_artifact, :trace, job: build) end - it 'does not archive' do + it "does not archive" do expect_any_instance_of(described_class).not_to receive(:archive_stream!) expect { subject }.to raise_error(Gitlab::Ci::Trace::AlreadyArchivedError) expect(build.job_artifacts_trace.file.exists?).to be_truthy end end - context 'when job is not finished yet' do + context "when job is not finished yet" do let!(:build) { create(:ci_build, :running, :trace_live) } - it 'does not archive' do + it "does not archive" do expect_any_instance_of(described_class).not_to receive(:archive_stream!) - expect { subject }.to raise_error('Job is not finished yet') + expect { subject }.to raise_error("Job is not finished yet") expect(build.trace.exist?).to be_truthy end end end - describe '#erase!' do + describe "#erase!" do subject { trace.erase! } - context 'when it is a live trace' do - context 'when trace is stored in database' do + context "when it is a live trace" do + context "when trace is stored in database" do let(:build) { create(:ci_build) } before do - build.update_column(:trace, 'sample trace') + build.update_column(:trace, "sample trace") end it { expect(trace.raw).not_to be_nil } @@ -625,7 +625,7 @@ shared_examples_for 'trace with disabled live trace feature' do end end - context 'when trace is stored in file storage' do + context "when trace is stored in file storage" do let(:build) { create(:ci_build, :trace_live) } it { expect(trace.raw).not_to be_nil } @@ -638,7 +638,7 @@ shared_examples_for 'trace with disabled live trace feature' do end end - context 'when it is an archived trace' do + context "when it is an archived trace" do let(:build) { create(:ci_build, :trace_artifact) } it "has trace at first" do @@ -655,12 +655,12 @@ shared_examples_for 'trace with disabled live trace feature' do end end -shared_examples_for 'trace with enabled live trace feature' do - it_behaves_like 'common trace features' +shared_examples_for "trace with enabled live trace feature" do + it_behaves_like "common trace features" - describe '#read' do - shared_examples 'read successfully with IO' do - it 'yields with source' do + describe "#read" do + shared_examples "read successfully with IO" do + it "yields with source" do trace.read do |stream| expect(stream).to be_a(Gitlab::Ci::Trace::Stream) expect(stream.stream).to be_a(IO) @@ -668,8 +668,8 @@ shared_examples_for 'trace with enabled live trace feature' do end end - shared_examples 'read successfully with ChunkedIO' do - it 'yields with source' do + shared_examples "read successfully with ChunkedIO" do + it "yields with source" do trace.read do |stream| expect(stream).to be_a(Gitlab::Ci::Trace::Stream) expect(stream.stream).to be_a(Gitlab::Ci::Trace::ChunkedIO) @@ -677,8 +677,8 @@ shared_examples_for 'trace with enabled live trace feature' do end end - shared_examples 'failed to read' do - it 'yields without source' do + shared_examples "failed to read" do + it "yields without source" do trace.read do |stream| expect(stream).to be_a(Gitlab::Ci::Trace::Stream) expect(stream.stream).to be_nil @@ -686,60 +686,60 @@ shared_examples_for 'trace with enabled live trace feature' do end end - context 'when trace artifact exists' do + context "when trace artifact exists" do before do create(:ci_job_artifact, :trace, job: build) end - it_behaves_like 'read successfully with IO' + it_behaves_like "read successfully with IO" end - context 'when live trace exists' do + context "when live trace exists" do before do Gitlab::Ci::Trace::ChunkedIO.new(build) do |stream| - stream.write('abc') + stream.write("abc") end end - it_behaves_like 'read successfully with ChunkedIO' + it_behaves_like "read successfully with ChunkedIO" end - context 'when no sources exist' do - it_behaves_like 'failed to read' + context "when no sources exist" do + it_behaves_like "failed to read" end end - describe 'trace handling' do + describe "trace handling" do subject { trace.exist? } - context 'trace does not exist' do + context "trace does not exist" do it { expect(trace.exist?).to be(false) } end - context 'when trace artifact exists' do + context "when trace artifact exists" do before do create(:ci_job_artifact, :trace, job: build) end it { is_expected.to be_truthy } - context 'when the trace artifact has been erased' do + context "when the trace artifact has been erased" do before do trace.erase! end it { is_expected.to be_falsy } - it 'removes associations' do + it "removes associations" do expect(Ci::JobArtifact.exists?(job_id: build.id, file_type: :trace)).to be_falsy end end end - context 'stored in live trace' do + context "stored in live trace" do before do Gitlab::Ci::Trace::ChunkedIO.new(build) do |stream| - stream.write('abc') + stream.write("abc") end end @@ -759,17 +759,17 @@ shared_examples_for 'trace with enabled live trace feature' do end end - describe '#archive!' do + describe "#archive!" do subject { trace.archive! } - shared_examples 'archive trace file in ChunkedIO' do + shared_examples "archive trace file in ChunkedIO" do it do expect { subject }.to change { Ci::JobArtifact.count }.by(1) build.reload expect(build.trace.exist?).to be_truthy expect(build.job_artifacts_trace.file.exists?).to be_truthy - expect(build.job_artifacts_trace.file.filename).to eq('job.log') + expect(build.job_artifacts_trace.file.filename).to eq("job.log") expect(Ci::BuildTraceChunk.where(build: build)).not_to be_exist expect(src_checksum) .to eq(Digest::SHA256.file(build.job_artifacts_trace.file.path).hexdigest) @@ -777,7 +777,7 @@ shared_examples_for 'trace with enabled live trace feature' do end end - shared_examples 'source trace in ChunkedIO stays intact' do |error:| + shared_examples "source trace in ChunkedIO stays intact" do |error:| it do expect { subject }.to raise_error(error) @@ -790,61 +790,61 @@ shared_examples_for 'trace with enabled live trace feature' do end end - context 'when job does not have trace artifact' do - context 'when trace is stored in ChunkedIO' do + context "when job does not have trace artifact" do + context "when trace is stored in ChunkedIO" do let!(:build) { create(:ci_build, :success, :trace_live) } let!(:trace_raw) { build.trace.raw } let!(:src_checksum) { Digest::SHA256.hexdigest(trace_raw) } - it_behaves_like 'archive trace file in ChunkedIO' + it_behaves_like "archive trace file in ChunkedIO" - context 'when failed to create clone file' do + context "when failed to create clone file" do before do allow(IO).to receive(:copy_stream).and_return(0) end - it_behaves_like 'source trace in ChunkedIO stays intact', error: Gitlab::Ci::Trace::ArchiveError + it_behaves_like "source trace in ChunkedIO stays intact", error: Gitlab::Ci::Trace::ArchiveError end - context 'when failed to create job artifact record' do + context "when failed to create job artifact record" do before do allow_any_instance_of(Ci::JobArtifact).to receive(:save).and_return(false) allow_any_instance_of(Ci::JobArtifact).to receive_message_chain(:errors, :full_messages) .and_return(%w[Error Error]) end - it_behaves_like 'source trace in ChunkedIO stays intact', error: ActiveRecord::RecordInvalid + it_behaves_like "source trace in ChunkedIO stays intact", error: ActiveRecord::RecordInvalid end end end - context 'when job has trace artifact' do + context "when job has trace artifact" do before do create(:ci_job_artifact, :trace, job: build) end - it 'does not archive' do + it "does not archive" do expect_any_instance_of(described_class).not_to receive(:archive_stream!) expect { subject }.to raise_error(Gitlab::Ci::Trace::AlreadyArchivedError) expect(build.job_artifacts_trace.file.exists?).to be_truthy end end - context 'when job is not finished yet' do + context "when job is not finished yet" do let!(:build) { create(:ci_build, :running, :trace_live) } - it 'does not archive' do + it "does not archive" do expect_any_instance_of(described_class).not_to receive(:archive_stream!) - expect { subject }.to raise_error('Job is not finished yet') + expect { subject }.to raise_error("Job is not finished yet") expect(build.trace.exist?).to be_truthy end end end - describe '#erase!' do + describe "#erase!" do subject { trace.erase! } - context 'when it is a live trace' do + context "when it is a live trace" do let(:build) { create(:ci_build, :trace_live) } it { expect(trace.raw).not_to be_nil } @@ -856,7 +856,7 @@ shared_examples_for 'trace with enabled live trace feature' do end end - context 'when it is an archived trace' do + context "when it is an archived trace" do let(:build) { create(:ci_build, :trace_artifact) } it "has trace at first" do diff --git a/spec/support/shared_examples/common_system_notes_examples.rb b/spec/support/shared_examples/common_system_notes_examples.rb index da5a4f3e319..50c459bd2cd 100644 --- a/spec/support/shared_examples/common_system_notes_examples.rb +++ b/spec/support/shared_examples/common_system_notes_examples.rb @@ -1,4 +1,4 @@ -shared_examples 'system note creation' do |update_params, note_text| +shared_examples "system note creation" do |update_params, note_text| subject { described_class.new(project, user).execute(issuable, old_labels: []) } before do @@ -6,7 +6,7 @@ shared_examples 'system note creation' do |update_params, note_text| issuable.save end - it 'creates 1 system note with the correct content' do + it "creates 1 system note with the correct content" do expect { subject }.to change { Note.count }.from(0).to(1) note = Note.last @@ -15,13 +15,13 @@ shared_examples 'system note creation' do |update_params, note_text| end end -shared_examples 'WIP notes creation' do |wip_action| +shared_examples "WIP notes creation" do |wip_action| subject { described_class.new(project, user).execute(issuable, old_labels: []) } - it 'creates WIP toggle and title change notes' do + it "creates WIP toggle and title change notes" do expect { subject }.to change { Note.count }.from(0).to(2) expect(Note.first.note).to match("#{wip_action} as a **Work In Progress**") - expect(Note.second.note).to match('changed title') + expect(Note.second.note).to match("changed title") end end diff --git a/spec/support/shared_examples/controllers/issuable_notes_filter_shared_examples.rb b/spec/support/shared_examples/controllers/issuable_notes_filter_shared_examples.rb index 0acc9e2a836..9a2d90c5342 100644 --- a/spec/support/shared_examples/controllers/issuable_notes_filter_shared_examples.rb +++ b/spec/support/shared_examples/controllers/issuable_notes_filter_shared_examples.rb @@ -1,13 +1,13 @@ -shared_examples 'issuable notes filter' do +shared_examples "issuable notes filter" do let(:params) do if issuable_parent.is_a?(Project) - { namespace_id: issuable_parent.namespace, project_id: issuable_parent, id: issuable.iid } + {namespace_id: issuable_parent.namespace, project_id: issuable_parent, id: issuable.iid} else - { group_id: issuable_parent, id: issuable.to_param } + {group_id: issuable_parent, id: issuable.to_param} end end - it 'sets discussion filter' do + it "sets discussion filter" do notes_filter = UserPreference::NOTES_FILTERS[:only_comments] get :discussions, params: params.merge(notes_filter: notes_filter) @@ -16,7 +16,7 @@ shared_examples 'issuable notes filter' do expect(UserPreference.count).to eq(1) end - it 'expires notes e-tag cache for issuable if filter changed' do + it "expires notes e-tag cache for issuable if filter changed" do notes_filter = UserPreference::NOTES_FILTERS[:only_comments] expect_any_instance_of(issuable.class).to receive(:expire_note_etag_cache) @@ -24,7 +24,7 @@ shared_examples 'issuable notes filter' do get :discussions, params: params.merge(notes_filter: notes_filter) end - it 'does not expires notes e-tag cache for issuable if filter did not change' do + it "does not expires notes e-tag cache for issuable if filter did not change" do notes_filter = UserPreference::NOTES_FILTERS[:only_comments] user.set_notes_filter(notes_filter, issuable) @@ -33,7 +33,7 @@ shared_examples 'issuable notes filter' do get :discussions, params: params.merge(notes_filter: notes_filter) end - it 'does not set notes filter when database is in read only mode' do + it "does not set notes filter when database is in read only mode" do allow(Gitlab::Database).to receive(:read_only?).and_return(true) notes_filter = UserPreference::NOTES_FILTERS[:only_comments] @@ -42,7 +42,7 @@ shared_examples 'issuable notes filter' do expect(user.reload.notes_filter_for(issuable)).to eq(0) end - it 'returns only user comments' do + it "returns only user comments" do user.set_notes_filter(UserPreference::NOTES_FILTERS[:only_comments], issuable) get :discussions, params: params @@ -52,7 +52,7 @@ shared_examples 'issuable notes filter' do expect(discussions.first["notes"].first["system"]).to be(false) end - it 'returns only activity notes' do + it "returns only activity notes" do user.set_notes_filter(UserPreference::NOTES_FILTERS[:only_activity], issuable) get :discussions, params: params @@ -63,7 +63,7 @@ shared_examples 'issuable notes filter' do end context 'when filter is set to "only_comments"' do - it 'does not merge label event notes' do + it "does not merge label event notes" do user.set_notes_filter(UserPreference::NOTES_FILTERS[:only_comments], issuable) expect(ResourceEvents::MergeIntoNotesService).not_to receive(:new) diff --git a/spec/support/shared_examples/controllers/repository_lfs_file_load_examples.rb b/spec/support/shared_examples/controllers/repository_lfs_file_load_examples.rb index 982e0317f7f..6d26dec88c8 100644 --- a/spec/support/shared_examples/controllers/repository_lfs_file_load_examples.rb +++ b/spec/support/shared_examples/controllers/repository_lfs_file_load_examples.rb @@ -9,39 +9,40 @@ # - `filepath`: path of the file (contains filename) # - `subject`: the request to be made to the controller. Example: # subject { get :show, namespace_id: project.namespace, project_id: project } -shared_examples 'repository lfs file load' do - context 'when file is stored in lfs' do - let(:lfs_oid) { '91eff75a492a3ed0dfcb544d7f31326bc4014c8551849c192fd1e48d4dd2c897' } - let(:lfs_size) { '1575078' } +shared_examples "repository lfs file load" do + context "when file is stored in lfs" do + let(:lfs_oid) { "91eff75a492a3ed0dfcb544d7f31326bc4014c8551849c192fd1e48d4dd2c897" } + let(:lfs_size) { "1575078" } let!(:lfs_object) { create(:lfs_object, oid: lfs_oid, size: lfs_size) } - context 'when lfs is enabled' do + context "when lfs is enabled" do before do allow_any_instance_of(Project).to receive(:lfs_enabled?).and_return(true) end - context 'when project has access' do + context "when project has access" do before do project.lfs_objects << lfs_object allow_any_instance_of(LfsObjectUploader).to receive(:exists?).and_return(true) allow(controller).to receive(:send_file) { controller.head :ok } end - it 'serves the file' do + it "serves the file" do # Notice the filename= is omitted from the disposition; this is because # Rails 5 will append this header in send_file expect(controller).to receive(:send_file) - .with( - "#{LfsObjectUploader.root}/91/ef/f75a492a3ed0dfcb544d7f31326bc4014c8551849c192fd1e48d4dd2c897", - filename: filename, - disposition: %Q(attachment; filename*=UTF-8''#{filename})) + .with( + "#{LfsObjectUploader.root}/91/ef/f75a492a3ed0dfcb544d7f31326bc4014c8551849c192fd1e48d4dd2c897", + filename: filename, + disposition: %(attachment; filename*=UTF-8''#{filename}) + ) subject expect(response).to have_gitlab_http_status(200) end - context 'and lfs uses object storage' do + context "and lfs uses object storage" do let(:lfs_object) { create(:lfs_object, :with_file, oid: lfs_oid, size: lfs_size) } before do @@ -49,14 +50,14 @@ shared_examples 'repository lfs file load' do lfs_object.file.migrate!(LfsObjectUploader::Store::REMOTE) end - it 'responds with redirect to file' do + it "responds with redirect to file" do subject expect(response).to have_gitlab_http_status(302) expect(response.location).to include(lfs_object.reload.file.path) end - it 'sets content disposition' do + it "sets content disposition" do subject file_uri = URI.parse(response.location) @@ -67,8 +68,8 @@ shared_examples 'repository lfs file load' do end end - context 'when project does not have access' do - it 'does not serve the file' do + context "when project does not have access" do + it "does not serve the file" do subject expect(response).to have_gitlab_http_status(404) @@ -76,19 +77,19 @@ shared_examples 'repository lfs file load' do end end - context 'when lfs is not enabled' do + context "when lfs is not enabled" do before do allow_any_instance_of(Project).to receive(:lfs_enabled?).and_return(false) end - it 'delivers ASCII file' do + it "delivers ASCII file" do subject expect(response).to have_gitlab_http_status(200) - expect(response.header['Content-Type']).to eq('text/plain; charset=utf-8') - expect(response.header['Content-Disposition']) - .to eq('inline') - expect(response.header[Gitlab::Workhorse::SEND_DATA_HEADER]).to start_with('git-blob:') + expect(response.header["Content-Type"]).to eq("text/plain; charset=utf-8") + expect(response.header["Content-Disposition"]) + .to eq("inline") + expect(response.header[Gitlab::Workhorse::SEND_DATA_HEADER]).to start_with("git-blob:") end end end diff --git a/spec/support/shared_examples/controllers/set_sort_order_from_user_preference_shared_examples.rb b/spec/support/shared_examples/controllers/set_sort_order_from_user_preference_shared_examples.rb index 98ab04c5636..bdf6438f0c9 100644 --- a/spec/support/shared_examples/controllers/set_sort_order_from_user_preference_shared_examples.rb +++ b/spec/support/shared_examples/controllers/set_sort_order_from_user_preference_shared_examples.rb @@ -1,25 +1,25 @@ -shared_examples 'set sort order from user preference' do - describe '#set_sort_order_from_user_preference' do +shared_examples "set sort order from user preference" do + describe "#set_sort_order_from_user_preference" do # There is no issuable_sorting_field defined in any CE controllers yet, # however any other field present in user_preferences table can be used for testing. - context 'when database is in read-only mode' do - it 'it does not update user preference' do + context "when database is in read-only mode" do + it "it does not update user preference" do allow(Gitlab::Database).to receive(:read_only?).and_return(true) - expect_any_instance_of(UserPreference).not_to receive(:update).with({ controller.send(:issuable_sorting_field) => sorting_param }) + expect_any_instance_of(UserPreference).not_to receive(:update).with({controller.send(:issuable_sorting_field) => sorting_param}) - get :index, params: { namespace_id: project.namespace, project_id: project, sort: sorting_param } + get :index, params: {namespace_id: project.namespace, project_id: project, sort: sorting_param} end end - context 'when database is not in read-only mode' do - it 'updates user preference' do + context "when database is not in read-only mode" do + it "updates user preference" do allow(Gitlab::Database).to receive(:read_only?).and_return(false) - expect_any_instance_of(UserPreference).to receive(:update).with({ controller.send(:issuable_sorting_field) => sorting_param }) + expect_any_instance_of(UserPreference).to receive(:update).with({controller.send(:issuable_sorting_field) => sorting_param}) - get :index, params: { namespace_id: project.namespace, project_id: project, sort: sorting_param } + get :index, params: {namespace_id: project.namespace, project_id: project, sort: sorting_param} end end end diff --git a/spec/support/shared_examples/controllers/todos_shared_examples.rb b/spec/support/shared_examples/controllers/todos_shared_examples.rb index bafd9bac8d0..8c2e1e5128a 100644 --- a/spec/support/shared_examples/controllers/todos_shared_examples.rb +++ b/spec/support/shared_examples/controllers/todos_shared_examples.rb @@ -1,41 +1,41 @@ -shared_examples 'todos actions' do - context 'when authorized' do +shared_examples "todos actions" do + context "when authorized" do before do sign_in(user) parent.add_developer(user) end - it 'creates todo' do - expect do + it "creates todo" do + expect { post_create - end.to change { user.todos.count }.by(1) + }.to change { user.todos.count }.by(1) expect(response).to have_gitlab_http_status(200) end - it 'returns todo path and pending count' do + it "returns todo path and pending count" do post_create expect(response).to have_gitlab_http_status(200) - expect(json_response['count']).to eq 1 - expect(json_response['delete_path']).to match(%r{/dashboard/todos/\d{1}}) + expect(json_response["count"]).to eq 1 + expect(json_response["delete_path"]).to match(%r{/dashboard/todos/\d{1}}) end end - context 'when not authorized for project/group' do - it 'does not create todo for resource that user has no access to' do + context "when not authorized for project/group" do + it "does not create todo for resource that user has no access to" do sign_in(user) - expect do + expect { post_create - end.to change { user.todos.count }.by(0) + }.to change { user.todos.count }.by(0) expect(response).to have_gitlab_http_status(404) end - it 'does not create todo when user is not logged in' do - expect do + it "does not create todo when user is not logged in" do + expect { post_create - end.to change { user.todos.count }.by(0) + }.to change { user.todos.count }.by(0) expect(response).to have_gitlab_http_status(parent.is_a?(Group) ? 401 : 302) end diff --git a/spec/support/shared_examples/controllers/uploads_actions_shared_examples.rb b/spec/support/shared_examples/controllers/uploads_actions_shared_examples.rb index 59708173716..cc0bf9f9bae 100644 --- a/spec/support/shared_examples/controllers/uploads_actions_shared_examples.rb +++ b/spec/support/shared_examples/controllers/uploads_actions_shared_examples.rb @@ -1,19 +1,19 @@ -shared_examples 'handle uploads' do +shared_examples "handle uploads" do let(:user) { create(:user) } - let(:jpg) { fixture_file_upload('spec/fixtures/rails_sample.jpg', 'image/jpg') } - let(:txt) { fixture_file_upload('spec/fixtures/doc_sample.txt', 'text/plain') } + let(:jpg) { fixture_file_upload("spec/fixtures/rails_sample.jpg", "image/jpg") } + let(:txt) { fixture_file_upload("spec/fixtures/doc_sample.txt", "text/plain") } let(:secret) { FileUploader.generate_secret } let(:uploader_class) { FileUploader } describe "POST #create" do - context 'when a user is not authorized to upload a file' do - it 'returns 404 status' do + context "when a user is not authorized to upload a file" do + it "returns 404 status" do post :create, params: params.merge(file: jpg), format: :json expect(response.status).to eq(404) end end - context 'when a user can upload a file' do + context "when a user can upload a file" do before do sign_in(user) model.add_developer(user) @@ -27,12 +27,12 @@ shared_examples 'handle uploads' do end end - context 'with valid image' do + context "with valid image" do before do post :create, params: params.merge(file: jpg), format: :json end - it 'returns a content with original filename, new link, and correct type.' do + it "returns a content with original filename, new link, and correct type." do expect(response.body).to match '\"alt\":\"rails_sample\"' expect(response.body).to match "\"url\":\"/uploads" end @@ -41,7 +41,7 @@ shared_examples 'handle uploads' do # behavior. We're avoiding a proper Feature test because those should be # testing things entirely user-facing, which the Upload model is very much # not. - it 'creates a corresponding Upload record' do + it "creates a corresponding Upload record" do upload = Upload.last aggregate_failures do @@ -51,12 +51,12 @@ shared_examples 'handle uploads' do end end - context 'with valid non-image file' do + context "with valid non-image file" do before do post :create, params: params.merge(file: txt), format: :json end - it 'returns a content with original filename, new link, and correct type.' do + it "returns a content with original filename, new link, and correct type." do expect(response.body).to match '\"alt\":\"doc_sample.txt\"' expect(response.body).to match "\"url\":\"/uploads" end @@ -261,78 +261,78 @@ shared_examples 'handle uploads' do end describe "POST #authorize" do - context 'when a user is not authorized to upload a file' do - it 'returns 404 status' do + context "when a user is not authorized to upload a file" do + it "returns 404 status" do post_authorize expect(response.status).to eq(404) end end - context 'when a user can upload a file' do + context "when a user can upload a file" do before do sign_in(user) model.add_developer(user) end - context 'and the request bypassed workhorse' do - it 'raises an exception' do + context "and the request bypassed workhorse" do + it "raises an exception" do expect { post_authorize(verified: false) }.to raise_error JWT::DecodeError end end - context 'and request is sent by gitlab-workhorse to authorize the request' do - shared_examples 'a valid response' do + context "and request is sent by gitlab-workhorse to authorize the request" do + shared_examples "a valid response" do before do post_authorize end - it 'responds with status 200' do + it "responds with status 200" do expect(response).to have_gitlab_http_status(200) end - it 'uses the gitlab-workhorse content type' do + it "uses the gitlab-workhorse content type" do expect(response.headers["Content-Type"]).to eq(Gitlab::Workhorse::INTERNAL_API_CONTENT_TYPE) end end - shared_examples 'a local file' do - it_behaves_like 'a valid response' do - it 'responds with status 200, location of uploads store and object details' do - expect(json_response['TempPath']).to eq(uploader_class.workhorse_local_upload_path) - expect(json_response['RemoteObject']).to be_nil + shared_examples "a local file" do + it_behaves_like "a valid response" do + it "responds with status 200, location of uploads store and object details" do + expect(json_response["TempPath"]).to eq(uploader_class.workhorse_local_upload_path) + expect(json_response["RemoteObject"]).to be_nil end end end - context 'when using local storage' do - it_behaves_like 'a local file' + context "when using local storage" do + it_behaves_like "a local file" end - context 'when using remote storage' do - context 'when direct upload is enabled' do + context "when using remote storage" do + context "when direct upload is enabled" do before do stub_uploads_object_storage(uploader_class, direct_upload: true) end - it_behaves_like 'a valid response' do - it 'responds with status 200, location of uploads remote store and object details' do - expect(json_response['TempPath']).to eq(uploader_class.workhorse_local_upload_path) - expect(json_response['RemoteObject']).to have_key('ID') - expect(json_response['RemoteObject']).to have_key('GetURL') - expect(json_response['RemoteObject']).to have_key('StoreURL') - expect(json_response['RemoteObject']).to have_key('DeleteURL') - expect(json_response['RemoteObject']).to have_key('MultipartUpload') + it_behaves_like "a valid response" do + it "responds with status 200, location of uploads remote store and object details" do + expect(json_response["TempPath"]).to eq(uploader_class.workhorse_local_upload_path) + expect(json_response["RemoteObject"]).to have_key("ID") + expect(json_response["RemoteObject"]).to have_key("GetURL") + expect(json_response["RemoteObject"]).to have_key("StoreURL") + expect(json_response["RemoteObject"]).to have_key("DeleteURL") + expect(json_response["RemoteObject"]).to have_key("MultipartUpload") end end end - context 'when direct upload is disabled' do + context "when direct upload is disabled" do before do stub_uploads_object_storage(uploader_class, direct_upload: false) end - it_behaves_like 'a local file' + it_behaves_like "a local file" end end end diff --git a/spec/support/shared_examples/controllers/variables_shared_examples.rb b/spec/support/shared_examples/controllers/variables_shared_examples.rb index b615a8f54cf..4b1326879c4 100644 --- a/spec/support/shared_examples/controllers/variables_shared_examples.rb +++ b/spec/support/shared_examples/controllers/variables_shared_examples.rb @@ -1,123 +1,123 @@ -shared_examples 'GET #show lists all variables' do - it 'renders the variables as json' do +shared_examples "GET #show lists all variables" do + it "renders the variables as json" do subject - expect(response).to match_response_schema('variables') + expect(response).to match_response_schema("variables") end - it 'has only one variable' do + it "has only one variable" do subject - expect(json_response['variables'].count).to eq(1) + expect(json_response["variables"].count).to eq(1) end end -shared_examples 'PATCH #update updates variables' do +shared_examples "PATCH #update updates variables" do let(:variable_attributes) do - { id: variable.id, - key: variable.key, - secret_value: variable.value, - protected: variable.protected?.to_s } + {id: variable.id, + key: variable.key, + secret_value: variable.value, + protected: variable.protected?.to_s,} end let(:new_variable_attributes) do - { key: 'new_key', - secret_value: 'dummy_value', - protected: 'false' } + {key: "new_key", + secret_value: "dummy_value", + protected: "false",} end - context 'with invalid new variable parameters' do + context "with invalid new variable parameters" do let(:variables_attributes) do [ - variable_attributes.merge(secret_value: 'other_value'), - new_variable_attributes.merge(key: '...?') + variable_attributes.merge(secret_value: "other_value"), + new_variable_attributes.merge(key: "...?"), ] end - it 'does not update the existing variable' do + it "does not update the existing variable" do expect { subject }.not_to change { variable.reload.value } end - it 'does not create the new variable' do + it "does not create the new variable" do expect { subject }.not_to change { owner.variables.count } end - it 'returns a bad request response' do + it "returns a bad request response" do subject expect(response).to have_gitlab_http_status(:bad_request) end end - context 'with duplicate new variable parameters' do + context "with duplicate new variable parameters" do let(:variables_attributes) do [ new_variable_attributes, - new_variable_attributes.merge(secret_value: 'other_value') + new_variable_attributes.merge(secret_value: "other_value"), ] end - it 'does not update the existing variable' do + it "does not update the existing variable" do expect { subject }.not_to change { variable.reload.value } end - it 'does not create the new variable' do + it "does not create the new variable" do expect { subject }.not_to change { owner.variables.count } end - it 'returns a bad request response' do + it "returns a bad request response" do subject expect(response).to have_gitlab_http_status(:bad_request) end end - context 'with valid new variable parameters' do + context "with valid new variable parameters" do let(:variables_attributes) do [ - variable_attributes.merge(secret_value: 'other_value'), - new_variable_attributes + variable_attributes.merge(secret_value: "other_value"), + new_variable_attributes, ] end - it 'updates the existing variable' do - expect { subject }.to change { variable.reload.value }.to('other_value') + it "updates the existing variable" do + expect { subject }.to change { variable.reload.value }.to("other_value") end - it 'creates the new variable' do + it "creates the new variable" do expect { subject }.to change { owner.variables.count }.by(1) end - it 'returns a successful response' do + it "returns a successful response" do subject expect(response).to have_gitlab_http_status(:ok) end - it 'has all variables in response' do + it "has all variables in response" do subject - expect(response).to match_response_schema('variables') + expect(response).to match_response_schema("variables") end end - context 'with a deleted variable' do - let(:variables_attributes) { [variable_attributes.merge(_destroy: 'true')] } + context "with a deleted variable" do + let(:variables_attributes) { [variable_attributes.merge(_destroy: "true")] } - it 'destroys the variable' do + it "destroys the variable" do expect { subject }.to change { owner.variables.count }.by(-1) expect { variable.reload }.to raise_error ActiveRecord::RecordNotFound end - it 'returns a successful response' do + it "returns a successful response" do subject expect(response).to have_gitlab_http_status(:ok) end - it 'has all variables in response' do + it "has all variables in response" do subject - expect(response).to match_response_schema('variables') + expect(response).to match_response_schema("variables") end end end diff --git a/spec/support/shared_examples/diff_file_collections.rb b/spec/support/shared_examples/diff_file_collections.rb index 367ddf06c28..f8c4beae5a0 100644 --- a/spec/support/shared_examples/diff_file_collections.rb +++ b/spec/support/shared_examples/diff_file_collections.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -shared_examples 'diff statistics' do |test_include_stats_flag: true| +shared_examples "diff statistics" do |test_include_stats_flag: true| def stub_stats_find_by_path(path, stats_mock) expect_next_instance_of(Gitlab::Git::DiffStatsCollection) do |collection| allow(collection).to receive(:find_by_path).and_call_original @@ -8,8 +8,8 @@ shared_examples 'diff statistics' do |test_include_stats_flag: true| end end - context 'when should request diff stats' do - it 'Repository#diff_stats is called' do + context "when should request diff stats" do + it "Repository#diff_stats is called" do subject = described_class.new(diffable, collection_default_args) expect(diffable.project.repository) @@ -20,10 +20,10 @@ shared_examples 'diff statistics' do |test_include_stats_flag: true| subject.diff_files end - it 'Gitlab::Diff::File is initialized with diff stats' do + it "Gitlab::Diff::File is initialized with diff stats" do subject = described_class.new(diffable, collection_default_args) - stats_mock = double(Gitaly::DiffStats, path: '.gitignore', additions: 758, deletions: 120) + stats_mock = double(Gitaly::DiffStats, path: ".gitignore", additions: 758, deletions: 120) stub_stats_find_by_path(stub_path, stats_mock) diff_file = subject.diff_files.find { |file| file.new_path == stub_path } @@ -33,8 +33,8 @@ shared_examples 'diff statistics' do |test_include_stats_flag: true| end end - context 'when should not request diff stats' do - it 'Repository#diff_stats is not called' do + context "when should not request diff stats" do + it "Repository#diff_stats is not called" do collection_default_args[:diff_options][:include_stats] = false subject = described_class.new(diffable, collection_default_args) @@ -46,13 +46,13 @@ shared_examples 'diff statistics' do |test_include_stats_flag: true| end end -shared_examples 'unfoldable diff' do +shared_examples "unfoldable diff" do let(:subject) { described_class.new(diffable, diff_options: nil) } - it 'calls Gitlab::Diff::File#unfold_diff_lines with correct position' do - position = instance_double(Gitlab::Diff::Position, file_path: 'README') - readme_file = instance_double(Gitlab::Diff::File, file_path: 'README') - other_file = instance_double(Gitlab::Diff::File, file_path: 'foo.rb') + it "calls Gitlab::Diff::File#unfold_diff_lines with correct position" do + position = instance_double(Gitlab::Diff::Position, file_path: "README") + readme_file = instance_double(Gitlab::Diff::File, file_path: "README") + other_file = instance_double(Gitlab::Diff::File, file_path: "foo.rb") nil_path_file = instance_double(Gitlab::Diff::File, file_path: nil) allow(subject).to receive(:diff_files) { [readme_file, other_file, nil_path_file] } diff --git a/spec/support/shared_examples/dirty_submit_form_shared_examples.rb b/spec/support/shared_examples/dirty_submit_form_shared_examples.rb index 52a2ee49495..031a8224ed4 100644 --- a/spec/support/shared_examples/dirty_submit_form_shared_examples.rb +++ b/spec/support/shared_examples/dirty_submit_form_shared_examples.rb @@ -1,8 +1,8 @@ -shared_examples 'dirty submit form' do |selector_args| +shared_examples "dirty submit form" do |selector_args| selectors = selector_args.is_a?(Array) ? selector_args : [selector_args] def expect_disabled_state(form, submit, is_disabled = true) - disabled_selector = is_disabled == true ? '[disabled]' : ':not([disabled])' + disabled_selector = is_disabled == true ? "[disabled]" : ":not([disabled])" form.find(".js-dirty-submit#{disabled_selector}", match: :first) @@ -12,10 +12,10 @@ shared_examples 'dirty submit form' do |selector_args| selectors.each do |selector| it "disables #{selector[:form]} submit until there are changes on #{selector[:input]}", :js do form = find(selector[:form]) - submit = form.first('.js-dirty-submit') + submit = form.first(".js-dirty-submit") input = form.first(selector[:input]) - is_radio = input[:type] == 'radio' - is_checkbox = input[:type] == 'checkbox' + is_radio = input[:type] == "radio" + is_checkbox = input[:type] == "checkbox" is_checkable = is_radio || is_checkbox original_value = input.value original_checkable = form.find("input[name='#{input[:name]}'][checked]") if is_radio diff --git a/spec/support/shared_examples/email_format_shared_examples.rb b/spec/support/shared_examples/email_format_shared_examples.rb index b924a208e71..01f05fa6fd0 100644 --- a/spec/support/shared_examples/email_format_shared_examples.rb +++ b/spec/support/shared_examples/email_format_shared_examples.rb @@ -4,7 +4,7 @@ # Note: You have access to `email_value` which is the email address value # being currently tested). -shared_examples 'an object with email-formated attributes' do |*attributes| +shared_examples "an object with email-formated attributes" do |*attributes| attributes.each do |attribute| describe "specifically its :#{attribute} attribute" do %w[ @@ -17,7 +17,7 @@ shared_examples 'an object with email-formated attributes' do |*attributes| context "with a value of '#{valid_email}'" do let(:email_value) { valid_email } - it 'is valid' do + it "is valid" do subject.send("#{attribute}=", valid_email) expect(subject).to be_valid @@ -32,7 +32,7 @@ shared_examples 'an object with email-formated attributes' do |*attributes| context "with a value of '#{invalid_email}'" do let(:email_value) { invalid_email } - it 'is invalid' do + it "is invalid" do subject.send("#{attribute}=", invalid_email) expect(subject).to be_invalid diff --git a/spec/support/shared_examples/fast_destroy_all.rb b/spec/support/shared_examples/fast_destroy_all.rb index a8079b6d864..1c6ce901f2a 100644 --- a/spec/support/shared_examples/fast_destroy_all.rb +++ b/spec/support/shared_examples/fast_destroy_all.rb @@ -1,19 +1,19 @@ -shared_examples_for 'fast destroyable' do - describe 'Forbid #destroy and #destroy_all' do - it 'does not delete database rows and associted external data' do +shared_examples_for "fast destroyable" do + describe "Forbid #destroy and #destroy_all" do + it "does not delete database rows and associted external data" do expect(external_data_counter).to be > 0 expect(subjects.count).to be > 0 - expect { subjects.first.destroy }.to raise_error('`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`') - expect { subjects.destroy_all }.to raise_error('`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`') # rubocop: disable DestroyAll + expect { subjects.first.destroy }.to raise_error("`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`") + expect { subjects.destroy_all }.to raise_error("`destroy` and `destroy_all` are forbidden. Please use `fast_destroy_all`") # rubocop: disable DestroyAll expect(subjects.count).to be > 0 expect(external_data_counter).to be > 0 end end - describe '.fast_destroy_all' do - it 'deletes database rows and associted external data' do + describe ".fast_destroy_all" do + it "deletes database rows and associted external data" do expect(external_data_counter).to be > 0 expect(subjects.count).to be > 0 @@ -24,8 +24,8 @@ shared_examples_for 'fast destroyable' do end end - describe '.use_fast_destroy' do - it 'performs cascading delete with fast_destroy_all' do + describe ".use_fast_destroy" do + it "performs cascading delete with fast_destroy_all" do expect(external_data_counter).to be > 0 expect(subjects.count).to be > 0 diff --git a/spec/support/shared_examples/features/comments_on_merge_request_files_shared_examples.rb b/spec/support/shared_examples/features/comments_on_merge_request_files_shared_examples.rb index 221926aaf7e..b5a7428b63a 100644 --- a/spec/support/shared_examples/features/comments_on_merge_request_files_shared_examples.rb +++ b/spec/support/shared_examples/features/comments_on_merge_request_files_shared_examples.rb @@ -1,28 +1,28 @@ -shared_examples 'comment on merge request file' do - it 'adds a comment' do +shared_examples "comment on merge request file" do + it "adds a comment" do click_diff_line(find("[id='#{sample_commit.line_code}']")) - page.within('.js-discussion-note-form') do - fill_in(:note_note, with: 'Line is wrong') - click_button('Comment') + page.within(".js-discussion-note-form") do + fill_in(:note_note, with: "Line is wrong") + click_button("Comment") end wait_for_requests - page.within('.notes_holder') do - expect(page).to have_content('Line is wrong') + page.within(".notes_holder") do + expect(page).to have_content("Line is wrong") end visit(merge_request_path(merge_request)) - page.within('.notes .discussion') do + page.within(".notes .discussion") do expect(page).to have_content("#{user.name} #{user.to_reference} started a discussion") expect(page).to have_content(sample_commit.line_code_path) - expect(page).to have_content('Line is wrong') + expect(page).to have_content("Line is wrong") end - page.within('.notes-tab .badge') do - expect(page).to have_content('1') + page.within(".notes-tab .badge") do + expect(page).to have_content("1") end end end diff --git a/spec/support/shared_examples/features/creatable_merge_request_shared_examples.rb b/spec/support/shared_examples/features/creatable_merge_request_shared_examples.rb index 7038a366144..cf779a923fd 100644 --- a/spec/support/shared_examples/features/creatable_merge_request_shared_examples.rb +++ b/spec/support/shared_examples/features/creatable_merge_request_shared_examples.rb @@ -1,4 +1,4 @@ -RSpec.shared_examples 'a creatable merge request' do +RSpec.shared_examples "a creatable merge request" do include WaitForRequests let(:user) { create(:user) } @@ -20,80 +20,81 @@ RSpec.shared_examples 'a creatable merge request' do merge_request: { source_project_id: source_project.id, target_project_id: target_project.id, - source_branch: 'fix', - target_branch: 'master' - }) + source_branch: "fix", + target_branch: "master", + } + ) end - it 'creates new merge request', :js do - click_button 'Assignee' - page.within '.dropdown-menu-user' do + it "creates new merge request", :js do + click_button "Assignee" + page.within ".dropdown-menu-user" do click_link user2.name end expect(find('input[name="merge_request[assignee_id]"]', visible: false).value).to match(user2.id.to_s) - page.within '.js-assignee-search' do + page.within ".js-assignee-search" do expect(page).to have_content user2.name end - click_link 'Assign to me' + click_link "Assign to me" expect(find('input[name="merge_request[assignee_id]"]', visible: false).value).to match(user.id.to_s) - page.within '.js-assignee-search' do + page.within ".js-assignee-search" do expect(page).to have_content user.name end - click_button 'Milestone' - page.within '.issue-milestone' do + click_button "Milestone" + page.within ".issue-milestone" do click_link milestone.title end expect(find('input[name="merge_request[milestone_id]"]', visible: false).value).to match(milestone.id.to_s) - page.within '.js-milestone-select' do + page.within ".js-milestone-select" do expect(page).to have_content milestone.title end - click_button 'Labels' - page.within '.dropdown-menu-labels' do + click_button "Labels" + page.within ".dropdown-menu-labels" do click_link label.title click_link label2.title end - page.within '.js-label-select' do + page.within ".js-label-select" do expect(page).to have_content label.title end expect(page.all('input[name="merge_request[label_ids][]"]', visible: false)[1].value).to match(label.id.to_s) expect(page.all('input[name="merge_request[label_ids][]"]', visible: false)[2].value).to match(label2.id.to_s) - click_button 'Submit merge request' + click_button "Submit merge request" - page.within '.issuable-sidebar' do - page.within '.assignee' do + page.within ".issuable-sidebar" do + page.within ".assignee" do expect(page).to have_content user.name end - page.within '.milestone' do + page.within ".milestone" do expect(page).to have_content milestone.title end - page.within '.labels' do + page.within ".labels" do expect(page).to have_content label.title expect(page).to have_content label2.title end end end - it 'updates the branches when selecting a new target project', :js do + it "updates the branches when selecting a new target project", :js do target_project_member = target_project.owner CreateBranchService.new(target_project, target_project_member) - .execute('a-brand-new-branch-to-test', 'master') + .execute("a-brand-new-branch-to-test", "master") visit project_new_merge_request_path(source_project) - first('.js-target-project').click - find('.dropdown-target-project .dropdown-content a', text: target_project.full_path).click + first(".js-target-project").click + find(".dropdown-target-project .dropdown-content a", text: target_project.full_path).click wait_for_requests - first('.js-target-branch').click + first(".js-target-branch").click - within('.js-target-branch-dropdown .dropdown-content') do - expect(page).to have_content('a-brand-new-branch-to-test') + within(".js-target-branch-dropdown .dropdown-content") do + expect(page).to have_content("a-brand-new-branch-to-test") end end end diff --git a/spec/support/shared_examples/features/editable_merge_request_shared_examples.rb b/spec/support/shared_examples/features/editable_merge_request_shared_examples.rb index eef0327c9a6..080c9aea908 100644 --- a/spec/support/shared_examples/features/editable_merge_request_shared_examples.rb +++ b/spec/support/shared_examples/features/editable_merge_request_shared_examples.rb @@ -1,4 +1,4 @@ -RSpec.shared_examples 'an editable merge request' do +RSpec.shared_examples "an editable merge request" do let(:user) { create(:user) } let(:user2) { create(:user) } let!(:milestone) { create(:milestone, project: target_project) } @@ -10,8 +10,8 @@ RSpec.shared_examples 'an editable merge request' do create(:merge_request, source_project: source_project, target_project: target_project, - source_branch: 'fix', - target_branch: 'master') + source_branch: "fix", + target_branch: "master") end before do @@ -23,82 +23,82 @@ RSpec.shared_examples 'an editable merge request' do visit edit_project_merge_request_path(target_project, merge_request) end - it 'updates merge request', :js do - click_button 'Assignee' - page.within '.dropdown-menu-user' do + it "updates merge request", :js do + click_button "Assignee" + page.within ".dropdown-menu-user" do click_link user.name end expect(find('input[name="merge_request[assignee_id]"]', visible: false).value).to match(user.id.to_s) - page.within '.js-assignee-search' do + page.within ".js-assignee-search" do expect(page).to have_content user.name end - click_button 'Milestone' - page.within '.issue-milestone' do + click_button "Milestone" + page.within ".issue-milestone" do click_link milestone.title end expect(find('input[name="merge_request[milestone_id]"]', visible: false).value).to match(milestone.id.to_s) - page.within '.js-milestone-select' do + page.within ".js-milestone-select" do expect(page).to have_content milestone.title end - click_button 'Labels' - page.within '.dropdown-menu-labels' do + click_button "Labels" + page.within ".dropdown-menu-labels" do click_link label.title click_link label2.title end expect(page.all('input[name="merge_request[label_ids][]"]', visible: false)[1].value).to match(label.id.to_s) expect(page.all('input[name="merge_request[label_ids][]"]', visible: false)[2].value).to match(label2.id.to_s) - page.within '.js-label-select' do + page.within ".js-label-select" do expect(page).to have_content label.title end - click_button 'Save changes' + click_button "Save changes" - page.within '.issuable-sidebar' do - page.within '.assignee' do + page.within ".issuable-sidebar" do + page.within ".assignee" do expect(page).to have_content user.name end - page.within '.milestone' do + page.within ".milestone" do expect(page).to have_content milestone.title end - page.within '.labels' do + page.within ".labels" do expect(page).to have_content label.title expect(page).to have_content label2.title end end end - it 'description has autocomplete', :js do - find('#merge_request_description').native.send_keys('') - fill_in 'merge_request_description', with: user.to_reference[0..4] + it "description has autocomplete", :js do + find("#merge_request_description").native.send_keys("") + fill_in "merge_request_description", with: user.to_reference[0..4] wait_for_requests - page.within('.atwho-view') do + page.within(".atwho-view") do expect(page).to have_content(user2.name) end end - it 'has class js-quick-submit in form' do - expect(page).to have_selector('.js-quick-submit') + it "has class js-quick-submit in form" do + expect(page).to have_selector(".js-quick-submit") end - it 'warns about version conflict' do + it "warns about version conflict" do merge_request.update(title: "New title") - fill_in 'merge_request_title', with: 'bug 345' - fill_in 'merge_request_description', with: 'bug description' + fill_in "merge_request_title", with: "bug 345" + fill_in "merge_request_description", with: "bug description" - click_button 'Save changes' + click_button "Save changes" - expect(page).to have_content 'Someone edited the merge request the same time you did' + expect(page).to have_content "Someone edited the merge request the same time you did" end - it 'preserves description textarea height', :js do - long_description = %q( + it "preserves description textarea height", :js do + long_description = ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac ornare ligula, ut tempus arcu. Etiam ultricies accumsan dolor vitae faucibus. Donec at elit lacus. Mauris orci ante, aliquam quis lorem eget, convallis faucibus arcu. Aenean at pulvinar lacus. Ut viverra quam massa, molestie ornare tortor dignissim a. Suspendisse tristique pellentesque tellus, id lacinia metus elementum id. Nam tristique, arcu rhoncus faucibus viverra, lacus ipsum sagittis ligula, vitae convallis odio lacus a nibh. Ut tincidunt est purus, ac vestibulum augue maximus in. Suspendisse vel erat et mi ultricies semper. Pellentesque volutpat pellentesque consequat. Cras congue nec ligula tristique viverra. Curabitur fringilla fringilla fringilla. Donec rhoncus dignissim orci ut accumsan. Ut rutrum urna a rhoncus varius. Maecenas blandit, mauris nec accumsan gravida, augue nibh finibus magna, sed maximus turpis libero nec neque. Suspendisse at semper est. Nunc imperdiet dapibus dui, varius sollicitudin erat luctus non. Sed pellentesque ligula eget posuere facilisis. Donec dictum commodo volutpat. Donec egestas dui ac magna sollicitudin bibendum. Vivamus purus neque, ullamcorper ac feugiat et, tempus sit amet metus. Praesent quis viverra neque. Sed bibendum viverra est, eu aliquam mi ornare vitae. Proin et dapibus ipsum. Nunc tortor diam, malesuada nec interdum vel, placerat quis justo. Ut viverra at erat eu laoreet. @@ -108,13 +108,13 @@ RSpec.shared_examples 'an editable merge request' do Nam tempor et magna sed convallis. Fusce sit amet sollicitudin risus, a ullamcorper lacus. Morbi gravida quis sem eget porttitor. Donec eu egestas mauris, in elementum tortor. Sed eget ex mi. Mauris iaculis tortor ut est auctor, nec dignissim quam sagittis. Suspendisse vel metus non quam suscipit tincidunt. Cras molestie lacus non justo finibus sodales quis vitae erat. In a porttitor nisi, id sollicitudin urna. Ut at felis tellus. Suspendisse potenti. Maecenas leo ligula, varius at neque vitae, ornare maximus justo. Nullam convallis luctus risus et vulputate. Duis suscipit faucibus iaculis. Etiam quis tortor faucibus, tristique tellus sit amet, sodales neque. Nulla dapibus nisi vel aliquet consequat. Etiam faucibus, metus eget condimentum iaculis, enim urna lobortis sem, id efficitur eros sapien nec nisi. Aenean ut finibus ex. - ) + ' - fill_in 'merge_request_description', with: long_description + fill_in "merge_request_description", with: long_description height = get_textarea_height - find('.js-md-preview-button').click - find('.js-md-write-button').click + find(".js-md-preview-button").click + find(".js-md-write-button").click new_height = get_textarea_height expect(height).to eq(new_height) @@ -122,19 +122,19 @@ RSpec.shared_examples 'an editable merge request' do context 'when "Remove source branch" is set' do before do - merge_request.update!(merge_params: { 'force_remove_source_branch' => '1' }) + merge_request.update!(merge_params: {"force_remove_source_branch" => "1"}) end it 'allows to unselect "Remove source branch"', :js do - expect(merge_request.merge_params['force_remove_source_branch']).to be_truthy + expect(merge_request.merge_params["force_remove_source_branch"]).to be_truthy visit edit_project_merge_request_path(target_project, merge_request) - uncheck 'Delete source branch when merge request is accepted' + uncheck "Delete source branch when merge request is accepted" - click_button 'Save changes' + click_button "Save changes" - expect(page).to have_unchecked_field 'remove-source-branch-input' - expect(page).to have_content 'Delete source branch' + expect(page).to have_unchecked_field "remove-source-branch-input" + expect(page).to have_content "Delete source branch" end end end diff --git a/spec/support/shared_examples/features/issuable_sidebar_shared_examples.rb b/spec/support/shared_examples/features/issuable_sidebar_shared_examples.rb index 96c821b26f7..80eaacdfbc5 100644 --- a/spec/support/shared_examples/features/issuable_sidebar_shared_examples.rb +++ b/spec/support/shared_examples/features/issuable_sidebar_shared_examples.rb @@ -1,9 +1,9 @@ -shared_examples 'issue sidebar stays collapsed on mobile' do +shared_examples "issue sidebar stays collapsed on mobile" do before do resize_screen_xs end - it 'keeps the sidebar collapsed' do - expect(page).not_to have_css('.right-sidebar.right-sidebar-collapsed') + it "keeps the sidebar collapsed" do + expect(page).not_to have_css(".right-sidebar.right-sidebar-collapsed") end end diff --git a/spec/support/shared_examples/features/issuables_user_dropdown_behaviors_shared_examples.rb b/spec/support/shared_examples/features/issuables_user_dropdown_behaviors_shared_examples.rb index c92c7f603d6..8ee09c4940a 100644 --- a/spec/support/shared_examples/features/issuables_user_dropdown_behaviors_shared_examples.rb +++ b/spec/support/shared_examples/features/issuables_user_dropdown_behaviors_shared_examples.rb @@ -1,4 +1,4 @@ -shared_examples 'issuable user dropdown behaviors' do +shared_examples "issuable user dropdown behaviors" do include FilteredSearchHelpers before do @@ -8,7 +8,7 @@ shared_examples 'issuable user dropdown behaviors' do %w[author assignee].each do |dropdown| describe "#{dropdown} dropdown", :js do - it 'only includes members of the project/group' do + it "only includes members of the project/group" do visit issuables_path filtered_search.set("#{dropdown}:") diff --git a/spec/support/shared_examples/features/master_manages_access_requests_shared_example.rb b/spec/support/shared_examples/features/master_manages_access_requests_shared_example.rb index 75ad948e42c..792ef7ad341 100644 --- a/spec/support/shared_examples/features/master_manages_access_requests_shared_example.rb +++ b/spec/support/shared_examples/features/master_manages_access_requests_shared_example.rb @@ -1,4 +1,4 @@ -RSpec.shared_examples 'Maintainer manages access requests' do +RSpec.shared_examples "Maintainer manages access requests" do let(:user) { create(:user) } let(:maintainer) { create(:user) } @@ -8,32 +8,32 @@ RSpec.shared_examples 'Maintainer manages access requests' do sign_in(maintainer) end - it 'maintainer can see access requests' do + it "maintainer can see access requests" do visit members_page_path expect_visible_access_request(entity, user) end - it 'maintainer can grant access', :js do + it "maintainer can grant access", :js do visit members_page_path expect_visible_access_request(entity, user) - accept_confirm { click_on 'Grant access' } + accept_confirm { click_on "Grant access" } expect_no_visible_access_request(entity, user) - page.within('.members-list') do + page.within(".members-list") do expect(page).to have_content user.name end end - it 'maintainer can deny access', :js do + it "maintainer can deny access", :js do visit members_page_path expect_visible_access_request(entity, user) - accept_confirm { click_on 'Deny access' } + accept_confirm { click_on "Deny access" } expect_no_visible_access_request(entity, user) expect(page).not_to have_content user.name diff --git a/spec/support/shared_examples/features/project_features_apply_to_issuables_shared_examples.rb b/spec/support/shared_examples/features/project_features_apply_to_issuables_shared_examples.rb index 64c3b80136d..1c040b87afa 100644 --- a/spec/support/shared_examples/features/project_features_apply_to_issuables_shared_examples.rb +++ b/spec/support/shared_examples/features/project_features_apply_to_issuables_shared_examples.rb @@ -1,8 +1,8 @@ -shared_examples 'project features apply to issuables' do |klass| +shared_examples "project features apply to issuables" do |klass| let(:described_class) { klass } let(:group) { create(:group) } - let(:user_in_group) { create(:group_member, :developer, user: create(:user), group: group ).user } + let(:user_in_group) { create(:group_member, :developer, user: create(:user), group: group).user } let(:user_outside_group) { create(:user) } let(:project) { create(:project, :public, project_args) } @@ -10,7 +10,7 @@ shared_examples 'project features apply to issuables' do |klass| def project_args feature = "#{described_class.model_name.plural}_access_level".to_sym - args = { group: group } + args = {group: group} args[feature] = access_level args @@ -22,32 +22,32 @@ shared_examples 'project features apply to issuables' do |klass| visit path end - context 'public access level' do + context "public access level" do let(:access_level) { ProjectFeature::ENABLED } - context 'group member' do + context "group member" do let(:user) { user_in_group } it { expect(page).to have_content(issuable.title) } end - context 'non-member' do + context "non-member" do let(:user) { user_outside_group } it { expect(page).to have_content(issuable.title) } end end - context 'private access level' do + context "private access level" do let(:access_level) { ProjectFeature::PRIVATE } - context 'group member' do + context "group member" do let(:user) { user_in_group } it { expect(page).to have_content(issuable.title) } end - context 'non-member' do + context "non-member" do let(:user) { user_outside_group } it { expect(page).not_to have_content(issuable.title) } diff --git a/spec/support/shared_examples/features/protected_branches_access_control_ce.rb b/spec/support/shared_examples/features/protected_branches_access_control_ce.rb index a8f2c2e7a5a..e9e95035c2c 100644 --- a/spec/support/shared_examples/features/protected_branches_access_control_ce.rb +++ b/spec/support/shared_examples/features/protected_branches_access_control_ce.rb @@ -3,15 +3,15 @@ shared_examples "protected branches > access control > CE" do it "allows creating protected branches that #{access_type_name} can push to" do visit project_protected_branches_path(project) - set_protected_branch_name('master') + set_protected_branch_name("master") find(".js-allowed-to-merge").click - within('.qa-allowed-to-merge-dropdown') do + within(".qa-allowed-to-merge-dropdown") do expect(first("li")).to have_content("Roles") - find(:link, 'No one').click + find(:link, "No one").click end - within('.js-new-protected-branch') do + within(".js-new-protected-branch") do allowed_to_push_button = find(".js-allowed-to-push") unless allowed_to_push_button.text == access_type_name @@ -29,18 +29,18 @@ shared_examples "protected branches > access control > CE" do it "allows updating protected branches so that #{access_type_name} can push to them" do visit project_protected_branches_path(project) - set_protected_branch_name('master') + set_protected_branch_name("master") find(".js-allowed-to-merge").click - within('.qa-allowed-to-merge-dropdown') do + within(".qa-allowed-to-merge-dropdown") do expect(first("li")).to have_content("Roles") - find(:link, 'No one').click + find(:link, "No one").click end find(".js-allowed-to-push").click - within('.qa-allowed-to-push-dropdown') do + within(".qa-allowed-to-push-dropdown") do expect(first("li")).to have_content("Roles") - find(:link, 'No one').click + find(:link, "No one").click end click_on "Protect" @@ -50,7 +50,7 @@ shared_examples "protected branches > access control > CE" do within(".protected-branches-list") do find(".js-allowed-to-push").click - within('.js-allowed-to-push-container') do + within(".js-allowed-to-push-container") do expect(first("li")).to have_content("Roles") find(:link, access_type_name).click end @@ -66,9 +66,9 @@ shared_examples "protected branches > access control > CE" do it "allows creating protected branches that #{access_type_name} can merge to" do visit project_protected_branches_path(project) - set_protected_branch_name('master') + set_protected_branch_name("master") - within('.js-new-protected-branch') do + within(".js-new-protected-branch") do allowed_to_merge_button = find(".js-allowed-to-merge") unless allowed_to_merge_button.text == access_type_name @@ -78,9 +78,9 @@ shared_examples "protected branches > access control > CE" do end find(".js-allowed-to-push").click - within('.qa-allowed-to-push-dropdown') do + within(".qa-allowed-to-push-dropdown") do expect(first("li")).to have_content("Roles") - find(:link, 'No one').click + find(:link, "No one").click end click_on "Protect" @@ -92,18 +92,18 @@ shared_examples "protected branches > access control > CE" do it "allows updating protected branches so that #{access_type_name} can merge to them" do visit project_protected_branches_path(project) - set_protected_branch_name('master') + set_protected_branch_name("master") find(".js-allowed-to-merge").click - within('.qa-allowed-to-merge-dropdown') do + within(".qa-allowed-to-merge-dropdown") do expect(first("li")).to have_content("Roles") - find(:link, 'No one').click + find(:link, "No one").click end find(".js-allowed-to-push").click - within('.qa-allowed-to-push-dropdown') do + within(".qa-allowed-to-push-dropdown") do expect(first("li")).to have_content("Roles") - find(:link, 'No one').click + find(:link, "No one").click end click_on "Protect" @@ -113,7 +113,7 @@ shared_examples "protected branches > access control > CE" do within(".protected-branches-list") do find(".js-allowed-to-merge").click - within('.js-allowed-to-merge-container') do + within(".js-allowed-to-merge-container") do expect(first("li")).to have_content("Roles") find(:link, access_type_name).click end diff --git a/spec/support/shared_examples/features/search_shared_examples.rb b/spec/support/shared_examples/features/search_shared_examples.rb index 25ebbf011d5..a18553ada97 100644 --- a/spec/support/shared_examples/features/search_shared_examples.rb +++ b/spec/support/shared_examples/features/search_shared_examples.rb @@ -1,5 +1,5 @@ -shared_examples 'top right search form' do - it 'does not show top right search form' do - expect(page).not_to have_selector('.search') +shared_examples "top right search form" do + it "does not show top right search form" do + expect(page).not_to have_selector(".search") end end diff --git a/spec/support/shared_examples/file_finder.rb b/spec/support/shared_examples/file_finder.rb index 0dc351b5149..b1c56ccea90 100644 --- a/spec/support/shared_examples/file_finder.rb +++ b/spec/support/shared_examples/file_finder.rb @@ -1,8 +1,8 @@ -shared_examples 'file finder' do - let(:query) { 'files' } +shared_examples "file finder" do + let(:query) { "files" } let(:search_results) { subject.find(query) } - it 'finds by name' do + it "finds by name" do blob = search_results.find { |blob| blob.filename == expected_file_by_name } expect(blob.filename).to eq(expected_file_by_name) @@ -11,7 +11,7 @@ shared_examples 'file finder' do expect(blob.data).not_to be_empty end - it 'finds by content' do + it "finds by content" do blob = search_results.find { |blob| blob.filename == expected_file_by_content } expect(blob.filename).to eq(expected_file_by_content) diff --git a/spec/support/shared_examples/gitlab_verify.rb b/spec/support/shared_examples/gitlab_verify.rb index 560913ca92f..d9278bcfc8d 100644 --- a/spec/support/shared_examples/gitlab_verify.rb +++ b/spec/support/shared_examples/gitlab_verify.rb @@ -1,18 +1,18 @@ -RSpec.shared_examples 'Gitlab::Verify::BatchVerifier subclass' do - describe 'batching' do +RSpec.shared_examples "Gitlab::Verify::BatchVerifier subclass" do + describe "batching" do let(:first_batch) { objects[0].id..objects[0].id } let(:second_batch) { objects[1].id..objects[1].id } let(:third_batch) { objects[2].id..objects[2].id } - it 'iterates through objects in batches' do + it "iterates through objects in batches" do expect(collect_ranges).to eq([first_batch, second_batch, third_batch]) end - it 'allows the starting ID to be specified' do + it "allows the starting ID to be specified" do expect(collect_ranges(start: second_batch.first)).to eq([second_batch, third_batch]) end - it 'allows the finishing ID to be specified' do + it "allows the finishing ID to be specified" do expect(collect_ranges(finish: second_batch.last)).to eq([first_batch, second_batch]) end end diff --git a/spec/support/shared_examples/graphql/issuable_state_shared_examples.rb b/spec/support/shared_examples/graphql/issuable_state_shared_examples.rb index 713f0a879c1..4ec71f9f664 100644 --- a/spec/support/shared_examples/graphql/issuable_state_shared_examples.rb +++ b/spec/support/shared_examples/graphql/issuable_state_shared_examples.rb @@ -1,5 +1,5 @@ -RSpec.shared_examples 'issuable state' do - it 'exposes all the existing issuable states' do - expect(described_class.values.keys).to include(*%w[opened closed locked]) +RSpec.shared_examples "issuable state" do + it "exposes all the existing issuable states" do + expect(described_class.values.keys).to include("opened", "closed", "locked") end end diff --git a/spec/support/shared_examples/group_members_shared_example.rb b/spec/support/shared_examples/group_members_shared_example.rb index 547c83c7955..812993313f3 100644 --- a/spec/support/shared_examples/group_members_shared_example.rb +++ b/spec/support/shared_examples/group_members_shared_example.rb @@ -1,14 +1,14 @@ -RSpec.shared_examples 'members and requesters associations' do - describe '#members_and_requesters' do - it 'includes members and requesters' do +RSpec.shared_examples "members and requesters associations" do + describe "#members_and_requesters" do + it "includes members and requesters" do member_and_requester_user_ids = namespace.members_and_requesters.pluck(:user_id) expect(member_and_requester_user_ids).to include(requester.id, developer.id) end end - describe '#members' do - it 'includes members and exclude requesters' do + describe "#members" do + it "includes members and exclude requesters" do member_user_ids = namespace.members.pluck(:user_id) expect(member_user_ids).to include(developer.id) @@ -16,8 +16,8 @@ RSpec.shared_examples 'members and requesters associations' do end end - describe '#requesters' do - it 'does not include requesters' do + describe "#requesters" do + it "does not include requesters" do requester_user_ids = namespace.requesters.pluck(:user_id) expect(requester_user_ids).to include(requester.id) diff --git a/spec/support/shared_examples/helm_generated_script.rb b/spec/support/shared_examples/helm_generated_script.rb index ba9b7d3bdcf..14dfc220acf 100644 --- a/spec/support/shared_examples/helm_generated_script.rb +++ b/spec/support/shared_examples/helm_generated_script.rb @@ -1,12 +1,12 @@ -shared_examples 'helm commands' do - describe '#generate_script' do +shared_examples "helm commands" do + describe "#generate_script" do let(:helm_setup) do <<~EOS - set -xeo pipefail + set -xeo pipefail EOS end - it 'should return appropriate command' do + it "should return appropriate command" do expect(subject.generate_script.strip).to eq((helm_setup + commands).strip) end end diff --git a/spec/support/shared_examples/instance_statistics_controllers_shared_examples.rb b/spec/support/shared_examples/instance_statistics_controllers_shared_examples.rb index 8ea307c7c61..9dd4054a1ec 100644 --- a/spec/support/shared_examples/instance_statistics_controllers_shared_examples.rb +++ b/spec/support/shared_examples/instance_statistics_controllers_shared_examples.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -shared_examples 'instance statistics availability' do +shared_examples "instance statistics availability" do let(:user) { create(:user) } before do @@ -9,14 +9,14 @@ shared_examples 'instance statistics availability' do stub_application_setting(usage_ping_enabled: true) end - describe 'GET #index' do - it 'is available when the feature is available publicly' do + describe "GET #index" do + it "is available when the feature is available publicly" do get :index expect(response).to have_gitlab_http_status(:success) end - it 'renders a 404 when the feature is not available publicly' do + it "renders a 404 when the feature is not available publicly" do stub_application_setting(instance_statistics_visibility_private: true) get :index @@ -24,10 +24,10 @@ shared_examples 'instance statistics availability' do expect(response).to have_gitlab_http_status(:not_found) end - context 'for admins' do + context "for admins" do let(:user) { create(:admin) } - it 'allows access when the feature is not available publicly' do + it "allows access when the feature is not available publicly" do stub_application_setting(instance_statistics_visibility_private: true) get :index diff --git a/spec/support/shared_examples/issuable_shared_examples.rb b/spec/support/shared_examples/issuable_shared_examples.rb index c3d40c5b231..e28346c8345 100644 --- a/spec/support/shared_examples/issuable_shared_examples.rb +++ b/spec/support/shared_examples/issuable_shared_examples.rb @@ -1,18 +1,18 @@ -shared_examples 'cache counters invalidator' do - it 'invalidates counter cache for assignees' do +shared_examples "cache counters invalidator" do + it "invalidates counter cache for assignees" do expect_any_instance_of(User).to receive(:invalidate_merge_request_cache_counts) described_class.new(project, user, {}).execute(merge_request) end end -shared_examples 'system notes for milestones' do +shared_examples "system notes for milestones" do def update_issuable(opts) issuable = try(:issue) || try(:merge_request) described_class.new(project, user, opts).execute(issuable) end - context 'group milestones' do + context "group milestones" do let(:group) { create(:group) } let(:group_milestone) { create(:milestone, group: group) } @@ -21,23 +21,23 @@ shared_examples 'system notes for milestones' do create(:group_member, group: group, user: user) end - it 'creates a system note' do - expect do + it "creates a system note" do + expect { update_issuable(milestone: group_milestone) - end.to change { Note.system.count }.by(1) + }.to change { Note.system.count }.by(1) end end - context 'project milestones' do - it 'creates a system note' do - expect do + context "project milestones" do + it "creates a system note" do + expect { update_issuable(milestone: create(:milestone)) - end.to change { Note.system.count }.by(1) + }.to change { Note.system.count }.by(1) end end end -shared_examples 'updating a single task' do +shared_examples "updating a single task" do def update_issuable(opts) issuable = try(:issue) || try(:merge_request) described_class.new(project, user, opts).execute(issuable) @@ -47,64 +47,64 @@ shared_examples 'updating a single task' do update_issuable(description: "- [ ] Task 1\n- [ ] Task 2") end - context 'when a task is marked as completed' do + context "when a task is marked as completed" do before do - update_issuable(update_task: { index: 1, checked: true, line_source: '- [ ] Task 1', line_number: 1 }) + update_issuable(update_task: {index: 1, checked: true, line_source: "- [ ] Task 1", line_number: 1}) end - it 'creates system note about task status change' do - note1 = find_note('marked the task **Task 1** as completed') + it "creates system note about task status change" do + note1 = find_note("marked the task **Task 1** as completed") expect(note1).not_to be_nil - description_notes = find_notes('description') + description_notes = find_notes("description") expect(description_notes.length).to eq(1) end end - context 'when a task is marked as incomplete' do + context "when a task is marked as incomplete" do before do update_issuable(description: "- [x] Task 1\n- [X] Task 2") - update_issuable(update_task: { index: 2, checked: false, line_source: '- [X] Task 2', line_number: 2 }) + update_issuable(update_task: {index: 2, checked: false, line_source: "- [X] Task 2", line_number: 2}) end - it 'creates system note about task status change' do - note1 = find_note('marked the task **Task 2** as incomplete') + it "creates system note about task status change" do + note1 = find_note("marked the task **Task 2** as incomplete") expect(note1).not_to be_nil - description_notes = find_notes('description') + description_notes = find_notes("description") expect(description_notes.length).to eq(1) end end - context 'when the task position has been modified' do + context "when the task position has been modified" do before do update_issuable(description: "- [ ] Task 1\n- [ ] Task 3\n- [ ] Task 2") end - it 'raises an exception' do + it "raises an exception" do expect(Note.count).to eq(2) - expect do - update_issuable(update_task: { index: 2, checked: true, line_source: '- [ ] Task 2', line_number: 2 }) - end.to raise_error(ActiveRecord::StaleObjectError) + expect { + update_issuable(update_task: {index: 2, checked: true, line_source: "- [ ] Task 2", line_number: 2}) + }.to raise_error(ActiveRecord::StaleObjectError) expect(Note.count).to eq(2) end end - context 'when the content changes but not task line number' do + context "when the content changes but not task line number" do before do update_issuable(description: "Paragraph\n\n- [ ] Task 1\n- [x] Task 2") update_issuable(description: "Paragraph with more words\n\n- [ ] Task 1\n- [x] Task 2") - update_issuable(update_task: { index: 2, checked: false, line_source: '- [x] Task 2', line_number: 4 }) + update_issuable(update_task: {index: 2, checked: false, line_source: "- [x] Task 2", line_number: 4}) end - it 'creates system note about task status change' do - note1 = find_note('marked the task **Task 2** as incomplete') + it "creates system note about task status change" do + note1 = find_note("marked the task **Task 2** as incomplete") expect(note1).not_to be_nil - description_notes = find_notes('description') + description_notes = find_notes("description") expect(description_notes.length).to eq(2) end end diff --git a/spec/support/shared_examples/issuables_list_metadata_shared_examples.rb b/spec/support/shared_examples/issuables_list_metadata_shared_examples.rb index 90d67fd00fc..a52fb093c30 100644 --- a/spec/support/shared_examples/issuables_list_metadata_shared_examples.rb +++ b/spec/support/shared_examples/issuables_list_metadata_shared_examples.rb @@ -1,11 +1,11 @@ -shared_examples 'issuables list meta-data' do |issuable_type, action = nil| +shared_examples "issuables list meta-data" do |issuable_type, action = nil| include ProjectForksHelper def get_action(action, project) if action - get action, params: { author_id: project.creator.id } + get action, params: {author_id: project.creator.id} else - get :index, params: { namespace_id: project.namespace, project_id: project } + get :index, params: {namespace_id: project.namespace, project_id: project} end end @@ -18,9 +18,9 @@ shared_examples 'issuables list meta-data' do |issuable_type, action = nil| end before do - @issuable_ids = %w[fix improve/awesome].map do |source_branch| + @issuable_ids = %w[fix improve/awesome].map { |source_branch| create_issuable(issuable_type, project, source_branch: source_branch).id - end + } end it "creates indexed meta-data object for issuable notes and votes count" do @@ -36,7 +36,7 @@ shared_examples 'issuables list meta-data' do |issuable_type, action = nil| it "avoids N+1 queries" do control = ActiveRecord::QueryRecorder.new { get_action(action, project) } - issuable = create_issuable(issuable_type, project, source_branch: 'csv') + issuable = create_issuable(issuable_type, project, source_branch: "csv") if issuable_type == :merge_request issuable.update!(source_project: fork_project(project)) @@ -51,9 +51,9 @@ shared_examples 'issuables list meta-data' do |issuable_type, action = nil| it "doesn't execute any queries with false conditions" do get_empty = if action - proc { get action, params: { author_id: project.creator.id } } + proc { get action, params: {author_id: project.creator.id} } else - proc { get :index, params: { namespace_id: project2.namespace, project_id: project2 } } + proc { get :index, params: {namespace_id: project2.namespace, project_id: project2} } end expect(&get_empty).not_to make_queries_matching(/WHERE (?:1=0|0=1)/) diff --git a/spec/support/shared_examples/issue_tracker_service_shared_example.rb b/spec/support/shared_examples/issue_tracker_service_shared_example.rb index a6ab03cb808..59d5e09ae61 100644 --- a/spec/support/shared_examples/issue_tracker_service_shared_example.rb +++ b/spec/support/shared_examples/issue_tracker_service_shared_example.rb @@ -1,22 +1,22 @@ -RSpec.shared_examples 'issue tracker service URL attribute' do |url_attr| - it { is_expected.to allow_value('https://example.com').for(url_attr) } +RSpec.shared_examples "issue tracker service URL attribute" do |url_attr| + it { is_expected.to allow_value("https://example.com").for(url_attr) } - it { is_expected.not_to allow_value('example.com').for(url_attr) } - it { is_expected.not_to allow_value('ftp://example.com').for(url_attr) } - it { is_expected.not_to allow_value('herp-and-derp').for(url_attr) } + it { is_expected.not_to allow_value("example.com").for(url_attr) } + it { is_expected.not_to allow_value("ftp://example.com").for(url_attr) } + it { is_expected.not_to allow_value("herp-and-derp").for(url_attr) } end -RSpec.shared_examples 'allows project key on reference pattern' do |url_attr| - it 'allows underscores in the project name' do - expect(described_class.reference_pattern.match('EXT_EXT-1234')[0]).to eq 'EXT_EXT-1234' +RSpec.shared_examples "allows project key on reference pattern" do |url_attr| + it "allows underscores in the project name" do + expect(described_class.reference_pattern.match("EXT_EXT-1234")[0]).to eq "EXT_EXT-1234" end - it 'allows numbers in the project name' do - expect(described_class.reference_pattern.match('EXT3_EXT-1234')[0]).to eq 'EXT3_EXT-1234' + it "allows numbers in the project name" do + expect(described_class.reference_pattern.match("EXT3_EXT-1234")[0]).to eq "EXT3_EXT-1234" end - it 'requires the project name to begin with A-Z' do - expect(described_class.reference_pattern.match('3EXT_EXT-1234')).to eq nil - expect(described_class.reference_pattern.match('EXT_EXT-1234')[0]).to eq 'EXT_EXT-1234' + it "requires the project name to begin with A-Z" do + expect(described_class.reference_pattern.match("3EXT_EXT-1234")).to eq nil + expect(described_class.reference_pattern.match("EXT_EXT-1234")[0]).to eq "EXT_EXT-1234" end end diff --git a/spec/support/shared_examples/ldap_shared_examples.rb b/spec/support/shared_examples/ldap_shared_examples.rb index 52c34e78965..46ba6769dae 100644 --- a/spec/support/shared_examples/ldap_shared_examples.rb +++ b/spec/support/shared_examples/ldap_shared_examples.rb @@ -1,68 +1,68 @@ -shared_examples_for 'normalizes a DN' do +shared_examples_for "normalizes a DN" do using RSpec::Parameterized::TableSyntax where(:test_description, :given, :expected) do - 'strips extraneous whitespace' | 'uid =John Smith , ou = People, dc= example,dc =com' | 'uid=john smith,ou=people,dc=example,dc=com' - 'strips extraneous whitespace for a DN with a single RDN' | 'uid = John Smith' | 'uid=john smith' - 'unescapes non-reserved, non-special Unicode characters' | 'uid = Sebasti\\c3\\a1n\\ C.\\20Smith, ou=People (aka. \\22humans\\") ,dc=example, dc=com' | 'uid=sebastián c. smith,ou=people (aka. \\"humans\\"),dc=example,dc=com' - 'downcases the whole string' | 'UID=John Smith,ou=People,dc=example,dc=com' | 'uid=john smith,ou=people,dc=example,dc=com' - 'for a null DN (empty string), returns empty string and does not error' | '' | '' - 'does not strip an escaped leading space in an attribute value' | 'uid=\\ John Smith,ou=People,dc=example,dc=com' | 'uid=\\ john smith,ou=people,dc=example,dc=com' - 'does not strip an escaped leading space in the last attribute value' | 'uid=\\ John Smith' | 'uid=\\ john smith' - 'does not strip an escaped trailing space in an attribute value' | 'uid=John Smith\\ ,ou=People,dc=example,dc=com' | 'uid=john smith\\ ,ou=people,dc=example,dc=com' - 'strips extraneous spaces after an escaped trailing space' | 'uid=John Smith\\ ,ou=People,dc=example,dc=com' | 'uid=john smith\\ ,ou=people,dc=example,dc=com' - 'strips extraneous spaces after an escaped trailing space at the end of the DN' | 'uid=John Smith,ou=People,dc=example,dc=com\\ ' | 'uid=john smith,ou=people,dc=example,dc=com\\ ' - 'properly preserves escaped trailing space after unescaped trailing spaces' | 'uid=John Smith \\ ,ou=People,dc=example,dc=com' | 'uid=john smith \\ ,ou=people,dc=example,dc=com' - 'preserves multiple inner spaces in an attribute value' | 'uid=John Smith,ou=People,dc=example,dc=com' | 'uid=john smith,ou=people,dc=example,dc=com' - 'preserves inner spaces after an escaped space' | 'uid=John\\ Smith,ou=People,dc=example,dc=com' | 'uid=john smith,ou=people,dc=example,dc=com' - 'hex-escapes an escaped leading newline in an attribute value' | "uid=\\\nJohn Smith,ou=People,dc=example,dc=com" | "uid=\\0ajohn smith,ou=people,dc=example,dc=com" - 'hex-escapes and does not strip an escaped trailing newline in an attribute value' | "uid=John Smith\\\n,ou=People,dc=example,dc=com" | "uid=john smith\\0a,ou=people,dc=example,dc=com" - 'hex-escapes an unescaped leading newline (actually an invalid DN?)' | "uid=\nJohn Smith,ou=People,dc=example,dc=com" | "uid=\\0ajohn smith,ou=people,dc=example,dc=com" - 'strips an unescaped trailing newline (actually an invalid DN?)' | "uid=John Smith\n,ou=People,dc=example,dc=com" | "uid=john smith,ou=people,dc=example,dc=com" - 'does not strip if no extraneous whitespace' | 'uid=John Smith,ou=People,dc=example,dc=com' | 'uid=john smith,ou=people,dc=example,dc=com' - 'does not modify an escaped equal sign in an attribute value' | 'uid= foo \\= bar' | 'uid=foo \\= bar' - 'converts an escaped hex equal sign to an escaped equal sign in an attribute value' | 'uid= foo \\3D bar' | 'uid=foo \\= bar' - 'does not modify an escaped comma in an attribute value' | 'uid= John C. Smith, ou=San Francisco\\, CA' | 'uid=john c. smith,ou=san francisco\\, ca' - 'converts an escaped hex comma to an escaped comma in an attribute value' | 'uid= John C. Smith, ou=San Francisco\\2C CA' | 'uid=john c. smith,ou=san francisco\\, ca' - 'does not modify an escaped hex carriage return character in an attribute value' | 'uid= John C. Smith, ou=San Francisco\\,\\0DCA' | 'uid=john c. smith,ou=san francisco\\,\\0dca' - 'does not modify an escaped hex line feed character in an attribute value' | 'uid= John C. Smith, ou=San Francisco\\,\\0ACA' | 'uid=john c. smith,ou=san francisco\\,\\0aca' - 'does not modify an escaped hex CRLF in an attribute value' | 'uid= John C. Smith, ou=San Francisco\\,\\0D\\0ACA' | 'uid=john c. smith,ou=san francisco\\,\\0d\\0aca' - 'allows attribute type name OIDs' | '0.9.2342.19200300.100.1.25=Example,0.9.2342.19200300.100.1.25=Com' | '0.9.2342.19200300.100.1.25=example,0.9.2342.19200300.100.1.25=com' - 'strips extraneous whitespace from attribute type name OIDs' | '0.9.2342.19200300.100.1.25 = Example, 0.9.2342.19200300.100.1.25 = Com' | '0.9.2342.19200300.100.1.25=example,0.9.2342.19200300.100.1.25=com' + "strips extraneous whitespace" | "uid =John Smith , ou = People, dc= example,dc =com" | "uid=john smith,ou=people,dc=example,dc=com" + "strips extraneous whitespace for a DN with a single RDN" | "uid = John Smith" | "uid=john smith" + "unescapes non-reserved, non-special Unicode characters" | 'uid = Sebasti\\c3\\a1n\\ C.\\20Smith, ou=People (aka. \\22humans\\") ,dc=example, dc=com' | 'uid=sebastián c. smith,ou=people (aka. \\"humans\\"),dc=example,dc=com' + "downcases the whole string" | "UID=John Smith,ou=People,dc=example,dc=com" | "uid=john smith,ou=people,dc=example,dc=com" + "for a null DN (empty string), returns empty string and does not error" | "" | "" + "does not strip an escaped leading space in an attribute value" | 'uid=\\ John Smith,ou=People,dc=example,dc=com' | 'uid=\\ john smith,ou=people,dc=example,dc=com' + "does not strip an escaped leading space in the last attribute value" | 'uid=\\ John Smith' | 'uid=\\ john smith' + "does not strip an escaped trailing space in an attribute value" | 'uid=John Smith\\ ,ou=People,dc=example,dc=com' | 'uid=john smith\\ ,ou=people,dc=example,dc=com' + "strips extraneous spaces after an escaped trailing space" | 'uid=John Smith\\ ,ou=People,dc=example,dc=com' | 'uid=john smith\\ ,ou=people,dc=example,dc=com' + "strips extraneous spaces after an escaped trailing space at the end of the DN" | 'uid=John Smith,ou=People,dc=example,dc=com\\ ' | 'uid=john smith,ou=people,dc=example,dc=com\\ ' + "properly preserves escaped trailing space after unescaped trailing spaces" | 'uid=John Smith \\ ,ou=People,dc=example,dc=com' | 'uid=john smith \\ ,ou=people,dc=example,dc=com' + "preserves multiple inner spaces in an attribute value" | "uid=John Smith,ou=People,dc=example,dc=com" | "uid=john smith,ou=people,dc=example,dc=com" + "preserves inner spaces after an escaped space" | 'uid=John\\ Smith,ou=People,dc=example,dc=com' | "uid=john smith,ou=people,dc=example,dc=com" + "hex-escapes an escaped leading newline in an attribute value" | "uid=\\\nJohn Smith,ou=People,dc=example,dc=com" | "uid=\\0ajohn smith,ou=people,dc=example,dc=com" + "hex-escapes and does not strip an escaped trailing newline in an attribute value" | "uid=John Smith\\\n,ou=People,dc=example,dc=com" | "uid=john smith\\0a,ou=people,dc=example,dc=com" + "hex-escapes an unescaped leading newline (actually an invalid DN?)" | "uid=\nJohn Smith,ou=People,dc=example,dc=com" | "uid=\\0ajohn smith,ou=people,dc=example,dc=com" + "strips an unescaped trailing newline (actually an invalid DN?)" | "uid=John Smith\n,ou=People,dc=example,dc=com" | "uid=john smith,ou=people,dc=example,dc=com" + "does not strip if no extraneous whitespace" | "uid=John Smith,ou=People,dc=example,dc=com" | "uid=john smith,ou=people,dc=example,dc=com" + "does not modify an escaped equal sign in an attribute value" | 'uid= foo \\= bar' | 'uid=foo \\= bar' + "converts an escaped hex equal sign to an escaped equal sign in an attribute value" | 'uid= foo \\3D bar' | 'uid=foo \\= bar' + "does not modify an escaped comma in an attribute value" | 'uid= John C. Smith, ou=San Francisco\\, CA' | 'uid=john c. smith,ou=san francisco\\, ca' + "converts an escaped hex comma to an escaped comma in an attribute value" | 'uid= John C. Smith, ou=San Francisco\\2C CA' | 'uid=john c. smith,ou=san francisco\\, ca' + "does not modify an escaped hex carriage return character in an attribute value" | 'uid= John C. Smith, ou=San Francisco\\,\\0DCA' | 'uid=john c. smith,ou=san francisco\\,\\0dca' + "does not modify an escaped hex line feed character in an attribute value" | 'uid= John C. Smith, ou=San Francisco\\,\\0ACA' | 'uid=john c. smith,ou=san francisco\\,\\0aca' + "does not modify an escaped hex CRLF in an attribute value" | 'uid= John C. Smith, ou=San Francisco\\,\\0D\\0ACA' | 'uid=john c. smith,ou=san francisco\\,\\0d\\0aca' + "allows attribute type name OIDs" | "0.9.2342.19200300.100.1.25=Example,0.9.2342.19200300.100.1.25=Com" | "0.9.2342.19200300.100.1.25=example,0.9.2342.19200300.100.1.25=com" + "strips extraneous whitespace from attribute type name OIDs" | "0.9.2342.19200300.100.1.25 = Example, 0.9.2342.19200300.100.1.25 = Com" | "0.9.2342.19200300.100.1.25=example,0.9.2342.19200300.100.1.25=com" end with_them do - it 'normalizes the DN' do + it "normalizes the DN" do assert_generic_test(test_description, subject, expected) end end end -shared_examples_for 'normalizes a DN attribute value' do +shared_examples_for "normalizes a DN attribute value" do using RSpec::Parameterized::TableSyntax where(:test_description, :given, :expected) do - 'strips extraneous whitespace' | ' John Smith ' | 'john smith' - 'unescapes non-reserved, non-special Unicode characters' | 'Sebasti\\c3\\a1n\\ C.\\20Smith' | 'sebastián c. smith' - 'downcases the whole string' | 'JoHn C. Smith' | 'john c. smith' - 'does not strip an escaped leading space in an attribute value' | '\\ John Smith' | '\\ john smith' - 'does not strip an escaped trailing space in an attribute value' | 'John Smith\\ ' | 'john smith\\ ' - 'hex-escapes an escaped leading newline in an attribute value' | "\\\nJohn Smith" | "\\0ajohn smith" - 'hex-escapes and does not strip an escaped trailing newline in an attribute value' | "John Smith\\\n" | "john smith\\0a" - 'hex-escapes an unescaped leading newline (actually an invalid DN value?)' | "\nJohn Smith" | "\\0ajohn smith" - 'strips an unescaped trailing newline (actually an invalid DN value?)' | "John Smith\n" | "john smith" - 'does not strip if no extraneous whitespace' | 'John Smith' | 'john smith' - 'does not modify an escaped equal sign in an attribute value' | ' foo \\= bar' | 'foo \\= bar' - 'converts an escaped hex equal sign to an escaped equal sign in an attribute value' | ' foo \\3D bar' | 'foo \\= bar' - 'does not modify an escaped comma in an attribute value' | 'San Francisco\\, CA' | 'san francisco\\, ca' - 'converts an escaped hex comma to an escaped comma in an attribute value' | 'San Francisco\\2C CA' | 'san francisco\\, ca' - 'does not modify an escaped hex carriage return character in an attribute value' | 'San Francisco\\,\\0DCA' | 'san francisco\\,\\0dca' - 'does not modify an escaped hex line feed character in an attribute value' | 'San Francisco\\,\\0ACA' | 'san francisco\\,\\0aca' - 'does not modify an escaped hex CRLF in an attribute value' | 'San Francisco\\,\\0D\\0ACA' | 'san francisco\\,\\0d\\0aca' + "strips extraneous whitespace" | " John Smith " | "john smith" + "unescapes non-reserved, non-special Unicode characters" | 'Sebasti\\c3\\a1n\\ C.\\20Smith' | "sebastián c. smith" + "downcases the whole string" | "JoHn C. Smith" | "john c. smith" + "does not strip an escaped leading space in an attribute value" | '\\ John Smith' | '\\ john smith' + "does not strip an escaped trailing space in an attribute value" | 'John Smith\\ ' | 'john smith\\ ' + "hex-escapes an escaped leading newline in an attribute value" | "\\\nJohn Smith" | "\\0ajohn smith" + "hex-escapes and does not strip an escaped trailing newline in an attribute value" | "John Smith\\\n" | "john smith\\0a" + "hex-escapes an unescaped leading newline (actually an invalid DN value?)" | "\nJohn Smith" | "\\0ajohn smith" + "strips an unescaped trailing newline (actually an invalid DN value?)" | "John Smith\n" | "john smith" + "does not strip if no extraneous whitespace" | "John Smith" | "john smith" + "does not modify an escaped equal sign in an attribute value" | ' foo \\= bar' | 'foo \\= bar' + "converts an escaped hex equal sign to an escaped equal sign in an attribute value" | ' foo \\3D bar' | 'foo \\= bar' + "does not modify an escaped comma in an attribute value" | 'San Francisco\\, CA' | 'san francisco\\, ca' + "converts an escaped hex comma to an escaped comma in an attribute value" | 'San Francisco\\2C CA' | 'san francisco\\, ca' + "does not modify an escaped hex carriage return character in an attribute value" | 'San Francisco\\,\\0DCA' | 'san francisco\\,\\0dca' + "does not modify an escaped hex line feed character in an attribute value" | 'San Francisco\\,\\0ACA' | 'san francisco\\,\\0aca' + "does not modify an escaped hex CRLF in an attribute value" | 'San Francisco\\,\\0D\\0ACA' | 'san francisco\\,\\0d\\0aca' end with_them do - it 'normalizes the DN attribute value' do + it "normalizes the DN attribute value" do assert_generic_test(test_description, subject, expected) end end diff --git a/spec/support/shared_examples/legacy_path_redirect_shared_examples.rb b/spec/support/shared_examples/legacy_path_redirect_shared_examples.rb index f300bdd48b1..185561b4203 100644 --- a/spec/support/shared_examples/legacy_path_redirect_shared_examples.rb +++ b/spec/support/shared_examples/legacy_path_redirect_shared_examples.rb @@ -1,4 +1,4 @@ -shared_examples 'redirecting a legacy path' do |source, target| +shared_examples "redirecting a legacy path" do |source, target| include RSpec::Rails::RequestExampleGroup it "redirects #{source} to #{target} when the resource does not exist" do diff --git a/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_examples.rb b/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_examples.rb index dcf7c1a90c2..0ca3d63e702 100644 --- a/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_examples.rb +++ b/spec/support/shared_examples/lib/gitlab/background_migration/backfill_project_repositories_examples.rb @@ -1,13 +1,13 @@ -shared_examples 'backfill migration for project repositories' do |storage| - describe '#perform' do +shared_examples "backfill migration for project repositories" do |storage| + describe "#perform" do let(:storage_versions) { storage == :legacy ? [nil, 0] : [1, 2] } let(:storage_version) { storage_versions.first } let(:namespaces) { table(:namespaces) } let(:project_repositories) { table(:project_repositories) } let(:projects) { table(:projects) } let(:shards) { table(:shards) } - let(:group) { namespaces.create!(name: 'foo', path: 'foo') } - let(:shard) { shards.create!(name: 'default') } + let(:group) { namespaces.create!(name: "foo", path: "foo") } + let(:shard) { shards.create!(name: "default") } it "creates a project_repository row for projects on #{storage} storage that needs one" do storage_versions.each_with_index do |storage_version, index| @@ -18,27 +18,27 @@ shared_examples 'backfill migration for project repositories' do |storage| 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) + 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) 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) + 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) end - it 'inserts rows in a single query' do - projects.create!(name: 'foo', path: 'foo', namespace_id: group.id, storage_version: storage_version, repository_storage: shard.name) - group2 = namespaces.create!(name: 'gro', path: 'gro') + it "inserts rows in a single query" do + projects.create!(name: "foo", path: "foo", namespace_id: group.id, storage_version: storage_version, repository_storage: shard.name) + group2 = namespaces.create!(name: "gro", path: "gro") control_count = ActiveRecord::QueryRecorder.new { described_class.new.perform(1, projects.last.id) } - projects.create!(name: 'bar', path: 'bar', namespace_id: group.id, storage_version: storage_version, repository_storage: shard.name) - projects.create!(name: 'top', path: 'top', namespace_id: group.id, storage_version: storage_version, repository_storage: shard.name) - projects.create!(name: 'zoo', path: 'zoo', namespace_id: group2.id, storage_version: storage_version, repository_storage: shard.name) + projects.create!(name: "bar", path: "bar", namespace_id: group.id, storage_version: storage_version, repository_storage: shard.name) + projects.create!(name: "top", path: "top", namespace_id: group.id, storage_version: storage_version, repository_storage: shard.name) + projects.create!(name: "zoo", path: "zoo", namespace_id: group2.id, storage_version: storage_version, repository_storage: shard.name) expect { described_class.new.perform(1, projects.last.id) }.not_to exceed_query_limit(control_count) end diff --git a/spec/support/shared_examples/malicious_regexp_shared_examples.rb b/spec/support/shared_examples/malicious_regexp_shared_examples.rb index db69b75c0c8..076ca7cf46c 100644 --- a/spec/support/shared_examples/malicious_regexp_shared_examples.rb +++ b/spec/support/shared_examples/malicious_regexp_shared_examples.rb @@ -1,10 +1,10 @@ -require 'timeout' +require "timeout" -shared_examples 'malicious regexp' do - let(:malicious_text) { 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!' } - let(:malicious_regexp) { '(?i)^(([a-z])+.)+[A-Z]([a-z])+$' } +shared_examples "malicious regexp" do + let(:malicious_text) { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!" } + let(:malicious_regexp) { "(?i)^(([a-z])+.)+[A-Z]([a-z])+$" } - it 'takes under a second' do + it "takes under a second" do expect { Timeout.timeout(1) { subject } }.not_to raise_error end end diff --git a/spec/support/shared_examples/mentionable_shared_examples.rb b/spec/support/shared_examples/mentionable_shared_examples.rb index 1226841f24c..f59f87d2822 100644 --- a/spec/support/shared_examples/mentionable_shared_examples.rb +++ b/spec/support/shared_examples/mentionable_shared_examples.rb @@ -4,7 +4,7 @@ # - let(:backref_text) { "the way that +subject+ should refer to itself in backreferences " } # - let(:set_mentionable_text) { lambda { |txt| "block that assigns txt to the subject's mentionable_text" } } -shared_context 'mentionable context' do +shared_context "mentionable context" do let(:project) { subject.project } let(:author) { subject.author } @@ -57,10 +57,10 @@ shared_context 'mentionable context' do end end -shared_examples 'a mentionable' do - include_context 'mentionable context' +shared_examples "a mentionable" do + include_context "mentionable context" - it 'generates a descriptive back-reference' do + it "generates a descriptive back-reference" do expect(subject.gfm_reference).to eq(backref_text) end @@ -76,9 +76,9 @@ shared_examples 'a mentionable' do expect(refs).to include(ext_commit) end - it 'creates cross-reference notes' do + it "creates cross-reference notes" do mentioned_objects = [mentioned_issue, mentioned_mr, mentioned_commit, - ext_issue, ext_mr, ext_commit] + ext_issue, ext_mr, ext_commit,] mentioned_objects.each do |referenced| expect(SystemNoteService).to receive(:cross_reference) @@ -89,16 +89,16 @@ shared_examples 'a mentionable' do end end -shared_examples 'an editable mentionable' do - include_context 'mentionable context' +shared_examples "an editable mentionable" do + include_context "mentionable context" - it_behaves_like 'a mentionable' + it_behaves_like "a mentionable" let(:new_issues) do [create(:issue, project: project), create(:issue, project: ext_proj)] end - it 'creates new cross-reference notes when the mentionable text is edited' do + it "creates new cross-reference notes when the mentionable text is edited" do subject.save subject.create_cross_references! diff --git a/spec/support/shared_examples/milestone_tabs_examples.rb b/spec/support/shared_examples/milestone_tabs_examples.rb index 8b757586941..94808a31ed3 100644 --- a/spec/support/shared_examples/milestone_tabs_examples.rb +++ b/spec/support/shared_examples/milestone_tabs_examples.rb @@ -1,83 +1,83 @@ -shared_examples 'milestone tabs' do +shared_examples "milestone tabs" do def go(path, extra_params = {}) params = case milestone when DashboardMilestone - { id: milestone.safe_title, title: milestone.title } + {id: milestone.safe_title, title: milestone.title} when GroupMilestone - { group_id: group.to_param, id: milestone.safe_title, title: milestone.title } + {group_id: group.to_param, id: milestone.safe_title, title: milestone.title} else - { namespace_id: project.namespace.to_param, project_id: project, id: milestone.iid } + {namespace_id: project.namespace.to_param, project_id: project, id: milestone.iid} end get path, params: params.merge(extra_params) end - describe '#merge_requests' do - context 'as html' do + describe "#merge_requests" do + context "as html" do before do - go(:merge_requests, format: 'html') + go(:merge_requests, format: "html") end - it 'redirects to milestone#show' do + it "redirects to milestone#show" do expect(response).to redirect_to(milestone_path) end end - context 'as json' do + context "as json" do before do - go(:merge_requests, format: 'json') + go(:merge_requests, format: "json") end - it 'renders the merge requests tab template to a string' do - expect(response).to render_template('shared/milestones/_merge_requests_tab') - expect(json_response).to have_key('html') + it "renders the merge requests tab template to a string" do + expect(response).to render_template("shared/milestones/_merge_requests_tab") + expect(json_response).to have_key("html") end end end - describe '#participants' do - context 'as html' do + describe "#participants" do + context "as html" do before do - go(:participants, format: 'html') + go(:participants, format: "html") end - it 'redirects to milestone#show' do + it "redirects to milestone#show" do expect(response).to redirect_to(milestone_path) end end - context 'as json' do + context "as json" do before do - go(:participants, format: 'json') + go(:participants, format: "json") end - it 'renders the participants tab template to a string' do - expect(response).to render_template('shared/milestones/_participants_tab') - expect(json_response).to have_key('html') + it "renders the participants tab template to a string" do + expect(response).to render_template("shared/milestones/_participants_tab") + expect(json_response).to have_key("html") end end end - describe '#labels' do - context 'as html' do + describe "#labels" do + context "as html" do before do - go(:labels, format: 'html') + go(:labels, format: "html") end - it 'redirects to milestone#show' do + it "redirects to milestone#show" do expect(response).to redirect_to(milestone_path) end end - context 'as json' do + context "as json" do before do - go(:labels, format: 'json') + go(:labels, format: "json") end - it 'renders the labels tab template to a string' do - expect(response).to render_template('shared/milestones/_labels_tab') - expect(json_response).to have_key('html') + it "renders the labels tab template to a string" do + expect(response).to render_template("shared/milestones/_labels_tab") + expect(json_response).to have_key("html") end end end diff --git a/spec/support/shared_examples/models/atomic_internal_id_spec.rb b/spec/support/shared_examples/models/atomic_internal_id_spec.rb index c659be8f13a..1e6ec25ece1 100644 --- a/spec/support/shared_examples/models/atomic_internal_id_spec.rb +++ b/spec/support/shared_examples/models/atomic_internal_id_spec.rb @@ -1,53 +1,53 @@ -require 'spec_helper' +require "spec_helper" -shared_examples_for 'AtomicInternalId' do |validate_presence: true| - describe '.has_internal_id' do - describe 'Module inclusion' do +shared_examples_for "AtomicInternalId" do |validate_presence: true| + describe ".has_internal_id" do + describe "Module inclusion" do subject { described_class } it { is_expected.to include_module(AtomicInternalId) } end - describe 'Validation' do + describe "Validation" do before do allow_any_instance_of(described_class).to receive(:"ensure_#{scope}_#{internal_id_attribute}!") instance.valid? end - context 'when presence validation is required' do + context "when presence validation is required" do before do skip unless validate_presence end - it 'validates presence' do + it "validates presence" do expect(instance.errors[internal_id_attribute]).to include("can't be blank") end end - context 'when presence validation is not required' do + context "when presence validation is not required" do before do skip if validate_presence end - it 'does not validate presence' do + it "does not validate presence" do expect(instance.errors[internal_id_attribute]).to be_empty end end end - describe 'Creating an instance' do + describe "Creating an instance" do subject { instance.save! } - it 'saves a new instance properly' do + it "saves a new instance properly" do expect { subject }.not_to raise_error end end - describe 'internal id generation' do + describe "internal id generation" do subject { instance.save! } - it 'calls InternalId.generate_next and sets internal id attribute' do + it "calls InternalId.generate_next and sets internal id attribute" do iid = rand(1..1000) expect(InternalId).to receive(:generate_next).with(instance, scope_attrs, usage, any_args).and_return(iid) @@ -55,16 +55,16 @@ shared_examples_for 'AtomicInternalId' do |validate_presence: true| expect(instance.public_send(internal_id_attribute)).to eq(iid) end - it 'does not overwrite an existing internal id' do + it "does not overwrite an existing internal id" do instance.public_send("#{internal_id_attribute}=", 4711) expect { subject }.not_to change { instance.public_send(internal_id_attribute) } end - context 'when the instance has an internal ID set' do + context "when the instance has an internal ID set" do let(:internal_id) { 9001 } - it 'calls InternalId.update_last_value and sets the `last_value` to that of the instance' do + it "calls InternalId.update_last_value and sets the `last_value` to that of the instance" do instance.send("#{internal_id_attribute}=", internal_id) expect(InternalId) diff --git a/spec/support/shared_examples/models/chat_service_spec.rb b/spec/support/shared_examples/models/chat_service_spec.rb index cf1d52a9616..fae1c4fc363 100644 --- a/spec/support/shared_examples/models/chat_service_spec.rb +++ b/spec/support/shared_examples/models/chat_service_spec.rb @@ -90,7 +90,7 @@ shared_examples_for "chat service" do |service_name| end context "with issue events" do - let(:opts) { { title: "Awesome issue", description: "please fix" } } + let(:opts) { {title: "Awesome issue", description: "please fix"} } let(:sample_data) do service = Issues::CreateService.new(project, user, opts) issue = service.execute @@ -106,7 +106,7 @@ shared_examples_for "chat service" do |service_name| title: "Awesome merge_request", description: "please fix", source_branch: "feature", - target_branch: "master" + target_branch: "master", } end @@ -129,7 +129,7 @@ shared_examples_for "chat service" do |service_name| title: "Awesome wiki_page", content: "Some text describing some thing or another", format: "md", - message: "user created page: Awesome wiki_page" + message: "user created page: Awesome wiki_page", } end let(:wiki_page) { create(:wiki_page, wiki: project.wiki, attrs: opts) } @@ -144,10 +144,10 @@ shared_examples_for "chat service" do |service_name| context "with commit comment" do let(:note) do create(:note_on_commit, - author: user, - project: project, - commit_id: project.repository.commit.id, - note: "a comment on a commit") + author: user, + project: project, + commit_id: project.repository.commit.id, + note: "a comment on a commit") end it_behaves_like "#{service_name} service" @@ -181,8 +181,8 @@ shared_examples_for "chat service" do |service_name| context "with pipeline events" do let(:pipeline) do create(:ci_pipeline, - project: project, status: status, - sha: project.commit.sha, ref: project.default_branch) + project: project, status: status, + sha: project.commit.sha, ref: project.default_branch) end let(:sample_data) { Gitlab::DataBuilder::Pipeline.build(pipeline) } diff --git a/spec/support/shared_examples/models/cluster_application_core_shared_examples.rb b/spec/support/shared_examples/models/cluster_application_core_shared_examples.rb index 1f76b981292..6a0c524b4f8 100644 --- a/spec/support/shared_examples/models/cluster_application_core_shared_examples.rb +++ b/spec/support/shared_examples/models/cluster_application_core_shared_examples.rb @@ -1,13 +1,13 @@ -shared_examples 'cluster application core specs' do |application_name| +shared_examples "cluster application core specs" do |application_name| it { is_expected.to belong_to(:cluster) } it { is_expected.to validate_presence_of(:cluster) } - describe '#name' do - it 'is .application_name' do + describe "#name" do + it "is .application_name" do expect(subject.name).to eq(described_class.application_name) end - it 'is recorded in Clusters::Cluster::APPLICATIONS' do + it "is recorded in Clusters::Cluster::APPLICATIONS" do expect(Clusters::Cluster::APPLICATIONS[subject.name]).to eq(described_class) end end diff --git a/spec/support/shared_examples/models/cluster_application_helm_cert_examples.rb b/spec/support/shared_examples/models/cluster_application_helm_cert_examples.rb index d87b3181e80..061e91820b6 100644 --- a/spec/support/shared_examples/models/cluster_application_helm_cert_examples.rb +++ b/spec/support/shared_examples/models/cluster_application_helm_cert_examples.rb @@ -1,20 +1,20 @@ -shared_examples 'cluster application helm specs' do |application_name| +shared_examples "cluster application helm specs" do |application_name| let(:application) { create(application_name) } - describe '#files' do + describe "#files" do subject { application.files } - context 'when the helm application does not have a ca_cert' do + context "when the helm application does not have a ca_cert" do before do application.cluster.application_helm.ca_cert = nil end - it 'should not include cert files when there is no ca_cert entry' do + it "should not include cert files when there is no ca_cert entry" do expect(subject).not_to include(:'ca.pem', :'cert.pem', :'key.pem') end end - it 'should include cert files when there is a ca_cert entry' do + it "should include cert files when there is a ca_cert entry" do expect(subject).to include(:'ca.pem', :'cert.pem', :'key.pem') expect(subject[:'ca.pem']).to eq(application.cluster.application_helm.ca_cert) diff --git a/spec/support/shared_examples/models/cluster_application_initial_status.rb b/spec/support/shared_examples/models/cluster_application_initial_status.rb index 9775d87953c..79e1e664215 100644 --- a/spec/support/shared_examples/models/cluster_application_initial_status.rb +++ b/spec/support/shared_examples/models/cluster_application_initial_status.rb @@ -1,27 +1,27 @@ # frozen_string_literal: true -shared_examples 'cluster application initial status specs' do - describe '#status' do +shared_examples "cluster application initial status specs" do + describe "#status" do let(:cluster) { create(:cluster, :provided_by_gcp) } subject { described_class.new(cluster: cluster) } - context 'when application helm is scheduled' do + context "when application helm is scheduled" do before do create(:clusters_applications_helm, :scheduled, cluster: cluster) end - it 'defaults to :not_installable' do + it "defaults to :not_installable" do expect(subject.status_name).to be(:not_installable) end end - context 'when application is scheduled' do + context "when application is scheduled" do before do create(:clusters_applications_helm, :installed, cluster: cluster) end - it 'sets a default status' do + it "sets a default status" do expect(subject.status_name).to be(:installable) end end diff --git a/spec/support/shared_examples/models/cluster_application_status_shared_examples.rb b/spec/support/shared_examples/models/cluster_application_status_shared_examples.rb index b8c19cab0c4..1d62caffc07 100644 --- a/spec/support/shared_examples/models/cluster_application_status_shared_examples.rb +++ b/spec/support/shared_examples/models/cluster_application_status_shared_examples.rb @@ -1,15 +1,15 @@ -shared_examples 'cluster application status specs' do |application_name| - describe '#status' do +shared_examples "cluster application status specs" do |application_name| + describe "#status" do let(:cluster) { create(:cluster, :provided_by_gcp) } subject { described_class.new(cluster: cluster) } - it 'sets a default status' do + it "sets a default status" do expect(subject.status_name).to be(:not_installable) end end - describe '.available' do + describe ".available" do subject { described_class.available } let!(:installed_cluster) { create(application_name, :installed) } @@ -22,28 +22,28 @@ shared_examples 'cluster application status specs' do |application_name| it { is_expected.to contain_exactly(installed_cluster, updated_cluster) } end - describe 'status state machine' do - describe '#make_installing' do + describe "status state machine" do + describe "#make_installing" do subject { create(application_name, :scheduled) } - it 'is installing' do + it "is installing" do subject.make_installing! expect(subject).to be_installing end end - describe '#make_installed' do + describe "#make_installed" do subject { create(application_name, :installing) } - it 'is installed' do + it "is installed" do subject.make_installed! expect(subject).to be_installed end - it 'updates helm version' do - subject.cluster.application_helm.update!(version: '1.2.3') + it "updates helm version" do + subject.cluster.application_helm.update!(version: "1.2.3") subject.make_installed! @@ -52,8 +52,8 @@ shared_examples 'cluster application status specs' do |application_name| expect(subject.cluster.application_helm.version).to eq(Gitlab::Kubernetes::Helm::HELM_VERSION) end - it 'sets the correct version of the application' do - subject.update!(version: '0.0.0') + it "sets the correct version of the application" do + subject.update!(version: "0.0.0") subject.make_installed! @@ -62,17 +62,17 @@ shared_examples 'cluster application status specs' do |application_name| expect(subject.version).to eq(subject.class.const_get(:VERSION)) end - context 'application is updating' do + context "application is updating" do subject { create(application_name, :updating) } - it 'is updated' do + it "is updated" do subject.make_installed! expect(subject).to be_updated end - it 'updates helm version' do - subject.cluster.application_helm.update!(version: '1.2.3') + it "updates helm version" do + subject.cluster.application_helm.update!(version: "1.2.3") subject.make_installed! @@ -81,8 +81,8 @@ shared_examples 'cluster application status specs' do |application_name| expect(subject.cluster.application_helm.version).to eq(Gitlab::Kubernetes::Helm::HELM_VERSION) end - it 'updates the version of the application' do - subject.update!(version: '0.0.0') + it "updates the version of the application" do + subject.update!(version: "0.0.0") subject.make_installed! @@ -93,21 +93,21 @@ shared_examples 'cluster application status specs' do |application_name| end end - describe '#make_errored' do + describe "#make_errored" do subject { create(application_name, :installing) } - let(:reason) { 'some errors' } + let(:reason) { "some errors" } - it 'is errored' do + it "is errored" do subject.make_errored(reason) expect(subject).to be_errored expect(subject.status_reason).to eq(reason) end - context 'application is updating' do + context "application is updating" do subject { create(application_name, :updating) } - it 'is update_errored' do + it "is update_errored" do subject.make_errored(reason) expect(subject).to be_update_errored @@ -116,19 +116,19 @@ shared_examples 'cluster application status specs' do |application_name| end end - describe '#make_scheduled' do + describe "#make_scheduled" do subject { create(application_name, :installable) } - it 'is scheduled' do + it "is scheduled" do subject.make_scheduled expect(subject).to be_scheduled end - describe 'when was errored' do + describe "when was errored" do subject { create(application_name, :errored) } - it 'clears #status_reason' do + it "clears #status_reason" do expect(subject.status_reason).not_to be_nil subject.make_scheduled! @@ -137,10 +137,10 @@ shared_examples 'cluster application status specs' do |application_name| end end - describe 'when was updated_errored' do + describe "when was updated_errored" do subject { create(application_name, :update_errored) } - it 'clears #status_reason' do + it "clears #status_reason" do expect(subject.status_reason).not_to be_nil subject.make_scheduled! @@ -151,7 +151,7 @@ shared_examples 'cluster application status specs' do |application_name| end end - describe '#available?' do + describe "#available?" do using RSpec::Parameterized::TableSyntax where(:trait, :available) do diff --git a/spec/support/shared_examples/models/cluster_application_version_shared_examples.rb b/spec/support/shared_examples/models/cluster_application_version_shared_examples.rb index 181b102e685..fdd905eb955 100644 --- a/spec/support/shared_examples/models/cluster_application_version_shared_examples.rb +++ b/spec/support/shared_examples/models/cluster_application_version_shared_examples.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -shared_examples 'cluster application version specs' do |application_name| - describe 'update_available?' do - let(:version) { '0.0.0' } +shared_examples "cluster application version specs" do |application_name| + describe "update_available?" do + let(:version) { "0.0.0" } subject { create(application_name, :installed, version: version).update_available? } - context 'version is not the same as VERSION' do + context "version is not the same as VERSION" do it { is_expected.to be_truthy } end - context 'version is the same as VERSION' do + context "version is the same as VERSION" do let(:application) { build(application_name) } let(:version) { application.class.const_get(:VERSION) } diff --git a/spec/support/shared_examples/models/issuable_hook_data_shared_examples.rb b/spec/support/shared_examples/models/issuable_hook_data_shared_examples.rb index a4762b68858..2e690db7ab0 100644 --- a/spec/support/shared_examples/models/issuable_hook_data_shared_examples.rb +++ b/spec/support/shared_examples/models/issuable_hook_data_shared_examples.rb @@ -1,14 +1,14 @@ # This shared example requires a `builder` and `user` variable -shared_examples 'issuable hook data' do |kind| +shared_examples "issuable hook data" do |kind| let(:data) { builder.build(user: user) } - include_examples 'project hook data' do + include_examples "project hook data" do let(:project) { builder.issuable.project } end - include_examples 'deprecated repository hook data' + include_examples "deprecated repository hook data" context "with a #{kind}" do - it 'contains issuable data' do + it "contains issuable data" do expect(data[:object_kind]).to eq(kind) expect(data[:user]).to eq(user.hook_attrs) expect(data[:project]).to eq(builder.issuable.project.hook_attrs) @@ -17,40 +17,40 @@ shared_examples 'issuable hook data' do |kind| expect(data[:repository]).to eq(builder.issuable.project.hook_attrs.slice(:name, :url, :description, :homepage)) end - it 'does not contain certain keys' do + it "does not contain certain keys" do expect(data).not_to have_key(:assignees) expect(data).not_to have_key(:assignee) end - describe 'changes are given' do + describe "changes are given" do let(:changes) do { cached_markdown_version: %w[foo bar], - description: ['A description', 'A cool description'], + description: ["A description", "A cool description"], description_html: %w[foo bar], in_progress_merge_commit_sha: %w[foo bar], lock_version: %w[foo bar], merge_jid: %w[foo bar], - title: ['A title', 'Hello World'], - title_html: %w[foo bar] + title: ["A title", "Hello World"], + title_html: %w[foo bar], } end let(:data) { builder.build(user: user, changes: changes) } - it 'populates the :changes hash' do + it "populates the :changes hash" do expect(data[:changes]).to match(hash_including({ - title: { previous: 'A title', current: 'Hello World' }, - description: { previous: 'A description', current: 'A cool description' } + title: {previous: "A title", current: "Hello World"}, + description: {previous: "A description", current: "A cool description"}, })) end - it 'does not contain certain keys' do - expect(data[:changes]).not_to have_key('cached_markdown_version') - expect(data[:changes]).not_to have_key('description_html') - expect(data[:changes]).not_to have_key('lock_version') - expect(data[:changes]).not_to have_key('title_html') - expect(data[:changes]).not_to have_key('in_progress_merge_commit_sha') - expect(data[:changes]).not_to have_key('merge_jid') + it "does not contain certain keys" do + expect(data[:changes]).not_to have_key("cached_markdown_version") + expect(data[:changes]).not_to have_key("description_html") + expect(data[:changes]).not_to have_key("lock_version") + expect(data[:changes]).not_to have_key("title_html") + expect(data[:changes]).not_to have_key("in_progress_merge_commit_sha") + expect(data[:changes]).not_to have_key("merge_jid") end end end diff --git a/spec/support/shared_examples/models/label_note_shared_examples.rb b/spec/support/shared_examples/models/label_note_shared_examples.rb index 406385c13bd..7b45b466a2c 100644 --- a/spec/support/shared_examples/models/label_note_shared_examples.rb +++ b/spec/support/shared_examples/models/label_note_shared_examples.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true -shared_examples 'label note created from events' do +shared_examples "label note created from events" do def create_event(params = {}) - event_params = { action: :add, label: label, user: user } + event_params = {action: :add, label: label, user: user} resource_key = resource.class.name.underscore.to_s event_params[resource_key] = resource @@ -12,14 +12,14 @@ shared_examples 'label note created from events' do def label_refs(events) labels = events.map(&:label).compact - labels.map { |l| l.to_reference}.sort.join(' ') + labels.map { |l| l.to_reference}.sort.join(" ") end let(:time) { Time.now } let(:local_label_ids) { [label.id, label2.id] } - describe '.from_events' do - it 'returns system note with expected attributes' do + describe ".from_events" do + it "returns system note with expected attributes" do event = create_event note = described_class.from_events([event, create_event]) @@ -32,7 +32,7 @@ shared_examples 'label note created from events' do expect(note.note_html).to be_present end - it 'updates markdown cache if reference is not set yet' do + it "updates markdown cache if reference is not set yet" do event = create_event(reference: nil) described_class.from_events([event]) @@ -40,15 +40,15 @@ shared_examples 'label note created from events' do expect(event.reference).not_to be_nil end - it 'updates markdown cache if label was deleted' do - event = create_event(reference: 'some_ref', label: nil) + it "updates markdown cache if label was deleted" do + event = create_event(reference: "some_ref", label: nil) described_class.from_events([event]) - expect(event.reference).to eq '' + expect(event.reference).to eq "" end - it 'returns html note' do + it "returns html note" do events = [create_event(created_at: time)] note = described_class.from_events(events) @@ -56,39 +56,39 @@ shared_examples 'label note created from events' do expect(note.note_html).to include label.title end - it 'returns text note for added labels' do + it "returns text note for added labels" do events = [create_event(created_at: time), create_event(created_at: time, label: label2), - create_event(created_at: time, label: nil)] + create_event(created_at: time, label: nil),] note = described_class.from_events(events) expect(note.note).to eq "added #{label_refs(events)} + 1 deleted label" end - it 'returns text note for removed labels' do + it "returns text note for removed labels" do events = [create_event(action: :remove, created_at: time), create_event(action: :remove, created_at: time, label: label2), - create_event(action: :remove, created_at: time, label: nil)] + create_event(action: :remove, created_at: time, label: nil),] note = described_class.from_events(events) expect(note.note).to eq "removed #{label_refs(events)} + 1 deleted label" end - it 'returns text note for added and removed labels' do + it "returns text note for added and removed labels" do add_events = [create_event(created_at: time), - create_event(created_at: time, label: nil)] + create_event(created_at: time, label: nil),] remove_events = [create_event(action: :remove, created_at: time), - create_event(action: :remove, created_at: time, label: nil)] + create_event(action: :remove, created_at: time, label: nil),] note = described_class.from_events(add_events + remove_events) expect(note.note).to eq "added #{label_refs(add_events)} + 1 deleted label and removed #{label_refs(remove_events)} + 1 deleted label" end - it 'returns text note for cross-project label' do + it "returns text note for cross-project label" do other_label = create(:label) event = create_event(label: other_label) @@ -97,7 +97,7 @@ shared_examples 'label note created from events' do expect(note.note).to eq "added #{other_label.to_reference(resource_parent)} label" end - it 'returns text note for cross-group label' do + it "returns text note for cross-group label" do other_label = create(:group_label) event = create_event(label: other_label) diff --git a/spec/support/shared_examples/models/member_shared_examples.rb b/spec/support/shared_examples/models/member_shared_examples.rb index 77376496854..510dbf4a593 100644 --- a/spec/support/shared_examples/models/member_shared_examples.rb +++ b/spec/support/shared_examples/models/member_shared_examples.rb @@ -1,35 +1,35 @@ # frozen_string_literal: true -shared_examples_for 'inherited access level as a member of entity' do +shared_examples_for "inherited access level as a member of entity" do let(:parent_entity) { create(:group) } let(:user) { create(:user) } let(:member) { entity.is_a?(Group) ? entity.group_member(user) : entity.project_member(user) } - context 'with root parent_entity developer member' do + context "with root parent_entity developer member" do before do parent_entity.add_developer(user) end - it 'is allowed to be a maintainer of the entity' do + it "is allowed to be a maintainer of the entity" do entity.add_maintainer(user) expect(member.access_level).to eq(Gitlab::Access::MAINTAINER) end - it 'is not allowed to be a reporter of the entity' do + it "is not allowed to be a reporter of the entity" do entity.add_reporter(user) expect(member).to be_nil end - it 'is allowed to change to be a developer of the entity' do + it "is allowed to change to be a developer of the entity" do entity.add_maintainer(user) expect { member.update(access_level: Gitlab::Access::DEVELOPER) } .to change { member.access_level }.to(Gitlab::Access::DEVELOPER) end - it 'is not allowed to change to be a guest of the entity' do + it "is not allowed to change to be a guest of the entity" do entity.add_maintainer(user) expect { member.update(access_level: Gitlab::Access::GUEST) } @@ -44,7 +44,7 @@ shared_examples_for 'inherited access level as a member of entity' do expect(member.errors.full_messages).to eq(["Access level should be higher than Developer inherited membership from group #{parent_entity.name}"]) end - it 'allows changing the level from a non existing member' do + it "allows changing the level from a non existing member" do non_member_user = create(:user) entity.add_maintainer(non_member_user) @@ -57,19 +57,19 @@ shared_examples_for 'inherited access level as a member of entity' do end end -shared_examples_for '#valid_level_roles' do |entity_name| +shared_examples_for "#valid_level_roles" do |entity_name| let(:member_user) { create(:user) } let(:group) { create(:group) } let(:entity) { create(entity_name) } let(:entity_member) { create("#{entity_name}_member", :developer, source: entity, user: member_user) } let(:presenter) { described_class.new(entity_member, current_user: member_user) } - let(:expected_roles) { { 'Developer' => 30, 'Maintainer' => 40, 'Reporter' => 20 } } + let(:expected_roles) { {"Developer" => 30, "Maintainer" => 40, "Reporter" => 20} } - it 'returns all roles when no parent member is present' do + it "returns all roles when no parent member is present" do expect(presenter.valid_level_roles).to eq(entity_member.class.access_level_roles) end - it 'returns higher roles when a parent member is present' do + it "returns higher roles when a parent member is present" do group.add_reporter(member_user) expect(presenter.valid_level_roles).to eq(expected_roles) diff --git a/spec/support/shared_examples/models/members_notifications_shared_example.rb b/spec/support/shared_examples/models/members_notifications_shared_example.rb index ef5cea3f2a5..e09e1bb772e 100644 --- a/spec/support/shared_examples/models/members_notifications_shared_example.rb +++ b/spec/support/shared_examples/models/members_notifications_shared_example.rb @@ -1,5 +1,5 @@ -RSpec.shared_examples 'members notifications' do |entity_type| - let(:notification_service) { double('NotificationService').as_null_object } +RSpec.shared_examples "members notifications" do |entity_type| + let(:notification_service) { double("NotificationService").as_null_object } before do allow(member).to receive(:notification_service).and_return(notification_service) @@ -31,7 +31,7 @@ RSpec.shared_examples 'members notifications' do |entity_type| end end - describe '#accept_request' do + describe "#accept_request" do let(:member) { create(:"#{entity_type}_member", :access_request) } it "calls NotificationService.new_#{entity_type}_member" do diff --git a/spec/support/shared_examples/models/project_hook_data_shared_examples.rb b/spec/support/shared_examples/models/project_hook_data_shared_examples.rb index f0264878811..0e0cd71ecad 100644 --- a/spec/support/shared_examples/models/project_hook_data_shared_examples.rb +++ b/spec/support/shared_examples/models/project_hook_data_shared_examples.rb @@ -1,5 +1,5 @@ -shared_examples 'project hook data with deprecateds' do |project_key: :project| - it 'contains project data' do +shared_examples "project hook data with deprecateds" do |project_key: :project| + it "contains project data" do expect(data[project_key][:name]).to eq(project.name) expect(data[project_key][:description]).to eq(project.description) expect(data[project_key][:web_url]).to eq(project.web_url) @@ -17,8 +17,8 @@ shared_examples 'project hook data with deprecateds' do |project_key: :project| end end -shared_examples 'project hook data' do |project_key: :project| - it 'contains project data' do +shared_examples "project hook data" do |project_key: :project| + it "contains project data" do expect(data[project_key][:name]).to eq(project.name) expect(data[project_key][:description]).to eq(project.description) expect(data[project_key][:web_url]).to eq(project.web_url) @@ -32,8 +32,8 @@ shared_examples 'project hook data' do |project_key: :project| end end -shared_examples 'deprecated repository hook data' do - it 'contains deprecated repository data' do +shared_examples "deprecated repository hook data" do + it "contains deprecated repository data" do expect(data[:repository][:name]).to eq(project.name) expect(data[:repository][:description]).to eq(project.description) expect(data[:repository][:url]).to eq(project.url_to_repo) diff --git a/spec/support/shared_examples/models/with_uploads_shared_examples.rb b/spec/support/shared_examples/models/with_uploads_shared_examples.rb index 43033a2d256..c8c965ff2d2 100644 --- a/spec/support/shared_examples/models/with_uploads_shared_examples.rb +++ b/spec/support/shared_examples/models/with_uploads_shared_examples.rb @@ -1,44 +1,44 @@ -require 'spec_helper' +require "spec_helper" -shared_examples_for 'model with uploads' do |supports_fileuploads| - describe '.destroy' do +shared_examples_for "model with uploads" do |supports_fileuploads| + describe ".destroy" do before do stub_uploads_object_storage(uploader_class) model_object.public_send(upload_attribute).migrate!(ObjectStorage::Store::REMOTE) end - context 'with mounted uploader' do - it 'deletes remote uploads' do + context "with mounted uploader" do + it "deletes remote uploads" do expect_any_instance_of(CarrierWave::Storage::Fog::File).to receive(:delete).and_call_original expect { model_object.destroy }.to change { Upload.count }.by(-1) end end - context 'with not mounted uploads', :sidekiq, skip: !supports_fileuploads do - context 'with local files' do + context "with not mounted uploads", :sidekiq, skip: !supports_fileuploads do + context "with local files" do let!(:uploads) { create_list(:upload, 2, uploader: FileUploader, model: model_object) } - it 'deletes any FileUploader uploads which are not mounted' do + it "deletes any FileUploader uploads which are not mounted" do expect { model_object.destroy }.to change { Upload.count }.by(-3) end - it 'deletes local files' do + it "deletes local files" do expect_any_instance_of(Uploads::Local).to receive(:delete_keys).with(uploads.map(&:absolute_path)) model_object.destroy end end - context 'with remote files' do + context "with remote files" do let!(:uploads) { create_list(:upload, 2, :object_storage, uploader: FileUploader, model: model_object) } - it 'deletes any FileUploader uploads which are not mounted' do + it "deletes any FileUploader uploads which are not mounted" do expect { model_object.destroy }.to change { Upload.count }.by(-3) end - it 'deletes remote files' do + it "deletes remote files" do expect_any_instance_of(Uploads::Fog).to receive(:delete_keys).with(uploads.map(&:path)) model_object.destroy diff --git a/spec/support/shared_examples/notify_shared_examples.rb b/spec/support/shared_examples/notify_shared_examples.rb index 4fff1c4e228..86062c40003 100644 --- a/spec/support/shared_examples/notify_shared_examples.rb +++ b/spec/support/shared_examples/notify_shared_examples.rb @@ -1,11 +1,11 @@ -shared_context 'gitlab email notification' do - set(:project) { create(:project, :repository, name: 'a-known-name') } - set(:recipient) { create(:user, email: 'recipient@example.com') } +shared_context "gitlab email notification" do + set(:project) { create(:project, :repository, name: "a-known-name") } + set(:recipient) { create(:user, email: "recipient@example.com") } let(:gitlab_sender_display_name) { Gitlab.config.gitlab.email_display_name } let(:gitlab_sender) { Gitlab.config.gitlab.email_from } let(:gitlab_sender_reply_to) { Gitlab.config.gitlab.email_reply_to } - let(:new_user_address) { 'newguy@example.com' } + let(:new_user_address) { "newguy@example.com" } before do email = recipient.emails.create(email: "notifications@example.com") @@ -14,20 +14,20 @@ shared_context 'gitlab email notification' do end end -shared_context 'reply-by-email is enabled with incoming address without %{key}' do +shared_context "reply-by-email is enabled with incoming address without %{key}" do before do stub_incoming_email_setting(enabled: true, address: "reply@#{Gitlab.config.gitlab.host}") end end -shared_examples 'a multiple recipients email' do - it 'is sent to the given recipient' do +shared_examples "a multiple recipients email" do + it "is sent to the given recipient" do is_expected.to deliver_to recipient.notification_email end end -shared_examples 'an email sent from GitLab' do - it 'has the characteristics of an email sent from GitLab' do +shared_examples "an email sent from GitLab" do + it "has the characteristics of an email sent from GitLab" do sender = subject.header[:from].addrs[0] reply_to = subject.header[:reply_to].addresses @@ -39,192 +39,192 @@ shared_examples 'an email sent from GitLab' do end end -shared_examples 'an email that contains a header with author username' do - it 'has X-GitLab-Author header containing author\'s username' do - is_expected.to have_header 'X-GitLab-Author', user.username +shared_examples "an email that contains a header with author username" do + it "has X-GitLab-Author header containing author's username" do + is_expected.to have_header "X-GitLab-Author", user.username end end -shared_examples 'an email with X-GitLab headers containing IDs' do - it 'has X-GitLab-*-ID header' do - is_expected.to have_header "X-GitLab-#{model.class.name}-ID", "#{model.id}" +shared_examples "an email with X-GitLab headers containing IDs" do + it "has X-GitLab-*-ID header" do + is_expected.to have_header "X-GitLab-#{model.class.name}-ID", model.id.to_s end - it 'has X-GitLab-*-IID header if model has iid defined' do + it "has X-GitLab-*-IID header if model has iid defined" do if model.respond_to?(:iid) - is_expected.to have_header "X-GitLab-#{model.class.name}-IID", "#{model.iid}" + is_expected.to have_header "X-GitLab-#{model.class.name}-IID", model.iid.to_s else expect(subject.header["X-GitLab-#{model.class.name}-IID"]).to eq nil end end end -shared_examples 'an email with X-GitLab headers containing project details' do - it 'has X-GitLab-Project headers' do +shared_examples "an email with X-GitLab headers containing project details" do + it "has X-GitLab-Project headers" do aggregate_failures do full_path_as_domain = "#{project.name}.#{project.namespace.path}" - is_expected.to have_header('X-GitLab-Project', /#{project.name}/) - is_expected.to have_header('X-GitLab-Project-Id', /#{project.id}/) - is_expected.to have_header('X-GitLab-Project-Path', /#{project.full_path}/) - is_expected.to have_header('List-Id', "#{project.full_path} <#{project.id}.#{full_path_as_domain}.#{Gitlab.config.gitlab.host}>") + is_expected.to have_header("X-GitLab-Project", /#{project.name}/) + is_expected.to have_header("X-GitLab-Project-Id", /#{project.id}/) + is_expected.to have_header("X-GitLab-Project-Path", /#{project.full_path}/) + is_expected.to have_header("List-Id", "#{project.full_path} <#{project.id}.#{full_path_as_domain}.#{Gitlab.config.gitlab.host}>") end end end -shared_examples 'a new thread email with reply-by-email enabled' do - it 'has the characteristics of a threaded email' do +shared_examples "a new thread email with reply-by-email enabled" do + it "has the characteristics of a threaded email" do host = Gitlab.config.gitlab.host route_key = "#{model.class.model_name.singular_route_key}_#{model.id}" aggregate_failures do - is_expected.to have_header('Message-ID', "<#{route_key}@#{host}>") - is_expected.to have_header('References', /\A<reply\-.*@#{host}>\Z/ ) + is_expected.to have_header("Message-ID", "<#{route_key}@#{host}>") + is_expected.to have_header("References", /\A<reply\-.*@#{host}>\Z/) end end end -shared_examples 'a thread answer email with reply-by-email enabled' do - include_examples 'an email with X-GitLab headers containing project details' - include_examples 'an email with X-GitLab headers containing IDs' +shared_examples "a thread answer email with reply-by-email enabled" do + include_examples "an email with X-GitLab headers containing project details" + include_examples "an email with X-GitLab headers containing IDs" - it 'has the characteristics of a threaded reply' do + it "has the characteristics of a threaded reply" do host = Gitlab.config.gitlab.host route_key = "#{model.class.model_name.singular_route_key}_#{model.id}" aggregate_failures do - is_expected.to have_header('Message-ID', /\A<.*@#{host}>\Z/) - is_expected.to have_header('In-Reply-To', "<#{route_key}@#{host}>") - is_expected.to have_header('References', /\A<reply\-.*@#{host}> <#{route_key}@#{host}>\Z/ ) + is_expected.to have_header("Message-ID", /\A<.*@#{host}>\Z/) + is_expected.to have_header("In-Reply-To", "<#{route_key}@#{host}>") + is_expected.to have_header("References", /\A<reply\-.*@#{host}> <#{route_key}@#{host}>\Z/) is_expected.to have_subject(/^Re: /) end end end -shared_examples 'an email starting a new thread with reply-by-email enabled' do - include_examples 'an email with X-GitLab headers containing project details' - include_examples 'an email with X-GitLab headers containing IDs' - include_examples 'a new thread email with reply-by-email enabled' +shared_examples "an email starting a new thread with reply-by-email enabled" do + include_examples "an email with X-GitLab headers containing project details" + include_examples "an email with X-GitLab headers containing IDs" + include_examples "a new thread email with reply-by-email enabled" it 'includes "Reply to this email directly or <View it on GitLab>"' do expect(subject.default_part.body).to include(%(Reply to this email directly or <a href="#{Gitlab::UrlBuilder.build(model)}">view it on GitLab</a>.)) end - context 'when reply-by-email is enabled with incoming address with %{key}' do - it 'has a Reply-To header' do - is_expected.to have_header 'Reply-To', /<reply+(.*)@#{Gitlab.config.gitlab.host}>\Z/ + context "when reply-by-email is enabled with incoming address with %{key}" do + it "has a Reply-To header" do + is_expected.to have_header "Reply-To", /<reply+(.*)@#{Gitlab.config.gitlab.host}>\Z/ end end - context 'when reply-by-email is enabled with incoming address without %{key}' do - include_context 'reply-by-email is enabled with incoming address without %{key}' - include_examples 'a new thread email with reply-by-email enabled' + context "when reply-by-email is enabled with incoming address without %{key}" do + include_context "reply-by-email is enabled with incoming address without %{key}" + include_examples "a new thread email with reply-by-email enabled" - it 'has a Reply-To header' do - is_expected.to have_header 'Reply-To', /<reply@#{Gitlab.config.gitlab.host}>\Z/ + it "has a Reply-To header" do + is_expected.to have_header "Reply-To", /<reply@#{Gitlab.config.gitlab.host}>\Z/ end end end -shared_examples 'an answer to an existing thread with reply-by-email enabled' do - include_examples 'an email with X-GitLab headers containing project details' - include_examples 'an email with X-GitLab headers containing IDs' - include_examples 'a thread answer email with reply-by-email enabled' +shared_examples "an answer to an existing thread with reply-by-email enabled" do + include_examples "an email with X-GitLab headers containing project details" + include_examples "an email with X-GitLab headers containing IDs" + include_examples "a thread answer email with reply-by-email enabled" - context 'when reply-by-email is enabled with incoming address with %{key}' do - it 'has a Reply-To header' do - is_expected.to have_header 'Reply-To', /<reply+(.*)@#{Gitlab.config.gitlab.host}>\Z/ + context "when reply-by-email is enabled with incoming address with %{key}" do + it "has a Reply-To header" do + is_expected.to have_header "Reply-To", /<reply+(.*)@#{Gitlab.config.gitlab.host}>\Z/ end end - context 'when reply-by-email is enabled with incoming address without %{key}' do - include_context 'reply-by-email is enabled with incoming address without %{key}' - include_examples 'a thread answer email with reply-by-email enabled' + context "when reply-by-email is enabled with incoming address without %{key}" do + include_context "reply-by-email is enabled with incoming address without %{key}" + include_examples "a thread answer email with reply-by-email enabled" - it 'has a Reply-To header' do - is_expected.to have_header 'Reply-To', /<reply@#{Gitlab.config.gitlab.host}>\Z/ + it "has a Reply-To header" do + is_expected.to have_header "Reply-To", /<reply@#{Gitlab.config.gitlab.host}>\Z/ end end end -shared_examples 'it should have Gmail Actions links' do +shared_examples "it should have Gmail Actions links" do it do aggregate_failures do is_expected.to have_body_text('<script type="application/ld+json">') - is_expected.to have_body_text('ViewAction') + is_expected.to have_body_text("ViewAction") end end end -shared_examples 'it should not have Gmail Actions links' do +shared_examples "it should not have Gmail Actions links" do it do aggregate_failures do is_expected.not_to have_body_text('<script type="application/ld+json">') - is_expected.not_to have_body_text('ViewAction') + is_expected.not_to have_body_text("ViewAction") end end end -shared_examples 'it should show Gmail Actions View Issue link' do - it_behaves_like 'it should have Gmail Actions links' +shared_examples "it should show Gmail Actions View Issue link" do + it_behaves_like "it should have Gmail Actions links" - it { is_expected.to have_body_text('View Issue') } + it { is_expected.to have_body_text("View Issue") } end -shared_examples 'it should show Gmail Actions View Merge request link' do - it_behaves_like 'it should have Gmail Actions links' +shared_examples "it should show Gmail Actions View Merge request link" do + it_behaves_like "it should have Gmail Actions links" - it { is_expected.to have_body_text('View Merge request') } + it { is_expected.to have_body_text("View Merge request") } end -shared_examples 'it should show Gmail Actions View Commit link' do - it_behaves_like 'it should have Gmail Actions links' +shared_examples "it should show Gmail Actions View Commit link" do + it_behaves_like "it should have Gmail Actions links" - it { is_expected.to have_body_text('View Commit') } + it { is_expected.to have_body_text("View Commit") } end -shared_examples 'an unsubscribeable thread' do - it_behaves_like 'an unsubscribeable thread with incoming address without %{key}' +shared_examples "an unsubscribeable thread" do + it_behaves_like "an unsubscribeable thread with incoming address without %{key}" - it 'has a List-Unsubscribe header in the correct format, and a body link' do + it "has a List-Unsubscribe header in the correct format, and a body link" do aggregate_failures do - is_expected.to have_header('List-Unsubscribe', /unsubscribe/) - is_expected.to have_header('List-Unsubscribe', /mailto/) - is_expected.to have_header('List-Unsubscribe', /^<.+,.+>$/) - is_expected.to have_body_text('unsubscribe') + is_expected.to have_header("List-Unsubscribe", /unsubscribe/) + is_expected.to have_header("List-Unsubscribe", /mailto/) + is_expected.to have_header("List-Unsubscribe", /^<.+,.+>$/) + is_expected.to have_body_text("unsubscribe") end end end -shared_examples 'an unsubscribeable thread with incoming address without %{key}' do - include_context 'reply-by-email is enabled with incoming address without %{key}' +shared_examples "an unsubscribeable thread with incoming address without %{key}" do + include_context "reply-by-email is enabled with incoming address without %{key}" - it 'has a List-Unsubscribe header in the correct format, and a body link' do + it "has a List-Unsubscribe header in the correct format, and a body link" do aggregate_failures do - is_expected.to have_header('List-Unsubscribe', /unsubscribe/) - is_expected.not_to have_header('List-Unsubscribe', /mailto/) - is_expected.to have_header('List-Unsubscribe', /^<[^,]+>$/) - is_expected.to have_body_text('unsubscribe') + is_expected.to have_header("List-Unsubscribe", /unsubscribe/) + is_expected.not_to have_header("List-Unsubscribe", /mailto/) + is_expected.to have_header("List-Unsubscribe", /^<[^,]+>$/) + is_expected.to have_body_text("unsubscribe") end end end -shared_examples 'a user cannot unsubscribe through footer link' do - it 'does not have a List-Unsubscribe header or a body link' do +shared_examples "a user cannot unsubscribe through footer link" do + it "does not have a List-Unsubscribe header or a body link" do aggregate_failures do - is_expected.not_to have_header('List-Unsubscribe', /unsubscribe/) - is_expected.not_to have_body_text('unsubscribe') + is_expected.not_to have_header("List-Unsubscribe", /unsubscribe/) + is_expected.not_to have_body_text("unsubscribe") end end end -shared_examples 'an email with a labels subscriptions link in its footer' do - it { is_expected.to have_body_text('label subscriptions') } +shared_examples "an email with a labels subscriptions link in its footer" do + it { is_expected.to have_body_text("label subscriptions") } end -shared_examples 'a note email' do - it_behaves_like 'it should have Gmail Actions links' +shared_examples "a note email" do + it_behaves_like "it should have Gmail Actions links" - it 'is sent to the given recipient as the author' do + it "is sent to the given recipient as the author" do sender = subject.header[:from].addrs[0] aggregate_failures do @@ -234,26 +234,26 @@ shared_examples 'a note email' do end end - it 'contains the message from the note' do + it "contains the message from the note" do is_expected.to have_body_text note.note end - it 'does not contain note author' do + it "does not contain note author" do is_expected.not_to have_body_text note.author_name end - context 'when enabled email_author_in_body' do + context "when enabled email_author_in_body" do before do stub_application_setting(email_author_in_body: true) end - it 'contains a link to note author' do + it "contains a link to note author" do is_expected.to have_body_text note.author_name end end end -shared_examples 'appearance header and footer enabled' do +shared_examples "appearance header and footer enabled" do it "contains header and footer" do create :appearance, header_message: "Foo", footer_message: "Bar", email_header_and_footer_enabled: true @@ -267,7 +267,7 @@ shared_examples 'appearance header and footer enabled' do end end -shared_examples 'appearance header and footer not enabled' do +shared_examples "appearance header and footer not enabled" do it "does not contain header and footer" do create :appearance, header_message: "Foo", footer_message: "Bar", email_header_and_footer_enabled: false diff --git a/spec/support/shared_examples/policies/clusterable_shared_examples.rb b/spec/support/shared_examples/policies/clusterable_shared_examples.rb index d99f94c76c3..fe82e8d46b9 100644 --- a/spec/support/shared_examples/policies/clusterable_shared_examples.rb +++ b/spec/support/shared_examples/policies/clusterable_shared_examples.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true -require 'spec_helper' +require "spec_helper" -shared_examples 'clusterable policies' do - describe '#add_cluster?' do +shared_examples "clusterable policies" do + describe "#add_cluster?" do let(:current_user) { create(:user) } subject { described_class.new(current_user, clusterable) } - context 'with a developer' do + context "with a developer" do before do clusterable.add_developer(current_user) end @@ -16,16 +16,16 @@ shared_examples 'clusterable policies' do it { expect_disallowed(:add_cluster) } end - context 'with a maintainer' do + context "with a maintainer" do before do clusterable.add_maintainer(current_user) end - context 'with no clusters' do + context "with no clusters" do it { expect_allowed(:add_cluster) } end - context 'with an existing cluster' do + context "with an existing cluster" do before do cluster end diff --git a/spec/support/shared_examples/position_formatters.rb b/spec/support/shared_examples/position_formatters.rb index ffc9456dbc7..2e794f94290 100644 --- a/spec/support/shared_examples/position_formatters.rb +++ b/spec/support/shared_examples/position_formatters.rb @@ -1,7 +1,7 @@ shared_examples_for "position formatter" do let(:formatter) { described_class.new(attrs) } - describe '#key' do + describe "#key" do let(:key) { [123, 456, 789, Digest::SHA1.hexdigest(formatter.old_path), Digest::SHA1.hexdigest(formatter.new_path), 1, 2] } subject { formatter.key } @@ -9,23 +9,23 @@ shared_examples_for "position formatter" do it { is_expected.to eq(key) } end - describe '#complete?' do + describe "#complete?" do subject { formatter.complete? } - context 'when there are missing key attributes' do + context "when there are missing key attributes" do it { is_expected.to be_truthy } end - context 'when old_line and new_line are nil' do + context "when old_line and new_line are nil" do let(:attrs) { base_attrs } it { is_expected.to be_falsy } end end - describe '#to_h' do + describe "#to_h" do let(:formatter_hash) do - attrs.merge(position_type: base_attrs[:position_type] || 'text' ) + attrs.merge(position_type: base_attrs[:position_type] || "text") end subject { formatter.to_h } @@ -33,7 +33,7 @@ shared_examples_for "position formatter" do it { is_expected.to eq(formatter_hash) } end - describe '#==' do + describe "#==" do subject { formatter } let(:other_formatter) { described_class.new(attrs) } diff --git a/spec/support/shared_examples/project_list_shared_examples.rb b/spec/support/shared_examples/project_list_shared_examples.rb index 675d489fcab..74c0b3c91f5 100644 --- a/spec/support/shared_examples/project_list_shared_examples.rb +++ b/spec/support/shared_examples/project_list_shared_examples.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -shared_examples 'shows public projects' do - it 'shows projects' do +shared_examples "shows public projects" do + it "shows projects" do expect(page).to have_content(public_project.title) expect(page).not_to have_content(internal_project.title) expect(page).not_to have_content(private_project.title) @@ -9,8 +9,8 @@ shared_examples 'shows public projects' do end end -shared_examples 'shows public and internal projects' do - it 'shows projects' do +shared_examples "shows public and internal projects" do + it "shows projects" do expect(page).to have_content(public_project.title) expect(page).to have_content(internal_project.title) expect(page).not_to have_content(private_project.title) diff --git a/spec/support/shared_examples/reference_parser_shared_examples.rb b/spec/support/shared_examples/reference_parser_shared_examples.rb index baf8bcc04b8..36d03cca7af 100644 --- a/spec/support/shared_examples/reference_parser_shared_examples.rb +++ b/spec/support/shared_examples/reference_parser_shared_examples.rb @@ -4,7 +4,7 @@ RSpec.shared_examples "referenced feature visibility" do |*related_features| end before do - link['data-project'] = project.id.to_s + link["data-project"] = project.id.to_s end context "when feature is disabled" do diff --git a/spec/support/shared_examples/requests/api/custom_attributes_shared_examples.rb b/spec/support/shared_examples/requests/api/custom_attributes_shared_examples.rb index 8a7fcf856a1..8e678b5a192 100644 --- a/spec/support/shared_examples/requests/api/custom_attributes_shared_examples.rb +++ b/spec/support/shared_examples/requests/api/custom_attributes_shared_examples.rb @@ -1,29 +1,29 @@ -shared_examples 'custom attributes endpoints' do |attributable_name| - let!(:custom_attribute1) { attributable.custom_attributes.create key: 'foo', value: 'foo' } - let!(:custom_attribute2) { attributable.custom_attributes.create key: 'bar', value: 'bar' } +shared_examples "custom attributes endpoints" do |attributable_name| + let!(:custom_attribute1) { attributable.custom_attributes.create key: "foo", value: "foo" } + let!(:custom_attribute2) { attributable.custom_attributes.create key: "bar", value: "bar" } describe "GET /#{attributable_name} with custom attributes filter" do before do other_attributable end - context 'with an unauthorized user' do - it 'does not filter by custom attributes' do - get api("/#{attributable_name}", user), params: { custom_attributes: { foo: 'foo', bar: 'bar' } } + context "with an unauthorized user" do + it "does not filter by custom attributes" do + get api("/#{attributable_name}", user), params: {custom_attributes: {foo: "foo", bar: "bar"}} expect(response).to have_gitlab_http_status(200) expect(json_response.size).to be 2 - expect(json_response.map { |r| r['id'] }).to contain_exactly attributable.id, other_attributable.id + expect(json_response.map { |r| r["id"] }).to contain_exactly attributable.id, other_attributable.id end end - context 'with an authorized user' do - it 'filters by custom attributes' do - get api("/#{attributable_name}", admin), params: { custom_attributes: { foo: 'foo', bar: 'bar' } } + context "with an authorized user" do + it "filters by custom attributes" do + get api("/#{attributable_name}", admin), params: {custom_attributes: {foo: "foo", bar: "bar"}} expect(response).to have_gitlab_http_status(200) expect(json_response.size).to be 1 - expect(json_response.first['id']).to eq attributable.id + expect(json_response.first["id"]).to eq attributable.id end end end @@ -33,157 +33,157 @@ shared_examples 'custom attributes endpoints' do |attributable_name| other_attributable end - context 'with an unauthorized user' do - it 'does not include custom attributes' do - get api("/#{attributable_name}", user), params: { with_custom_attributes: true } + context "with an unauthorized user" do + it "does not include custom attributes" do + get api("/#{attributable_name}", user), params: {with_custom_attributes: true} expect(response).to have_gitlab_http_status(200) expect(json_response.size).to be 2 - expect(json_response.first).not_to include 'custom_attributes' + expect(json_response.first).not_to include "custom_attributes" end end - context 'with an authorized user' do - it 'does not include custom attributes by default' do + context "with an authorized user" do + it "does not include custom attributes by default" do get api("/#{attributable_name}", admin) expect(response).to have_gitlab_http_status(200) expect(json_response.size).to be 2 - expect(json_response.first).not_to include 'custom_attributes' - expect(json_response.second).not_to include 'custom_attributes' + expect(json_response.first).not_to include "custom_attributes" + expect(json_response.second).not_to include "custom_attributes" end - it 'includes custom attributes if requested' do - get api("/#{attributable_name}", admin), params: { with_custom_attributes: true } + it "includes custom attributes if requested" do + get api("/#{attributable_name}", admin), params: {with_custom_attributes: true} expect(response).to have_gitlab_http_status(200) expect(json_response.size).to be 2 - attributable_response = json_response.find { |r| r['id'] == attributable.id } - other_attributable_response = json_response.find { |r| r['id'] == other_attributable.id } + attributable_response = json_response.find { |r| r["id"] == attributable.id } + other_attributable_response = json_response.find { |r| r["id"] == other_attributable.id } - expect(attributable_response['custom_attributes']).to contain_exactly( - { 'key' => 'foo', 'value' => 'foo' }, - { 'key' => 'bar', 'value' => 'bar' } + expect(attributable_response["custom_attributes"]).to contain_exactly( + {"key" => "foo", "value" => "foo"}, + {"key" => "bar", "value" => "bar"} ) - expect(other_attributable_response['custom_attributes']).to eq [] + expect(other_attributable_response["custom_attributes"]).to eq [] end end end describe "GET /#{attributable_name}/:id with custom attributes" do - context 'with an unauthorized user' do - it 'does not include custom attributes' do - get api("/#{attributable_name}/#{attributable.id}", user), params: { with_custom_attributes: true } + context "with an unauthorized user" do + it "does not include custom attributes" do + get api("/#{attributable_name}/#{attributable.id}", user), params: {with_custom_attributes: true} expect(response).to have_gitlab_http_status(200) - expect(json_response).not_to include 'custom_attributes' + expect(json_response).not_to include "custom_attributes" end end - context 'with an authorized user' do - it 'does not include custom attributes by default' do + context "with an authorized user" do + it "does not include custom attributes by default" do get api("/#{attributable_name}/#{attributable.id}", admin) expect(response).to have_gitlab_http_status(200) - expect(json_response).not_to include 'custom_attributes' + expect(json_response).not_to include "custom_attributes" end - it 'includes custom attributes if requested' do - get api("/#{attributable_name}/#{attributable.id}", admin), params: { with_custom_attributes: true } + it "includes custom attributes if requested" do + get api("/#{attributable_name}/#{attributable.id}", admin), params: {with_custom_attributes: true} expect(response).to have_gitlab_http_status(200) - expect(json_response['custom_attributes']).to contain_exactly( - { 'key' => 'foo', 'value' => 'foo' }, - { 'key' => 'bar', 'value' => 'bar' } + expect(json_response["custom_attributes"]).to contain_exactly( + {"key" => "foo", "value" => "foo"}, + {"key" => "bar", "value" => "bar"} ) end end end describe "GET /#{attributable_name}/:id/custom_attributes" do - context 'with an unauthorized user' do + context "with an unauthorized user" do subject { get api("/#{attributable_name}/#{attributable.id}/custom_attributes", user) } - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end - context 'with an authorized user' do - it 'returns all custom attributes' do + context "with an authorized user" do + it "returns all custom attributes" do get api("/#{attributable_name}/#{attributable.id}/custom_attributes", admin) expect(response).to have_gitlab_http_status(200) expect(json_response).to contain_exactly( - { 'key' => 'foo', 'value' => 'foo' }, - { 'key' => 'bar', 'value' => 'bar' } + {"key" => "foo", "value" => "foo"}, + {"key" => "bar", "value" => "bar"} ) end end end describe "GET /#{attributable_name}/:id/custom_attributes/:key" do - context 'with an unauthorized user' do + context "with an unauthorized user" do subject { get api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", user) } - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end - context 'with an authorized user' do - it'returns a single custom attribute' do + context "with an authorized user" do + it"returns a single custom attribute" do get api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", admin) expect(response).to have_gitlab_http_status(200) - expect(json_response).to eq({ 'key' => 'foo', 'value' => 'foo' }) + expect(json_response).to eq({"key" => "foo", "value" => "foo"}) end end end describe "PUT /#{attributable_name}/:id/custom_attributes/:key" do - context 'with an unauthorized user' do - subject { put api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", user), params: { value: 'new' } } + context "with an unauthorized user" do + subject { put api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", user), params: {value: "new"} } - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end - context 'with an authorized user' do - it 'creates a new custom attribute' do - expect do - put api("/#{attributable_name}/#{attributable.id}/custom_attributes/new", admin), params: { value: 'new' } - end.to change { attributable.custom_attributes.count }.by(1) + context "with an authorized user" do + it "creates a new custom attribute" do + expect { + put api("/#{attributable_name}/#{attributable.id}/custom_attributes/new", admin), params: {value: "new"} + }.to change { attributable.custom_attributes.count }.by(1) expect(response).to have_gitlab_http_status(200) - expect(json_response).to eq({ 'key' => 'new', 'value' => 'new' }) - expect(attributable.custom_attributes.find_by(key: 'new').value).to eq 'new' + expect(json_response).to eq({"key" => "new", "value" => "new"}) + expect(attributable.custom_attributes.find_by(key: "new").value).to eq "new" end - it 'updates an existing custom attribute' do - expect do - put api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", admin), params: { value: 'new' } - end.not_to change { attributable.custom_attributes.count } + it "updates an existing custom attribute" do + expect { + put api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", admin), params: {value: "new"} + }.not_to change { attributable.custom_attributes.count } expect(response).to have_gitlab_http_status(200) - expect(json_response).to eq({ 'key' => 'foo', 'value' => 'new' }) - expect(custom_attribute1.reload.value).to eq 'new' + expect(json_response).to eq({"key" => "foo", "value" => "new"}) + expect(custom_attribute1.reload.value).to eq "new" end end end describe "DELETE /#{attributable_name}/:id/custom_attributes/:key" do - context 'with an unauthorized user' do + context "with an unauthorized user" do subject { delete api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", user) } - it_behaves_like 'an unauthorized API user' + it_behaves_like "an unauthorized API user" end - context 'with an authorized user' do - it 'deletes an existing custom attribute' do - expect do + context "with an authorized user" do + it "deletes an existing custom attribute" do + expect { delete api("/#{attributable_name}/#{attributable.id}/custom_attributes/foo", admin) - end.to change { attributable.custom_attributes.count }.by(-1) + }.to change { attributable.custom_attributes.count }.by(-1) expect(response).to have_gitlab_http_status(204) - expect(attributable.custom_attributes.find_by(key: 'foo')).to be_nil + expect(attributable.custom_attributes.find_by(key: "foo")).to be_nil end end end diff --git a/spec/support/shared_examples/requests/api/diff_discussions.rb b/spec/support/shared_examples/requests/api/diff_discussions.rb index 366c2955359..4657ffbc555 100644 --- a/spec/support/shared_examples/requests/api/diff_discussions.rb +++ b/spec/support/shared_examples/requests/api/diff_discussions.rb @@ -1,14 +1,14 @@ -shared_examples 'diff discussions API' do |parent_type, noteable_type, id_name| +shared_examples "diff discussions API" do |parent_type, noteable_type, id_name| describe "GET /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions" do it "includes diff discussions" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", user) - discussion = json_response.find { |record| record['id'] == diff_note.discussion_id } + discussion = json_response.find { |record| record["id"] == diff_note.discussion_id } expect(response).to have_gitlab_http_status(200) expect(discussion).not_to be_nil - expect(discussion['individual_note']).to eq(false) - expect(discussion['notes'].first['body']).to eq(diff_note.note) + expect(discussion["individual_note"]).to eq(false) + expect(discussion["notes"].first["body"]).to eq(diff_note.note) end end @@ -17,9 +17,9 @@ shared_examples 'diff discussions API' do |parent_type, noteable_type, id_name| get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions/#{diff_note.discussion_id}", user) expect(response).to have_gitlab_http_status(200) - expect(json_response['id']).to eq(diff_note.discussion_id) - expect(json_response['notes'].first['body']).to eq(diff_note.note) - expect(json_response['notes'].first['position']).to eq(diff_note.position.to_h.stringify_keys) + expect(json_response["id"]).to eq(diff_note.discussion_id) + expect(json_response["notes"].first["body"]).to eq(diff_note.note) + expect(json_response["notes"].first["position"]).to eq(diff_note.position.to_h.stringify_keys) end end @@ -28,32 +28,32 @@ shared_examples 'diff discussions API' do |parent_type, noteable_type, id_name| position = diff_note.position.to_h post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", user), - params: { body: 'hi!', position: position } + params: {body: "hi!", position: position} expect(response).to have_gitlab_http_status(201) - expect(json_response['notes'].first['body']).to eq('hi!') - expect(json_response['notes'].first['type']).to eq('DiffNote') - expect(json_response['notes'].first['position']).to eq(position.stringify_keys) + expect(json_response["notes"].first["body"]).to eq("hi!") + expect(json_response["notes"].first["type"]).to eq("DiffNote") + expect(json_response["notes"].first["position"]).to eq(position.stringify_keys) end it "returns a 400 bad request error when position is invalid" do - position = diff_note.position.to_h.merge(new_line: '100000') + position = diff_note.position.to_h.merge(new_line: "100000") post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", user), - params: { body: 'hi!', position: position } + params: {body: "hi!", position: position} expect(response).to have_gitlab_http_status(400) end end describe "POST /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions/:discussion_id/notes" do - it 'adds a new note to the diff discussion' do + it "adds a new note to the diff discussion" do post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{diff_note.discussion_id}/notes", user), params: { body: 'hi!' } + "discussions/#{diff_note.discussion_id}/notes", user), params: {body: "hi!"} expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('hi!') - expect(json_response['type']).to eq('DiffNote') + expect(json_response["body"]).to eq("hi!") + expect(json_response["type"]).to eq("DiffNote") end end end diff --git a/spec/support/shared_examples/requests/api/discussions.rb b/spec/support/shared_examples/requests/api/discussions.rb index e44da4faa5a..316f6ae448f 100644 --- a/spec/support/shared_examples/requests/api/discussions.rb +++ b/spec/support/shared_examples/requests/api/discussions.rb @@ -1,4 +1,4 @@ -shared_examples 'discussions API' do |parent_type, noteable_type, id_name| +shared_examples "discussions API" do |parent_type, noteable_type, id_name| describe "GET /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions" do it "returns an array of discussions" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", user) @@ -6,7 +6,7 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array - expect(json_response.first['id']).to eq(note.discussion_id) + expect(json_response.first["id"]).to eq(note.discussion_id) end it "returns a 404 error when noteable id not found" do @@ -29,8 +29,8 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions/#{note.discussion_id}", user) expect(response).to have_gitlab_http_status(200) - expect(json_response['id']).to eq(note.discussion_id) - expect(json_response['notes'].first['body']).to eq(note.note) + expect(json_response["id"]).to eq(note.discussion_id) + expect(json_response["notes"].first["body"]).to eq(note.note) end it "returns a 404 error if discussion not found" do @@ -42,11 +42,11 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| describe "POST /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions" do it "creates a new note" do - post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", user), params: { body: 'hi!' } + post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", user), params: {body: "hi!"} expect(response).to have_gitlab_http_status(201) - expect(json_response['notes'].first['body']).to eq('hi!') - expect(json_response['notes'].first['author']['username']).to eq(user.username) + expect(json_response["notes"].first["body"]).to eq("hi!") + expect(json_response["notes"].first["author"]["username"]).to eq(user.username) end it "returns a 400 bad request error if body not given" do @@ -56,32 +56,32 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| end it "returns a 401 unauthorized error if user not authenticated" do - post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions"), params: { body: 'hi!' } + post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions"), params: {body: "hi!"} expect(response).to have_gitlab_http_status(401) end - context 'when an admin or owner makes the request' do - it 'accepts the creation date to be set' do + context "when an admin or owner makes the request" do + it "accepts the creation date to be set" do creation_time = 2.weeks.ago post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", user), - params: { body: 'hi!', created_at: creation_time } + params: {body: "hi!", created_at: creation_time} expect(response).to have_gitlab_http_status(201) - expect(json_response['notes'].first['body']).to eq('hi!') - expect(json_response['notes'].first['author']['username']).to eq(user.username) - expect(Time.parse(json_response['notes'].first['created_at'])).to be_like_time(creation_time) + expect(json_response["notes"].first["body"]).to eq("hi!") + expect(json_response["notes"].first["author"]["username"]).to eq(user.username) + expect(Time.parse(json_response["notes"].first["created_at"])).to be_like_time(creation_time) end end - context 'when user does not have access to read the discussion' do + context "when user does not have access to read the discussion" do before do parent.update!(visibility_level: Gitlab::VisibilityLevel::PRIVATE) end - it 'responds with 404' do + it "responds with 404" do post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/discussions", private_user), - params: { body: 'Foo' } + params: {body: "Foo"} expect(response).to have_gitlab_http_status(404) end @@ -89,16 +89,16 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| end describe "POST /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions/:discussion_id/notes" do - it 'adds a new note to the discussion' do + it "adds a new note to the discussion" do post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}/notes", user), params: { body: 'Hello!' } + "discussions/#{note.discussion_id}/notes", user), params: {body: "Hello!"} expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('Hello!') - expect(json_response['type']).to eq('DiscussionNote') + expect(json_response["body"]).to eq("Hello!") + expect(json_response["type"]).to eq("DiscussionNote") end - it 'returns a 400 bad request error if body not given' do + it "returns a 400 bad request error if body not given" do post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes", user) @@ -109,30 +109,30 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| note.update_attribute(:type, nil) post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}/notes", user), params: { body: 'hi!' } + "discussions/#{note.discussion_id}/notes", user), params: {body: "hi!"} expect(response).to have_gitlab_http_status(400) end end describe "PUT /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions/:discussion_id/notes/:note_id" do - it 'returns modified note' do + it "returns modified note" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}/notes/#{note.id}", user), params: { body: 'Hello!' } + "discussions/#{note.discussion_id}/notes/#{note.id}", user), params: {body: "Hello!"} expect(response).to have_gitlab_http_status(200) - expect(json_response['body']).to eq('Hello!') + expect(json_response["body"]).to eq("Hello!") end - it 'returns a 404 error when note id not found' do + it "returns a 404 error when note id not found" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes/12345", user), - params: { body: 'Hello!' } + params: {body: "Hello!"} expect(response).to have_gitlab_http_status(404) end - it 'returns a 400 bad request error if body not given' do + it "returns a 400 bad request error if body not given" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes/#{note.id}", user) @@ -141,7 +141,7 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| end describe "DELETE /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions/:discussion_id/notes/:note_id" do - it 'deletes a note' do + it "deletes a note" do delete api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes/#{note.id}", user) @@ -152,14 +152,14 @@ shared_examples 'discussions API' do |parent_type, noteable_type, id_name| expect(response).to have_gitlab_http_status(404) end - it 'returns a 404 error when note id not found' do + it "returns a 404 error when note id not found" do delete api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes/12345", user) expect(response).to have_gitlab_http_status(404) end - it_behaves_like '412 response' do + it_behaves_like "412 response" do let(:request) do api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes/#{note.id}", user) diff --git a/spec/support/shared_examples/requests/api/issuable_participants_examples.rb b/spec/support/shared_examples/requests/api/issuable_participants_examples.rb index 96d59e0c472..e6cd45175f6 100644 --- a/spec/support/shared_examples/requests/api/issuable_participants_examples.rb +++ b/spec/support/shared_examples/requests/api/issuable_participants_examples.rb @@ -1,7 +1,7 @@ -shared_examples 'issuable participants endpoint' do +shared_examples "issuable participants endpoint" do let(:area) { entity.class.name.underscore.pluralize } - it 'returns participants' do + it "returns participants" do get api("/projects/#{project.id}/#{area}/#{entity.iid}/participants", user) expect(response).to have_gitlab_http_status(200) @@ -10,18 +10,18 @@ shared_examples 'issuable participants endpoint' do expect(json_response.size).to eq(entity.participants.size) last_participant = entity.participants.last - expect(json_response.last['id']).to eq(last_participant.id) - expect(json_response.last['name']).to eq(last_participant.name) - expect(json_response.last['username']).to eq(last_participant.username) + expect(json_response.last["id"]).to eq(last_participant.id) + expect(json_response.last["name"]).to eq(last_participant.name) + expect(json_response.last["username"]).to eq(last_participant.username) end - it 'returns a 404 when iid does not exist' do + it "returns a 404 when iid does not exist" do get api("/projects/#{project.id}/#{area}/999/participants", user) expect(response).to have_gitlab_http_status(404) end - it 'returns a 404 when id is used instead of iid' do + it "returns a 404 when id is used instead of iid" do get api("/projects/#{project.id}/#{area}/#{entity.id}/participants", user) expect(response).to have_gitlab_http_status(404) diff --git a/spec/support/shared_examples/requests/api/merge_requests_list.rb b/spec/support/shared_examples/requests/api/merge_requests_list.rb index 6713ec47ace..022bc352fd1 100644 --- a/spec/support/shared_examples/requests/api/merge_requests_list.rb +++ b/spec/support/shared_examples/requests/api/merge_requests_list.rb @@ -1,6 +1,6 @@ -shared_examples 'merge requests list' do - context 'when unauthenticated' do - it 'returns merge requests for public projects' do +shared_examples "merge requests list" do + context "when unauthenticated" do + it "returns merge requests for public projects" do get api(endpoint_path) expect(response).to have_gitlab_http_status(200) @@ -8,67 +8,67 @@ shared_examples 'merge requests list' do end end - context 'when authenticated' do - it 'avoids N+1 queries' do - control = ActiveRecord::QueryRecorder.new do + context "when authenticated" do + it "avoids N+1 queries" do + control = ActiveRecord::QueryRecorder.new { get api(endpoint_path, user) - end + } - create(:merge_request, state: 'closed', milestone: milestone1, author: user, assignee: user, source_project: project, target_project: project, title: 'Test', created_at: base_time) + create(:merge_request, state: "closed", milestone: milestone1, author: user, assignee: user, source_project: project, target_project: project, title: "Test", created_at: base_time) - merge_request = create(:merge_request, milestone: milestone1, author: user, assignee: user, source_project: project, target_project: project, title: 'Test', created_at: base_time) + merge_request = create(:merge_request, milestone: milestone1, author: user, assignee: user, source_project: project, target_project: project, title: "Test", created_at: base_time) merge_request.metrics.update!(merged_by: user, latest_closed_by: user, latest_closed_at: 1.hour.ago, merged_at: 2.hours.ago) - expect do + expect { get api(endpoint_path, user) - end.not_to exceed_query_limit(control) + }.not_to exceed_query_limit(control) end - it 'returns an array of all merge_requests' do + it "returns an array of all merge_requests" do get api(endpoint_path, user) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(4) - expect(json_response.last['title']).to eq(merge_request.title) - expect(json_response.last).to have_key('web_url') - expect(json_response.last['sha']).to eq(merge_request.diff_head_sha) - expect(json_response.last['merge_commit_sha']).to be_nil - expect(json_response.last['merge_commit_sha']).to eq(merge_request.merge_commit_sha) - expect(json_response.last['downvotes']).to eq(1) - expect(json_response.last['upvotes']).to eq(1) - expect(json_response.last['labels']).to eq([label2.title, label.title]) - expect(json_response.first['title']).to eq(merge_request_merged.title) - expect(json_response.first['sha']).to eq(merge_request_merged.diff_head_sha) - expect(json_response.first['merge_commit_sha']).not_to be_nil - expect(json_response.first['merge_commit_sha']).to eq(merge_request_merged.merge_commit_sha) + expect(json_response.last["title"]).to eq(merge_request.title) + expect(json_response.last).to have_key("web_url") + expect(json_response.last["sha"]).to eq(merge_request.diff_head_sha) + expect(json_response.last["merge_commit_sha"]).to be_nil + expect(json_response.last["merge_commit_sha"]).to eq(merge_request.merge_commit_sha) + expect(json_response.last["downvotes"]).to eq(1) + expect(json_response.last["upvotes"]).to eq(1) + expect(json_response.last["labels"]).to eq([label2.title, label.title]) + expect(json_response.first["title"]).to eq(merge_request_merged.title) + expect(json_response.first["sha"]).to eq(merge_request_merged.diff_head_sha) + expect(json_response.first["merge_commit_sha"]).not_to be_nil + expect(json_response.first["merge_commit_sha"]).to eq(merge_request_merged.merge_commit_sha) end - it 'returns an array of all merge_requests using simple mode' do - path = endpoint_path + '?view=simple' + it "returns an array of all merge_requests using simple mode" do + path = endpoint_path + "?view=simple" get api(path, user) expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers - expect(json_response.last.keys).to match_array(%w(id iid title web_url created_at description project_id state updated_at)) + expect(json_response.last.keys).to match_array(%w[id iid title web_url created_at description project_id state updated_at]) expect(json_response).to be_an Array expect(json_response.length).to eq(4) - expect(json_response.last['iid']).to eq(merge_request.iid) - expect(json_response.last['title']).to eq(merge_request.title) - expect(json_response.last).to have_key('web_url') - expect(json_response.first['iid']).to eq(merge_request_merged.iid) - expect(json_response.first['title']).to eq(merge_request_merged.title) - expect(json_response.first).to have_key('web_url') + expect(json_response.last["iid"]).to eq(merge_request.iid) + expect(json_response.last["title"]).to eq(merge_request.title) + expect(json_response.last).to have_key("web_url") + expect(json_response.first["iid"]).to eq(merge_request_merged.iid) + expect(json_response.first["title"]).to eq(merge_request_merged.title) + expect(json_response.first).to have_key("web_url") end - it 'returns an array of all merge_requests' do - path = endpoint_path + '?state' + it "returns an array of all merge_requests" do + path = endpoint_path + "?state" get api(path, user) @@ -76,11 +76,11 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(4) - expect(json_response.last['title']).to eq(merge_request.title) + expect(json_response.last["title"]).to eq(merge_request.title) end - it 'returns an array of open merge_requests' do - path = endpoint_path + '?state=opened' + it "returns an array of open merge_requests" do + path = endpoint_path + "?state=opened" get api(path, user) @@ -88,11 +88,11 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.last['title']).to eq(merge_request.title) + expect(json_response.last["title"]).to eq(merge_request.title) end - it 'returns an array of closed merge_requests' do - path = endpoint_path + '?state=closed' + it "returns an array of closed merge_requests" do + path = endpoint_path + "?state=closed" get api(path, user) @@ -100,11 +100,11 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.first['title']).to eq(merge_request_closed.title) + expect(json_response.first["title"]).to eq(merge_request_closed.title) end - it 'returns an array of merged merge_requests' do - path = endpoint_path + '?state=merged' + it "returns an array of merged merge_requests" do + path = endpoint_path + "?state=merged" get api(path, user) @@ -112,50 +112,50 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.first['title']).to eq(merge_request_merged.title) + expect(json_response.first["title"]).to eq(merge_request_merged.title) end - it 'matches V4 response schema' do + it "matches V4 response schema" do get api(endpoint_path, user) expect(response).to have_gitlab_http_status(200) - expect(response).to match_response_schema('public_api/v4/merge_requests') + expect(response).to match_response_schema("public_api/v4/merge_requests") end - it 'returns an empty array if no issue matches milestone' do - get api(endpoint_path, user), params: { milestone: '1.0.0' } + it "returns an empty array if no issue matches milestone" do + get api(endpoint_path, user), params: {milestone: "1.0.0"} expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.length).to eq(0) end - it 'returns an empty array if milestone does not exist' do - get api(endpoint_path, user), params: { milestone: 'foo' } + it "returns an empty array if milestone does not exist" do + get api(endpoint_path, user), params: {milestone: "foo"} expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.length).to eq(0) end - it 'returns an array of merge requests in given milestone' do - get api(endpoint_path, user), params: { milestone: '0.9' } + it "returns an array of merge requests in given milestone" do + get api(endpoint_path, user), params: {milestone: "0.9"} - closed_issues = json_response.select { |mr| mr['id'] == merge_request_closed.id } + closed_issues = json_response.select { |mr| mr["id"] == merge_request_closed.id } expect(closed_issues.length).to eq(1) - expect(closed_issues.first['title']).to eq merge_request_closed.title + expect(closed_issues.first["title"]).to eq merge_request_closed.title end - it 'returns an array of merge requests matching state in milestone' do - get api(endpoint_path, user), params: { milestone: '0.9', state: 'closed' } + it "returns an array of merge requests matching state in milestone" do + get api(endpoint_path, user), params: {milestone: "0.9", state: "closed"} expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.first['id']).to eq(merge_request_closed.id) + expect(json_response.first["id"]).to eq(merge_request_closed.id) end - it 'returns an array of labeled merge requests' do + it "returns an array of labeled merge requests" do path = endpoint_path + "?labels=#{label.title}" get api(path, user) @@ -163,10 +163,10 @@ shared_examples 'merge requests list' do expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.first['labels']).to eq([label2.title, label.title]) + expect(json_response.first["labels"]).to eq([label2.title, label.title]) end - it 'returns an array of labeled merge requests where all labels match' do + it "returns an array of labeled merge requests where all labels match" do path = endpoint_path + "?labels=#{label.title},foo,bar" get api(path, user) @@ -176,8 +176,8 @@ shared_examples 'merge requests list' do expect(json_response.length).to eq(0) end - it 'returns an empty array if no merge request matches labels' do - path = endpoint_path + '?labels=foo,bar' + it "returns an empty array if no merge request matches labels" do + path = endpoint_path + "?labels=foo,bar" get api(path, user) @@ -186,30 +186,30 @@ shared_examples 'merge requests list' do expect(json_response.length).to eq(0) end - it 'returns an array of merge requests with any label when filtering by any label' do - get api(endpoint_path, user), params: { labels: IssuesFinder::FILTER_ANY } + it "returns an array of merge requests with any label when filtering by any label" do + get api(endpoint_path, user), params: {labels: IssuesFinder::FILTER_ANY} expect_paginated_array_response expect(json_response.length).to eq(1) - expect(json_response.first['id']).to eq(merge_request.id) + expect(json_response.first["id"]).to eq(merge_request.id) end - it 'returns an array of merge requests without a label when filtering by no label' do - get api(endpoint_path, user), params: { labels: IssuesFinder::FILTER_NONE } + it "returns an array of merge requests without a label when filtering by no label" do + get api(endpoint_path, user), params: {labels: IssuesFinder::FILTER_NONE} - response_ids = json_response.map { |merge_request| merge_request['id'] } + response_ids = json_response.map { |merge_request| merge_request["id"] } expect_paginated_array_response expect(response_ids).to contain_exactly(merge_request_closed.id, merge_request_merged.id, merge_request_locked.id) end - it 'returns an array of labeled merge requests that are merged for a milestone' do - bug_label = create(:label, title: 'bug', color: '#FFAABB', project: project) + it "returns an array of labeled merge requests that are merged for a milestone" do + bug_label = create(:label, title: "bug", color: "#FFAABB", project: project) - mr1 = create(:merge_request, state: 'merged', source_project: project, target_project: project, milestone: milestone) - mr2 = create(:merge_request, state: 'merged', source_project: project, target_project: project, milestone: milestone1) - mr3 = create(:merge_request, state: 'closed', source_project: project, target_project: project, milestone: milestone1) - _mr = create(:merge_request, state: 'merged', source_project: project, target_project: project, milestone: milestone1) + mr1 = create(:merge_request, state: "merged", source_project: project, target_project: project, milestone: milestone) + mr2 = create(:merge_request, state: "merged", source_project: project, target_project: project, milestone: milestone1) + mr3 = create(:merge_request, state: "closed", source_project: project, target_project: project, milestone: milestone1) + _mr = create(:merge_request, state: "merged", source_project: project, target_project: project, milestone: milestone1) create(:label_link, label: bug_label, target: mr1) create(:label_link, label: bug_label, target: mr2) @@ -222,17 +222,17 @@ shared_examples 'merge requests list' do expect(response).to have_gitlab_http_status(200) expect(json_response).to be_an Array expect(json_response.length).to eq(1) - expect(json_response.first['id']).to eq(mr2.id) + expect(json_response.first["id"]).to eq(mr2.id) end - context 'with ordering' do + context "with ordering" do before do @mr_later = mr_with_later_created_and_updated_at_time @mr_earlier = mr_with_earlier_created_and_updated_at_time end - it 'returns an array of merge_requests in ascending order' do - path = endpoint_path + '?sort=asc' + it "returns an array of merge_requests in ascending order" do + path = endpoint_path + "?sort=asc" get api(path, user) @@ -240,12 +240,12 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(4) - response_dates = json_response.map { |merge_request| merge_request['created_at'] } + response_dates = json_response.map { |merge_request| merge_request["created_at"] } expect(response_dates).to eq(response_dates.sort) end - it 'returns an array of merge_requests in descending order' do - path = endpoint_path + '?sort=desc' + it "returns an array of merge_requests in descending order" do + path = endpoint_path + "?sort=desc" get api(path, user) @@ -253,44 +253,44 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(4) - response_dates = json_response.map { |merge_request| merge_request['created_at'] } + response_dates = json_response.map { |merge_request| merge_request["created_at"] } expect(response_dates).to eq(response_dates.sort.reverse) end - context '2 merge requests with equal created_at' do + context "2 merge requests with equal created_at" do let!(:closed_mr2) do create :merge_request, - state: 'closed', - milestone: milestone1, - author: user, - assignee: user, - source_project: project, - target_project: project, - title: "Test", - created_at: @mr_earlier.created_at + state: "closed", + milestone: milestone1, + author: user, + assignee: user, + source_project: project, + target_project: project, + title: "Test", + created_at: @mr_earlier.created_at end - it 'page breaks first page correctly' do + it "page breaks first page correctly" do get api("#{endpoint_path}?sort=desc&per_page=4", user) - response_ids = json_response.map { |merge_request| merge_request['id'] } + response_ids = json_response.map { |merge_request| merge_request["id"] } expect(response_ids).to include(closed_mr2.id) expect(response_ids).not_to include(@mr_earlier.id) end - it 'page breaks second page correctly' do + it "page breaks second page correctly" do get api("#{endpoint_path}?sort=desc&per_page=4&page=2", user) - response_ids = json_response.map { |merge_request| merge_request['id'] } + response_ids = json_response.map { |merge_request| merge_request["id"] } expect(response_ids).not_to include(closed_mr2.id) expect(response_ids).to include(@mr_earlier.id) end end - it 'returns an array of merge_requests ordered by updated_at' do - path = endpoint_path + '?order_by=updated_at' + it "returns an array of merge_requests ordered by updated_at" do + path = endpoint_path + "?order_by=updated_at" get api(path, user) @@ -298,12 +298,12 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(4) - response_dates = json_response.map { |merge_request| merge_request['updated_at'] } + response_dates = json_response.map { |merge_request| merge_request["updated_at"] } expect(response_dates).to eq(response_dates.sort.reverse) end - it 'returns an array of merge_requests ordered by created_at' do - path = endpoint_path + '?order_by=created_at&sort=asc' + it "returns an array of merge_requests ordered by created_at" do + path = endpoint_path + "?order_by=created_at&sort=asc" get api(path, user) @@ -311,22 +311,22 @@ shared_examples 'merge requests list' do expect(response).to include_pagination_headers expect(json_response).to be_an Array expect(json_response.length).to eq(4) - response_dates = json_response.map { |merge_request| merge_request['created_at'] } + response_dates = json_response.map { |merge_request| merge_request["created_at"] } expect(response_dates).to eq(response_dates.sort) end end - context 'source_branch param' do - it 'returns merge requests with the given source branch' do - get api(endpoint_path, user), params: { source_branch: merge_request_closed.source_branch, state: 'all' } + context "source_branch param" do + it "returns merge requests with the given source branch" do + get api(endpoint_path, user), params: {source_branch: merge_request_closed.source_branch, state: "all"} expect_response_contain_exactly(merge_request_closed, merge_request_merged, merge_request_locked) end end - context 'target_branch param' do - it 'returns merge requests with the given target branch' do - get api(endpoint_path, user), params: { target_branch: merge_request_closed.target_branch, state: 'all' } + context "target_branch param" do + it "returns merge requests with the given target branch" do + get api(endpoint_path, user), params: {target_branch: merge_request_closed.target_branch, state: "all"} expect_response_contain_exactly(merge_request_closed, merge_request_merged, merge_request_locked) end diff --git a/spec/support/shared_examples/requests/api/notes.rb b/spec/support/shared_examples/requests/api/notes.rb index 57eefd5ef01..f2a45299862 100644 --- a/spec/support/shared_examples/requests/api/notes.rb +++ b/spec/support/shared_examples/requests/api/notes.rb @@ -1,47 +1,47 @@ -shared_examples 'noteable API' do |parent_type, noteable_type, id_name| +shared_examples "noteable API" do |parent_type, noteable_type, id_name| describe "GET /#{parent_type}/:id/#{noteable_type}/:noteable_id/notes" do - context 'sorting' do + context "sorting" do before do - params = { noteable: noteable, author: user } + params = {noteable: noteable, author: user} params[:project] = parent if parent.is_a?(Project) create_list(:note, 3, params) end - context 'without sort params' do - it 'sorts by created_at in descending order by default' do + context "without sort params" do + it "sorts by created_at in descending order by default" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user) - response_dates = json_response.map { |note| note['created_at'] } + response_dates = json_response.map { |note| note["created_at"] } expect(json_response.length).to eq(4) expect(response_dates).to eq(response_dates.sort.reverse) end - context '2 notes with equal created_at' do + context "2 notes with equal created_at" do before do @first_note = Note.first - params = { noteable: noteable, author: user } + params = {noteable: noteable, author: user} params[:project] = parent if parent.is_a?(Project) params[:created_at] = @first_note.created_at @note2 = create(:note, params) end - it 'page breaks first page correctly' do + it "page breaks first page correctly" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes?per_page=4", user) - response_ids = json_response.map { |note| note['id'] } + response_ids = json_response.map { |note| note["id"] } expect(response_ids).to include(@note2.id) expect(response_ids).not_to include(@first_note.id) end - it 'page breaks second page correctly' do + it "page breaks second page correctly" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes?per_page=4&page=2", user) - response_ids = json_response.map { |note| note['id'] } + response_ids = json_response.map { |note| note["id"] } expect(response_ids).not_to include(@note2.id) expect(response_ids).to include(@first_note.id) @@ -49,28 +49,28 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| end end - it 'sorts by ascending order when requested' do + it "sorts by ascending order when requested" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes?sort=asc", user) - response_dates = json_response.map { |note| note['created_at'] } + response_dates = json_response.map { |note| note["created_at"] } expect(json_response.length).to eq(4) expect(response_dates).to eq(response_dates.sort) end - it 'sorts by updated_at in descending order when requested' do + it "sorts by updated_at in descending order when requested" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes?order_by=updated_at", user) - response_dates = json_response.map { |note| note['updated_at'] } + response_dates = json_response.map { |note| note["updated_at"] } expect(json_response.length).to eq(4) expect(response_dates).to eq(response_dates.sort.reverse) end - it 'sorts by updated_at in ascending order when requested' do + it "sorts by updated_at in ascending order when requested" do get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes?order_by=updated_at&sort=asc", user) - response_dates = json_response.map { |note| note['updated_at'] } + response_dates = json_response.map { |note| note["updated_at"] } expect(json_response.length).to eq(4) expect(response_dates).to eq(response_dates.sort) @@ -83,7 +83,7 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| expect(response).to have_gitlab_http_status(200) expect(response).to include_pagination_headers expect(json_response).to be_an Array - expect(json_response.first['body']).to eq(note.note) + expect(json_response.first["body"]).to eq(note.note) end it "returns a 404 error when noteable id not found" do @@ -106,7 +106,7 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| get api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes/#{note.id}", user) expect(response).to have_gitlab_http_status(200) - expect(json_response['body']).to eq(note.note) + expect(json_response["body"]).to eq(note.note) end it "returns a 404 error if note not found" do @@ -118,11 +118,11 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| describe "POST /#{parent_type}/:id/#{noteable_type}/:noteable_id/notes" do it "creates a new note" do - post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: { body: 'hi!' } + post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: {body: "hi!"} expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('hi!') - expect(json_response['author']['username']).to eq(user.username) + expect(json_response["body"]).to eq("hi!") + expect(json_response["author"]["username"]).to eq(user.username) end it "returns a 400 bad request error if body not given" do @@ -132,7 +132,7 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| end it "returns a 401 unauthorized error if user not authenticated" do - post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes"), params: { body: 'hi!' } + post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes"), params: {body: "hi!"} expect(response).to have_gitlab_http_status(401) end @@ -140,41 +140,41 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| it "creates an activity event when a note is created" do expect(Event).to receive(:create!) - post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: { body: 'hi!' } + post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: {body: "hi!"} end - context 'setting created_at' do + context "setting created_at" do let(:creation_time) { 2.weeks.ago } - let(:params) { { body: 'hi!', created_at: creation_time } } + let(:params) { {body: "hi!", created_at: creation_time} } - context 'by an admin' do - it 'sets the creation time on the new note' do + context "by an admin" do + it "sets the creation time on the new note" do admin = create(:admin) post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", admin), params: params expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('hi!') - expect(json_response['author']['username']).to eq(admin.username) - expect(Time.parse(json_response['created_at'])).to be_like_time(creation_time) - expect(Time.parse(json_response['updated_at'])).to be_like_time(creation_time) + expect(json_response["body"]).to eq("hi!") + expect(json_response["author"]["username"]).to eq(admin.username) + expect(Time.parse(json_response["created_at"])).to be_like_time(creation_time) + expect(Time.parse(json_response["updated_at"])).to be_like_time(creation_time) end end - if parent_type == 'projects' - context 'by a project owner' do - it 'sets the creation time on the new note' do + if parent_type == "projects" + context "by a project owner" do + it "sets the creation time on the new note" do post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: params expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('hi!') - expect(json_response['author']['username']).to eq(user.username) - expect(Time.parse(json_response['created_at'])).to be_like_time(creation_time) - expect(Time.parse(json_response['updated_at'])).to be_like_time(creation_time) + expect(json_response["body"]).to eq("hi!") + expect(json_response["author"]["username"]).to eq(user.username) + expect(Time.parse(json_response["created_at"])).to be_like_time(creation_time) + expect(Time.parse(json_response["updated_at"])).to be_like_time(creation_time) end end - context 'by a group owner' do - it 'sets the creation time on the new note' do + context "by a group owner" do + it "sets the creation time on the new note" do user2 = create(:user) group = create(:group) group.add_owner(user2) @@ -184,68 +184,68 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user2), params: params expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('hi!') - expect(json_response['author']['username']).to eq(user2.username) - expect(Time.parse(json_response['created_at'])).to be_like_time(creation_time) - expect(Time.parse(json_response['updated_at'])).to be_like_time(creation_time) + expect(json_response["body"]).to eq("hi!") + expect(json_response["author"]["username"]).to eq(user2.username) + expect(Time.parse(json_response["created_at"])).to be_like_time(creation_time) + expect(Time.parse(json_response["updated_at"])).to be_like_time(creation_time) end end - elsif parent_type == 'groups' - context 'by a group owner' do - it 'sets the creation time on the new note' do + elsif parent_type == "groups" + context "by a group owner" do + it "sets the creation time on the new note" do post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: params expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('hi!') - expect(json_response['author']['username']).to eq(user.username) - expect(Time.parse(json_response['created_at'])).to be_like_time(creation_time) - expect(Time.parse(json_response['updated_at'])).to be_like_time(creation_time) + expect(json_response["body"]).to eq("hi!") + expect(json_response["author"]["username"]).to eq(user.username) + expect(Time.parse(json_response["created_at"])).to be_like_time(creation_time) + expect(Time.parse(json_response["updated_at"])).to be_like_time(creation_time) end end end - context 'by another user' do - it 'ignores the given creation time' do + context "by another user" do + it "ignores the given creation time" do user2 = create(:user) parent.add_developer(user2) post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user2), params: params expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq('hi!') - expect(json_response['author']['username']).to eq(user2.username) - expect(Time.parse(json_response['created_at'])).not_to be_like_time(creation_time) - expect(Time.parse(json_response['updated_at'])).not_to be_like_time(creation_time) + expect(json_response["body"]).to eq("hi!") + expect(json_response["author"]["username"]).to eq(user2.username) + expect(Time.parse(json_response["created_at"])).not_to be_like_time(creation_time) + expect(Time.parse(json_response["updated_at"])).not_to be_like_time(creation_time) end end end - context 'when the user is posting an award emoji on a noteable created by someone else' do - it 'creates a new note' do + context "when the user is posting an award emoji on a noteable created by someone else" do + it "creates a new note" do parent.add_developer(private_user) - post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", private_user), params: { body: ':+1:' } + post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", private_user), params: {body: ":+1:"} expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq(':+1:') + expect(json_response["body"]).to eq(":+1:") end end - context 'when the user is posting an award emoji on his/her own noteable' do - it 'creates a new note' do - post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: { body: ':+1:' } + context "when the user is posting an award emoji on his/her own noteable" do + it "creates a new note" do + post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", user), params: {body: ":+1:"} expect(response).to have_gitlab_http_status(201) - expect(json_response['body']).to eq(':+1:') + expect(json_response["body"]).to eq(":+1:") end end - context 'when user does not have access to read the noteable' do + context "when user does not have access to read the noteable" do before do parent.update!(visibility_level: Gitlab::VisibilityLevel::PRIVATE) end - it 'responds with 404' do + it "responds with 404" do post api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes", private_user), - params: { body: 'Foo' } + params: {body: "Foo"} expect(response).to have_gitlab_http_status(404) end @@ -253,22 +253,22 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| end describe "PUT /#{parent_type}/:id/#{noteable_type}/:noteable_id/notes/:note_id" do - it 'returns modified note' do + it "returns modified note" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "notes/#{note.id}", user), params: { body: 'Hello!' } + "notes/#{note.id}", user), params: {body: "Hello!"} expect(response).to have_gitlab_http_status(200) - expect(json_response['body']).to eq('Hello!') + expect(json_response["body"]).to eq("Hello!") end - it 'returns a 404 error when note id not found' do + it "returns a 404 error when note id not found" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes/12345", user), - params: { body: 'Hello!' } + params: {body: "Hello!"} expect(response).to have_gitlab_http_status(404) end - it 'returns a 400 bad request error if body not given' do + it "returns a 400 bad request error if body not given" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "notes/#{note.id}", user) @@ -277,7 +277,7 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| end describe "DELETE /#{parent_type}/:id/#{noteable_type}/:noteable_id/notes/:note_id" do - it 'deletes a note' do + it "deletes a note" do delete api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "notes/#{note.id}", user) @@ -288,13 +288,13 @@ shared_examples 'noteable API' do |parent_type, noteable_type, id_name| expect(response).to have_gitlab_http_status(404) end - it 'returns a 404 error when note id not found' do + it "returns a 404 error when note id not found" do delete api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes/12345", user) expect(response).to have_gitlab_http_status(404) end - it_behaves_like '412 response' do + it_behaves_like "412 response" do let(:request) { api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/notes/#{note.id}", user) } end end diff --git a/spec/support/shared_examples/requests/api/resolvable_discussions.rb b/spec/support/shared_examples/requests/api/resolvable_discussions.rb index 7e2416b23f3..02e2bf6b7cf 100644 --- a/spec/support/shared_examples/requests/api/resolvable_discussions.rb +++ b/spec/support/shared_examples/requests/api/resolvable_discussions.rb @@ -1,21 +1,21 @@ -shared_examples 'resolvable discussions API' do |parent_type, noteable_type, id_name| +shared_examples "resolvable discussions API" do |parent_type, noteable_type, id_name| describe "PUT /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions/:discussion_id" do it "resolves discussion if resolved is true" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}", user), params: { resolved: true } + "discussions/#{note.discussion_id}", user), params: {resolved: true} expect(response).to have_gitlab_http_status(200) - expect(json_response['notes'].size).to eq(1) - expect(json_response['notes'][0]['resolved']).to eq(true) + expect(json_response["notes"].size).to eq(1) + expect(json_response["notes"][0]["resolved"]).to eq(true) end it "unresolves discussion if resolved is false" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}", user), params: { resolved: false } + "discussions/#{note.discussion_id}", user), params: {resolved: false} expect(response).to have_gitlab_http_status(200) - expect(json_response['notes'].size).to eq(1) - expect(json_response['notes'][0]['resolved']).to eq(false) + expect(json_response["notes"].size).to eq(1) + expect(json_response["notes"][0]["resolved"]).to eq(false) end it "returns a 400 bad request error if resolved parameter is not passed" do @@ -27,26 +27,26 @@ shared_examples 'resolvable discussions API' do |parent_type, noteable_type, id_ it "returns a 401 unauthorized error if user is not authenticated" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}"), params: { resolved: true } + "discussions/#{note.discussion_id}"), params: {resolved: true} expect(response).to have_gitlab_http_status(401) end it "returns a 403 error if user resolves discussion of someone else" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}", private_user), params: { resolved: true } + "discussions/#{note.discussion_id}", private_user), params: {resolved: true} expect(response).to have_gitlab_http_status(403) end - context 'when user does not have access to read the discussion' do + context "when user does not have access to read the discussion" do before do parent.update!(visibility_level: Gitlab::VisibilityLevel::PRIVATE) end - it 'responds with 404' do + it "responds with 404" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}", private_user), params: { resolved: true } + "discussions/#{note.discussion_id}", private_user), params: {resolved: true} expect(response).to have_gitlab_http_status(404) end @@ -54,23 +54,23 @@ shared_examples 'resolvable discussions API' do |parent_type, noteable_type, id_ end describe "PUT /#{parent_type}/:id/#{noteable_type}/:noteable_id/discussions/:discussion_id/notes/:note_id" do - it 'returns resolved note when resolved parameter is true' do + it "returns resolved note when resolved parameter is true" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}/notes/#{note.id}", user), params: { resolved: true } + "discussions/#{note.discussion_id}/notes/#{note.id}", user), params: {resolved: true} expect(response).to have_gitlab_http_status(200) - expect(json_response['resolved']).to eq(true) + expect(json_response["resolved"]).to eq(true) end - it 'returns a 404 error when note id not found' do + it "returns a 404 error when note id not found" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes/12345", user), - params: { body: 'Hello!' } + params: {body: "Hello!"} expect(response).to have_gitlab_http_status(404) end - it 'returns a 400 bad request error if neither body nor resolved parameter is given' do + it "returns a 400 bad request error if neither body nor resolved parameter is given" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ "discussions/#{note.discussion_id}/notes/#{note.id}", user) @@ -79,7 +79,7 @@ shared_examples 'resolvable discussions API' do |parent_type, noteable_type, id_ it "returns a 403 error if user resolves note of someone else" do put api("/#{parent_type}/#{parent.id}/#{noteable_type}/#{noteable[id_name]}/"\ - "discussions/#{note.discussion_id}/notes/#{note.id}", private_user), params: { resolved: true } + "discussions/#{note.discussion_id}/notes/#{note.id}", private_user), params: {resolved: true} expect(response).to have_gitlab_http_status(403) end diff --git a/spec/support/shared_examples/requests/api/status_shared_examples.rb b/spec/support/shared_examples/requests/api/status_shared_examples.rb index ebfc5fed3bb..5d9f6ae2e61 100644 --- a/spec/support/shared_examples/requests/api/status_shared_examples.rb +++ b/spec/support/shared_examples/requests/api/status_shared_examples.rb @@ -2,7 +2,7 @@ # # Requires an API request: # let(:request) { get api("/projects/#{project.id}/repository/branches", user) } -shared_examples_for '400 response' do +shared_examples_for "400 response" do let(:message) { nil } before do @@ -10,27 +10,27 @@ shared_examples_for '400 response' do request end - it 'returns 400' do + it "returns 400" do expect(response).to have_gitlab_http_status(400) if message.present? - expect(json_response['message']).to eq(message) + expect(json_response["message"]).to eq(message) end end end -shared_examples_for '403 response' do +shared_examples_for "403 response" do before do # Fires the request request end - it 'returns 403' do + it "returns 403" do expect(response).to have_gitlab_http_status(403) end end -shared_examples_for '404 response' do +shared_examples_for "404 response" do let(:message) { nil } before do @@ -38,36 +38,36 @@ shared_examples_for '404 response' do request end - it 'returns 404' do + it "returns 404" do expect(response).to have_gitlab_http_status(404) expect(json_response).to be_an Object if message.present? - expect(json_response['message']).to eq(message) + expect(json_response["message"]).to eq(message) end end end -shared_examples_for '412 response' do +shared_examples_for "412 response" do let(:params) { nil } let(:success_status) { 204 } - context 'for a modified ressource' do + context "for a modified ressource" do before do - delete request, params: params, headers: { 'HTTP_IF_UNMODIFIED_SINCE' => '1990-01-12T00:00:48-0600' } + delete request, params: params, headers: {"HTTP_IF_UNMODIFIED_SINCE" => "1990-01-12T00:00:48-0600"} end - it 'returns 412' do + it "returns 412" do expect(response).to have_gitlab_http_status(412) end end - context 'for an unmodified ressource' do + context "for an unmodified ressource" do before do - delete request, params: params, headers: { 'HTTP_IF_UNMODIFIED_SINCE' => Time.now } + delete request, params: params, headers: {"HTTP_IF_UNMODIFIED_SINCE" => Time.now} end - it 'returns accepted' do + it "returns accepted" do expect(response).to have_gitlab_http_status(success_status) end end diff --git a/spec/support/shared_examples/requests/graphql_shared_examples.rb b/spec/support/shared_examples/requests/graphql_shared_examples.rb index 04140cad3f0..d039fe91c7e 100644 --- a/spec/support/shared_examples/requests/graphql_shared_examples.rb +++ b/spec/support/shared_examples/requests/graphql_shared_examples.rb @@ -1,11 +1,11 @@ -require 'spec_helper' +require "spec_helper" -shared_examples 'a working graphql query' do +shared_examples "a working graphql query" do include GraphqlHelpers - it 'returns a successful response', :aggregate_failures do + it "returns a successful response", :aggregate_failures do expect(response).to have_gitlab_http_status(:success) expect(graphql_errors).to be_nil - expect(json_response.keys).to include('data') + expect(json_response.keys).to include("data") end end diff --git a/spec/support/shared_examples/serializers/diff_file_entity_examples.rb b/spec/support/shared_examples/serializers/diff_file_entity_examples.rb index 96cb71be737..037ace7c5b4 100644 --- a/spec/support/shared_examples/serializers/diff_file_entity_examples.rb +++ b/spec/support/shared_examples/serializers/diff_file_entity_examples.rb @@ -1,20 +1,20 @@ # frozen_string_literal: true -shared_examples 'diff file base entity' do - it 'exposes essential attributes' do +shared_examples "diff file base entity" do + it "exposes essential attributes" do expect(subject).to include(:content_sha, :submodule, :submodule_link, - :submodule_tree_url, :old_path_html, - :new_path_html, :blob, :can_modify_blob, - :file_hash, :file_path, :old_path, :new_path, - :viewer, :diff_refs, :stored_externally, - :external_storage, :renamed_file, :deleted_file, - :a_mode, :b_mode, :new_file) + :submodule_tree_url, :old_path_html, + :new_path_html, :blob, :can_modify_blob, + :file_hash, :file_path, :old_path, :new_path, + :viewer, :diff_refs, :stored_externally, + :external_storage, :renamed_file, :deleted_file, + :a_mode, :b_mode, :new_file) end # Converted diff files from GitHub import does not contain blob file # and content sha. - context 'when diff file does not have a blob and content sha' do - it 'exposes some attributes as nil' do + context "when diff file does not have a blob and content sha" do + it "exposes some attributes as nil" do allow(diff_file).to receive(:content_sha).and_return(nil) allow(diff_file).to receive(:blob).and_return(nil) @@ -26,21 +26,21 @@ shared_examples 'diff file base entity' do end end -shared_examples 'diff file entity' do - it_behaves_like 'diff file base entity' +shared_examples "diff file entity" do + it_behaves_like "diff file base entity" - it 'exposes correct attributes' do + it "exposes correct attributes" do expect(subject).to include(:added_lines, :removed_lines, - :context_lines_path, :highlighted_diff_lines, - :parallel_diff_lines) + :context_lines_path, :highlighted_diff_lines, + :parallel_diff_lines) end - it 'includes viewer' do + it "includes viewer" do expect(subject[:viewer].with_indifferent_access) - .to match_schema('entities/diff_viewer') + .to match_schema("entities/diff_viewer") end end -shared_examples 'diff file discussion entity' do - it_behaves_like 'diff file base entity' +shared_examples "diff file discussion entity" do + it_behaves_like "diff file base entity" end diff --git a/spec/support/shared_examples/serializers/note_entity_examples.rb b/spec/support/shared_examples/serializers/note_entity_examples.rb index ec208aba2a9..5f7fc5f6281 100644 --- a/spec/support/shared_examples/serializers/note_entity_examples.rb +++ b/spec/support/shared_examples/serializers/note_entity_examples.rb @@ -1,41 +1,41 @@ -shared_examples 'note entity' do +shared_examples "note entity" do subject { entity.as_json } - context 'basic note' do - it 'exposes correct elements' do + context "basic note" do + it "exposes correct elements" do expect(subject).to include(:type, :author, :note, :note_html, :current_user, :discussion_id, :emoji_awardable, :award_emoji, :report_abuse_path, :attachment, :noteable_note_url, :resolvable) end - it 'does not expose elements for specific notes cases' do + it "does not expose elements for specific notes cases" do expect(subject).not_to include(:last_edited_by, :last_edited_at, :system_note_icon_name) end - it 'exposes author correctly' do + it "exposes author correctly" do expect(subject[:author]).to include(:id, :name, :username, :state, :avatar_url, :path) end - it 'does not expose web_url for author' do + it "does not expose web_url for author" do expect(subject[:author]).not_to include(:web_url) end end - context 'when note was edited' do + context "when note was edited" do before do note.update(updated_at: 1.minute.from_now, updated_by: user) end - it 'exposes last_edited_at and last_edited_by elements' do + it "exposes last_edited_at and last_edited_by elements" do expect(subject).to include(:last_edited_at, :last_edited_by) end end - context 'when note is a system note' do + context "when note is a system note" do before do note.update(system: true) end - it 'exposes system_note_icon_name element' do + it "exposes system_note_icon_name element" do expect(subject).to include(:system_note_icon_name) end end diff --git a/spec/support/shared_examples/services/boards/boards_create_service.rb b/spec/support/shared_examples/services/boards/boards_create_service.rb index 5bdc04f660f..343a8c86656 100644 --- a/spec/support/shared_examples/services/boards/boards_create_service.rb +++ b/spec/support/shared_examples/services/boards/boards_create_service.rb @@ -1,10 +1,10 @@ -shared_examples 'boards create service' do - context 'when parent does not have a board' do - it 'creates a new board' do +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) end - it 'creates the default lists' do + it "creates the default lists" do board = service.execute expect(board.lists.size).to eq 2 @@ -13,12 +13,12 @@ shared_examples 'boards create service' do end end - context 'when parent has a board' do + context "when parent has a board" do before do create(:board, parent: parent) end - it 'does not create a new board' 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) diff --git a/spec/support/shared_examples/services/boards/boards_list_service.rb b/spec/support/shared_examples/services/boards/boards_list_service.rb index e0d5a7c61f2..d2641361d66 100644 --- a/spec/support/shared_examples/services/boards/boards_list_service.rb +++ b/spec/support/shared_examples/services/boards/boards_list_service.rb @@ -1,27 +1,27 @@ -shared_examples 'boards list service' do - context 'when parent does not have a board' do - it 'creates a new parent board' do +shared_examples "boards list service" do + context "when parent does not have a board" do + it "creates a new parent board" do expect { service.execute }.to change(parent.boards, :count).by(1) end - it 'delegates the parent board creation to Boards::CreateService' do + it "delegates the parent board creation to Boards::CreateService" do expect_any_instance_of(Boards::CreateService).to receive(:execute).once service.execute end end - context 'when parent has a board' do + context "when parent has a board" do before do create(:board, parent: parent) end - it 'does not create a new board' do + it "does not create a new board" do expect { service.execute }.not_to change(parent.boards, :count) end end - it 'returns parent boards' do + it "returns parent boards" do board = create(:board, parent: parent) expect(service.execute).to eq [board] diff --git a/spec/support/shared_examples/services/boards/issues_list_service.rb b/spec/support/shared_examples/services/boards/issues_list_service.rb index 8b879cef084..58b63aa4765 100644 --- a/spec/support/shared_examples/services/boards/issues_list_service.rb +++ b/spec/support/shared_examples/services/boards/issues_list_service.rb @@ -1,15 +1,15 @@ -shared_examples 'issues list service' do - it 'delegates search to IssuesFinder' do - params = { board_id: board.id, id: list1.id } +shared_examples "issues list service" do + it "delegates search to IssuesFinder" do + params = {board_id: board.id, id: list1.id} expect_any_instance_of(IssuesFinder).to receive(:execute).once.and_call_original described_class.new(parent, user, params).execute end - context '#metadata' do - it 'returns issues count for list' do - params = { board_id: board.id, id: list1.id } + context "#metadata" do + it "returns issues count for list" do + params = {board_id: board.id, id: list1.id} metadata = described_class.new(parent, user, params).metadata @@ -17,33 +17,33 @@ shared_examples 'issues list service' do end end - context 'issues are ordered by priority' do - it 'returns opened issues when list_id is missing' do - params = { board_id: board.id } + context "issues are ordered by priority" do + it "returns opened issues when list_id is missing" do + params = {board_id: board.id} issues = described_class.new(parent, user, params).execute expect(issues).to eq [opened_issue2, reopened_issue1, opened_issue1] end - it 'returns opened issues when listing issues from Backlog' do - params = { board_id: board.id, id: backlog.id } + it "returns opened issues when listing issues from Backlog" do + params = {board_id: board.id, id: backlog.id} issues = described_class.new(parent, user, params).execute expect(issues).to eq [opened_issue2, reopened_issue1, opened_issue1] end - it 'returns closed issues when listing issues from Closed' do - params = { board_id: board.id, id: closed.id } + it "returns closed issues when listing issues from Closed" do + params = {board_id: board.id, id: closed.id} issues = described_class.new(parent, user, params).execute expect(issues).to eq [closed_issue4, closed_issue2, closed_issue5, closed_issue3, closed_issue1] end - it 'returns opened issues that have label list applied when listing issues from a label list' do - params = { board_id: board.id, id: list1.id } + it "returns opened issues that have label list applied when listing issues from a label list" do + params = {board_id: board.id, id: list1.id} issues = described_class.new(parent, user, params).execute @@ -51,8 +51,8 @@ shared_examples 'issues list service' do end end - context 'with list that does not belong to the board' do - it 'raises an error' do + context "with list that does not belong to the board" do + it "raises an error" do list = create(:list) service = described_class.new(parent, user, board_id: board.id, id: list.id) @@ -60,8 +60,8 @@ shared_examples 'issues list service' do end end - context 'with invalid list id' do - it 'raises an error' do + context "with invalid list id" do + it "raises an error" do service = described_class.new(parent, user, board_id: board.id, id: nil) expect { service.execute }.to raise_error(ActiveRecord::RecordNotFound) diff --git a/spec/support/shared_examples/services/boards/issues_move_service.rb b/spec/support/shared_examples/services/boards/issues_move_service.rb index 9dbd1d8e867..07fc2dd01af 100644 --- a/spec/support/shared_examples/services/boards/issues_move_service.rb +++ b/spec/support/shared_examples/services/boards/issues_move_service.rb @@ -1,9 +1,9 @@ -shared_examples 'issues move service' do |group| - context 'when moving an issue between lists' do +shared_examples "issues move service" do |group| + context "when moving an issue between lists" do let(:issue) { create(:labeled_issue, project: project, labels: [bug, development]) } - let(:params) { { board_id: board1.id, from_list_id: list1.id, to_list_id: list2.id } } + let(:params) { {board_id: board1.id, from_list_id: list1.id, to_list_id: list2.id} } - it 'delegates the label changes to Issues::UpdateService' do + it "delegates the label changes to Issues::UpdateService" do service = double(:service) expect(Issues::UpdateService).to receive(:new).and_return(service) expect(service).to receive(:execute).with(issue).once @@ -11,26 +11,26 @@ shared_examples 'issues move service' do |group| described_class.new(parent, user, params).execute(issue) end - it 'removes the label from the list it came from and adds the label of the list it goes to' do + it "removes the label from the list it came from and adds the label of the list it goes to" do described_class.new(parent, user, params).execute(issue) expect(issue.reload.labels).to contain_exactly(bug, testing) end end - context 'when moving to closed' do + context "when moving to closed" do let!(:list3) { create(:list, board: board2, label: regression, position: 1) } let(:issue) { create(:labeled_issue, project: project, labels: [bug, development, testing, regression]) } - let(:params) { { board_id: board1.id, from_list_id: list2.id, to_list_id: closed.id } } + let(:params) { {board_id: board1.id, from_list_id: list2.id, to_list_id: closed.id} } - it 'delegates the close proceedings to Issues::CloseService' do + it "delegates the close proceedings to Issues::CloseService" do expect_any_instance_of(Issues::CloseService).to receive(:execute).with(issue).once described_class.new(parent, user, params).execute(issue) end - it 'removes all list-labels from boards and close the issue' do + it "removes all list-labels from boards and close the issue" do described_class.new(parent, user, params).execute(issue) issue.reload @@ -39,14 +39,14 @@ shared_examples 'issues move service' do |group| end end - context 'when moving to backlog' do + context "when moving to backlog" do let(:milestone) { create(:milestone, project: project) } let!(:backlog) { create(:backlog_list, board: board1) } let(:issue) { create(:labeled_issue, project: project, labels: [bug, development, testing, regression], milestone: milestone) } - let(:params) { { board_id: board1.id, from_list_id: list2.id, to_list_id: backlog.id } } + let(:params) { {board_id: board1.id, from_list_id: list2.id, to_list_id: backlog.id} } - it 'keeps labels and milestone' do + it "keeps labels and milestone" do described_class.new(parent, user, params).execute(issue) issue.reload @@ -55,17 +55,17 @@ shared_examples 'issues move service' do |group| end end - context 'when moving from closed' do + context "when moving from closed" do let(:issue) { create(:labeled_issue, :closed, project: project, labels: [bug]) } - let(:params) { { board_id: board1.id, from_list_id: closed.id, to_list_id: list2.id } } + let(:params) { {board_id: board1.id, from_list_id: closed.id, to_list_id: list2.id} } - it 'delegates the re-open proceedings to Issues::ReopenService' do + it "delegates the re-open proceedings to Issues::ReopenService" do expect_any_instance_of(Issues::ReopenService).to receive(:execute).with(issue).once described_class.new(parent, user, params).execute(issue) end - it 'adds the label of the list it goes to and reopen the issue' do + it "adds the label of the list it goes to and reopen the issue" do described_class.new(parent, user, params).execute(issue) issue.reload @@ -74,23 +74,23 @@ shared_examples 'issues move service' do |group| end end - context 'when moving to same list' do + context "when moving to same list" do let(:issue) { create(:labeled_issue, project: project, labels: [bug, development]) } let(:issue1) { create(:labeled_issue, project: project, labels: [bug, development]) } let(:issue2) { create(:labeled_issue, project: project, labels: [bug, development]) } - let(:params) { { board_id: board1.id, from_list_id: list1.id, to_list_id: list1.id } } + let(:params) { {board_id: board1.id, from_list_id: list1.id, to_list_id: list1.id} } - it 'returns false' do + it "returns false" do expect(described_class.new(parent, user, params).execute(issue)).to eq false end - it 'keeps issues labels' do + it "keeps issues labels" do described_class.new(parent, user, params).execute(issue) expect(issue.reload.labels).to contain_exactly(bug, development) end - it 'sorts issues' do + it "sorts issues" do [issue, issue1, issue2].each do |issue| issue.move_to_end && issue.save! end @@ -103,11 +103,11 @@ shared_examples 'issues move service' do |group| end if group - context 'when on a group board' do - it 'sends the board_group_id parameter' do + context "when on a group board" do + it "sends the board_group_id parameter" do params.merge!(move_after_id: issue1.id, move_before_id: issue2.id) - match_params = { move_between_ids: [issue1.id, issue2.id], board_group_id: parent.id } + match_params = {move_between_ids: [issue1.id, issue2.id], board_group_id: parent.id} expect(Issues::UpdateService).to receive(:new).with(issue.project, user, match_params).and_return(double(execute: build(:issue))) described_class.new(parent, user, params).execute(issue) diff --git a/spec/support/shared_examples/services/boards/lists_destroy_service.rb b/spec/support/shared_examples/services/boards/lists_destroy_service.rb index 62b6ffe1836..e9734c46e6e 100644 --- a/spec/support/shared_examples/services/boards/lists_destroy_service.rb +++ b/spec/support/shared_examples/services/boards/lists_destroy_service.rb @@ -1,13 +1,13 @@ -shared_examples 'lists destroy service' do - context 'when list type is label' do - it 'removes list from board' do +shared_examples "lists destroy service" do + context "when list type is label" do + it "removes list from board" do list = create(:list, board: board) service = described_class.new(parent, user) expect { service.execute(list) }.to change(board.lists, :count).by(-1) end - it 'decrements position of higher lists' do + it "decrements position of higher lists" do development = create(:list, board: board, position: 0) review = create(:list, board: board, position: 1) staging = create(:list, board: board, position: 2) @@ -21,7 +21,7 @@ shared_examples 'lists destroy service' do end end - it 'does not remove list from board when list type is closed' do + it "does not remove list from board when list type is closed" do list = board.closed_list service = described_class.new(parent, user) diff --git a/spec/support/shared_examples/services/boards/lists_list_service.rb b/spec/support/shared_examples/services/boards/lists_list_service.rb index 0a8220111ab..b7b89b3aeea 100644 --- a/spec/support/shared_examples/services/boards/lists_list_service.rb +++ b/spec/support/shared_examples/services/boards/lists_list_service.rb @@ -1,8 +1,8 @@ -shared_examples 'lists list service' do - context 'when the board has a backlog list' do +shared_examples "lists list service" do + context "when the board has a backlog list" do let!(:backlog_list) { create(:backlog_list, board: board) } - it 'does not create a backlog list' do + it "does not create a backlog list" do expect { service.execute(board) }.not_to change(board.lists, :count) end @@ -11,8 +11,8 @@ shared_examples 'lists list service' do end end - context 'when the board does not have a backlog list' do - it 'creates a backlog list' 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) end diff --git a/spec/support/shared_examples/services/boards/lists_move_service.rb b/spec/support/shared_examples/services/boards/lists_move_service.rb index 2cdb968a45d..ea1cfec98cb 100644 --- a/spec/support/shared_examples/services/boards/lists_move_service.rb +++ b/spec/support/shared_examples/services/boards/lists_move_service.rb @@ -1,12 +1,12 @@ -shared_examples 'lists move service' do +shared_examples "lists move service" do let!(:planning) { create(:list, board: board, position: 0) } let!(:development) { create(:list, board: board, position: 1) } let!(:review) { create(:list, board: board, position: 2) } let!(:staging) { create(:list, board: board, position: 3) } let!(:closed) { create(:closed_list, board: board) } - context 'when list type is set to label' do - it 'keeps position of lists when new position is nil' do + context "when list type is set to label" do + it "keeps position of lists when new position is nil" do service = described_class.new(parent, user, position: nil) service.execute(planning) @@ -14,7 +14,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [0, 1, 2, 3] end - it 'keeps position of lists when new position is equal to old position' do + it "keeps position of lists when new position is equal to old position" do service = described_class.new(parent, user, position: planning.position) service.execute(planning) @@ -22,7 +22,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [0, 1, 2, 3] end - it 'keeps position of lists when new position is negative' do + it "keeps position of lists when new position is negative" do service = described_class.new(parent, user, position: -1) service.execute(planning) @@ -30,7 +30,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [0, 1, 2, 3] end - it 'keeps position of lists when new position is equal to number of labels lists' do + it "keeps position of lists when new position is equal to number of labels lists" do service = described_class.new(parent, user, position: board.lists.label.size) service.execute(planning) @@ -38,7 +38,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [0, 1, 2, 3] end - it 'keeps position of lists when new position is greater than number of labels lists' do + it "keeps position of lists when new position is greater than number of labels lists" do service = described_class.new(parent, user, position: board.lists.label.size + 1) service.execute(planning) @@ -46,7 +46,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [0, 1, 2, 3] end - it 'increments position of intermediate lists when new position is equal to first position' do + it "increments position of intermediate lists when new position is equal to first position" do service = described_class.new(parent, user, position: 0) service.execute(staging) @@ -54,7 +54,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [1, 2, 3, 0] end - it 'decrements position of intermediate lists when new position is equal to last position' do + it "decrements position of intermediate lists when new position is equal to last position" do service = described_class.new(parent, user, position: board.lists.label.last.position) service.execute(planning) @@ -62,7 +62,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [3, 0, 1, 2] end - it 'decrements position of intermediate lists when new position is greater than old position' do + it "decrements position of intermediate lists when new position is greater than old position" do service = described_class.new(parent, user, position: 2) service.execute(planning) @@ -70,7 +70,7 @@ shared_examples 'lists move service' do expect(current_list_positions).to eq [2, 0, 1, 3] end - it 'increments position of intermediate lists when new position is lower than old position' do + it "increments position of intermediate lists when new position is lower than old position" do service = described_class.new(parent, user, position: 1) service.execute(staging) @@ -79,7 +79,7 @@ shared_examples 'lists move service' do end end - it 'keeps position of lists when list type is closed' do + it "keeps position of lists when list type is closed" do service = described_class.new(parent, user, position: 2) service.execute(closed) diff --git a/spec/support/shared_examples/services/check_ingress_ip_address_service_shared_examples.rb b/spec/support/shared_examples/services/check_ingress_ip_address_service_shared_examples.rb index 14638a574a5..4447bc92f01 100644 --- a/spec/support/shared_examples/services/check_ingress_ip_address_service_shared_examples.rb +++ b/spec/support/shared_examples/services/check_ingress_ip_address_service_shared_examples.rb @@ -1,27 +1,27 @@ -shared_examples 'check ingress ip executions' do |app_name| - describe '#execute' do +shared_examples "check ingress ip executions" do |app_name| + describe "#execute" do let(:application) { create(app_name, :installed) } let(:service) { described_class.new(application) } let(:kubeclient) { double(::Kubeclient::Client, get_service: kube_service) } - context 'when the ingress ip address is available' do - it 'updates the external_ip for the app' do + context "when the ingress ip address is available" do + it "updates the external_ip for the app" do subject - expect(application.external_ip).to eq('111.222.111.222') + expect(application.external_ip).to eq("111.222.111.222") end end - context 'when the ingress ip address is not available' do + context "when the ingress ip address is not available" do let(:ingress) { nil } - it 'does not error' do + it "does not error" do subject end end - context 'when the exclusive lease cannot be obtained' do - it 'does not call kubeclient' do + context "when the exclusive lease cannot be obtained" do + it "does not call kubeclient" do stub_exclusive_lease_taken(lease_key, timeout: 15.seconds.to_i) subject diff --git a/spec/support/shared_examples/services/gitlab_projects_import_service_shared_examples.rb b/spec/support/shared_examples/services/gitlab_projects_import_service_shared_examples.rb index b8db35a6ef9..c154fc2d3de 100644 --- a/spec/support/shared_examples/services/gitlab_projects_import_service_shared_examples.rb +++ b/spec/support/shared_examples/services/gitlab_projects_import_service_shared_examples.rb @@ -1,8 +1,8 @@ -shared_examples 'gitlab projects import validations' do - context 'with an invalid path' do - let(:path) { '/invalid-path/' } +shared_examples "gitlab projects import validations" do + context "with an invalid path" do + let(:path) { "/invalid-path/" } - it 'returns an invalid project' do + it "returns an invalid project" do project = subject.execute expect(project).not_to be_persisted @@ -10,8 +10,8 @@ shared_examples 'gitlab projects import validations' do end end - context 'with a valid path' do - it 'creates a project' do + context "with a valid path" do + it "creates a project" do project = subject.execute expect(project).to be_persisted @@ -19,31 +19,31 @@ shared_examples 'gitlab projects import validations' do end end - context 'override params' do - it 'stores them as import data when passed' do + context "override params" do + it "stores them as import data when passed" do project = described_class - .new(namespace.owner, import_params, description: 'Hello') - .execute + .new(namespace.owner, import_params, description: "Hello") + .execute - expect(project.import_data.data['override_params']['description']).to eq('Hello') + expect(project.import_data.data["override_params"]["description"]).to eq("Hello") end end - context 'when there is a project with the same path' do + context "when there is a project with the same path" do let(:existing_project) { create(:project, namespace: namespace) } let(:path) { existing_project.path} - it 'does not create the project' do + it "does not create the project" do project = subject.execute expect(project).to be_invalid expect(project).not_to be_persisted end - context 'when overwrite param is set' do + context "when overwrite param is set" do let(:overwrite) { true } - it 'creates a project in a temporary full_path' do + it "creates a project in a temporary full_path" do project = subject.execute expect(project).to be_valid diff --git a/spec/support/shared_examples/showing_user_status_shared_examples.rb b/spec/support/shared_examples/showing_user_status_shared_examples.rb index eef769de2fc..40411f091c4 100644 --- a/spec/support/shared_examples/showing_user_status_shared_examples.rb +++ b/spec/support/shared_examples/showing_user_status_shared_examples.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true -shared_examples 'showing user status' do - let!(:status) { create(:user_status, user: user_with_status, emoji: 'smirk', message: 'Authoring this object') } +shared_examples "showing user status" do + let!(:status) { create(:user_status, user: user_with_status, emoji: "smirk", message: "Authoring this object") } - it 'shows the status' do + it "shows the status" do subject expect(page).to show_user_status(status) diff --git a/spec/support/shared_examples/slack_mattermost_notifications_shared_examples.rb b/spec/support/shared_examples/slack_mattermost_notifications_shared_examples.rb index 940c24c8d67..1b8a87a1ff2 100644 --- a/spec/support/shared_examples/slack_mattermost_notifications_shared_examples.rb +++ b/spec/support/shared_examples/slack_mattermost_notifications_shared_examples.rb @@ -1,12 +1,12 @@ Dir[Rails.root.join("app/models/project_services/chat_message/*.rb")].each { |f| require f } -RSpec.shared_examples 'slack or mattermost notifications' do +RSpec.shared_examples "slack or mattermost notifications" do let(:chat_service) { described_class.new } - let(:webhook_url) { 'https://example.gitlab.com/' } + let(:webhook_url) { "https://example.gitlab.com/" } def execute_with_options(options) receive(:new).with(webhook_url, options) - .and_return(double(:slack_service).as_null_object) + .and_return(double(:slack_service).as_null_object) end describe "Associations" do @@ -14,17 +14,17 @@ RSpec.shared_examples 'slack or mattermost notifications' do it { is_expected.to have_one :service_hook } end - describe 'Validations' do - context 'when service is active' do + describe "Validations" do + context "when service is active" do before do subject.active = true end it { is_expected.to validate_presence_of(:webhook) } - it_behaves_like 'issue tracker service URL attribute', :webhook + it_behaves_like "issue tracker service URL attribute", :webhook end - context 'when service is inactive' do + context "when service is inactive" do before do subject.active = false end @@ -36,9 +36,9 @@ RSpec.shared_examples 'slack or mattermost notifications' do describe "#execute" do let(:user) { create(:user) } let(:project) { create(:project, :repository, :wiki_repo) } - let(:username) { 'slack_username' } - let(:channel) { 'slack_channel' } - let(:issue_service_options) { { title: 'Awesome issue', description: 'please fix' } } + let(:username) { "slack_username" } + let(:channel) { "slack_channel" } + let(:issue_service_options) { {title: "Awesome issue", description: "please fix"} } let(:push_sample_data) do Gitlab::DataBuilder::Push.build_sample(project, user) @@ -56,30 +56,30 @@ RSpec.shared_examples 'slack or mattermost notifications' do issue_service = Issues::CreateService.new(project, user, issue_service_options) @issue = issue_service.execute - @issues_sample_data = issue_service.hook_data(@issue, 'open') + @issues_sample_data = issue_service.hook_data(@issue, "open") project.add_developer(user) opts = { - title: 'Awesome merge_request', - description: 'please fix', - source_branch: 'feature', - target_branch: 'master' + title: "Awesome merge_request", + description: "please fix", + source_branch: "feature", + target_branch: "master", } merge_service = MergeRequests::CreateService.new(project, - user, opts) + user, opts) @merge_request = merge_service.execute @merge_sample_data = merge_service.hook_data(@merge_request, - 'open') + "open") opts = { title: "Awesome wiki_page", content: "Some text describing some thing or another", format: "md", - message: "user created page: Awesome wiki_page" + message: "user created page: Awesome wiki_page", } @wiki_page = create(:wiki_page, wiki: project.wiki, attrs: opts) - @wiki_page_sample_data = Gitlab::DataBuilder::WikiPage.build(@wiki_page, user, 'create') + @wiki_page_sample_data = Gitlab::DataBuilder::WikiPage.build(@wiki_page, user, "create") end it "calls Slack/Mattermost API for push events" do @@ -106,19 +106,19 @@ RSpec.shared_examples 'slack or mattermost notifications' do expect(WebMock).to have_requested(:post, webhook_url).once end - it 'uses the username as an option for slack when configured' do + it "uses the username as an option for slack when configured" do allow(chat_service).to receive(:username).and_return(username) expect(Slack::Notifier).to receive(:new) - .with(webhook_url, username: username) - .and_return( - double(:slack_service).as_null_object - ) + .with(webhook_url, username: username) + .and_return( + double(:slack_service).as_null_object + ) chat_service.execute(push_sample_data) end - it 'uses the channel as an option when it is configured' do + it "uses the channel as an option when it is configured" do allow(chat_service).to receive(:channel).and_return(channel) expect(Slack::Notifier).to receive(:new) .with(webhook_url, channel: channel) @@ -133,10 +133,10 @@ RSpec.shared_examples 'slack or mattermost notifications' do chat_service.update(push_channel: "random") expect(Slack::Notifier).to receive(:new) - .with(webhook_url, channel: "random") - .and_return( - double(:slack_service).as_null_object - ) + .with(webhook_url, channel: "random") + .and_return( + double(:slack_service).as_null_object + ) chat_service.execute(push_sample_data) end @@ -145,10 +145,10 @@ RSpec.shared_examples 'slack or mattermost notifications' do chat_service.update(merge_request_channel: "random") expect(Slack::Notifier).to receive(:new) - .with(webhook_url, channel: "random") - .and_return( - double(:slack_service).as_null_object - ) + .with(webhook_url, channel: "random") + .and_return( + double(:slack_service).as_null_object + ) chat_service.execute(@merge_sample_data) end @@ -157,29 +157,29 @@ RSpec.shared_examples 'slack or mattermost notifications' do chat_service.update(issue_channel: "random") expect(Slack::Notifier).to receive(:new) - .with(webhook_url, channel: "random") - .and_return( - double(:slack_service).as_null_object - ) + .with(webhook_url, channel: "random") + .and_return( + double(:slack_service).as_null_object + ) chat_service.execute(@issues_sample_data) end - context 'for confidential issues' do - let(:issue_service_options) { { title: 'Secret', confidential: true } } + context "for confidential issues" do + let(:issue_service_options) { {title: "Secret", confidential: true} } it "uses confidential issue channel" do - chat_service.update(confidential_issue_channel: 'confidential') + chat_service.update(confidential_issue_channel: "confidential") - expect(Slack::Notifier).to execute_with_options(channel: 'confidential') + expect(Slack::Notifier).to execute_with_options(channel: "confidential") chat_service.execute(@issues_sample_data) end - it 'falls back to issue channel' do - chat_service.update(issue_channel: 'fallback_channel') + it "falls back to issue channel" do + chat_service.update(issue_channel: "fallback_channel") - expect(Slack::Notifier).to execute_with_options(channel: 'fallback_channel') + expect(Slack::Notifier).to execute_with_options(channel: "fallback_channel") chat_service.execute(@issues_sample_data) end @@ -189,10 +189,10 @@ RSpec.shared_examples 'slack or mattermost notifications' do chat_service.update(wiki_page_channel: "random") expect(Slack::Notifier).to receive(:new) - .with(webhook_url, channel: "random") - .and_return( - double(:slack_service).as_null_object - ) + .with(webhook_url, channel: "random") + .and_return( + double(:slack_service).as_null_object + ) chat_service.execute(@wiki_page_sample_data) end @@ -208,15 +208,15 @@ RSpec.shared_examples 'slack or mattermost notifications' do note_data = Gitlab::DataBuilder::Note.build(issue_note, user) expect(Slack::Notifier).to receive(:new) - .with(webhook_url, channel: "random") - .and_return( - double(:slack_service).as_null_object - ) + .with(webhook_url, channel: "random") + .and_return( + double(:slack_service).as_null_object + ) chat_service.execute(note_data) end - context 'for confidential notes' do + context "for confidential notes" do before do issue_note.noteable.update!(confidential: true) end @@ -226,17 +226,17 @@ RSpec.shared_examples 'slack or mattermost notifications' do note_data = Gitlab::DataBuilder::Note.build(issue_note, user) - expect(Slack::Notifier).to execute_with_options(channel: 'confidential') + expect(Slack::Notifier).to execute_with_options(channel: "confidential") chat_service.execute(note_data) end - it 'falls back to note channel' do + it "falls back to note channel" do chat_service.update(note_channel: "fallback_channel") note_data = Gitlab::DataBuilder::Note.build(issue_note, user) - expect(Slack::Notifier).to execute_with_options(channel: 'fallback_channel') + expect(Slack::Notifier).to execute_with_options(channel: "fallback_channel") chat_service.execute(note_data) end @@ -245,7 +245,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - describe 'Push events' do + describe "Push events" do let(:user) { create(:user) } let(:project) { create(:project, :repository, creator: user) } @@ -259,13 +259,13 @@ RSpec.shared_examples 'slack or mattermost notifications' do WebMock.stub_request(:post, webhook_url) end - context 'only notify for the default branch' do - context 'when enabled' do + context "only notify for the default branch" do + context "when enabled" do before do chat_service.notify_only_default_branch = true end - it 'does not notify push events if they are not for the default branch' do + it "does not notify push events if they are not for the default branch" do ref = "#{Gitlab::Git::BRANCH_REF_PREFIX}test" push_sample_data = Gitlab::DataBuilder::Push.build(project, user, nil, nil, ref, []) @@ -274,7 +274,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do expect(WebMock).not_to have_requested(:post, webhook_url) end - it 'notifies about push events for the default branch' do + it "notifies about push events for the default branch" do push_sample_data = Gitlab::DataBuilder::Push.build_sample(project, user) chat_service.execute(push_sample_data) @@ -282,7 +282,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do expect(WebMock).to have_requested(:post, webhook_url).once end - it 'still notifies about pushed tags' do + it "still notifies about pushed tags" do ref = "#{Gitlab::Git::TAG_REF_PREFIX}test" push_sample_data = Gitlab::DataBuilder::Push.build(project, user, nil, nil, ref, []) @@ -292,12 +292,12 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - context 'when disabled' do + context "when disabled" do before do chat_service.notify_only_default_branch = false end - it 'notifies about all push events' do + it "notifies about all push events" do ref = "#{Gitlab::Git::BRANCH_REF_PREFIX}test" push_sample_data = Gitlab::DataBuilder::Push.build(project, user, nil, nil, ref, []) @@ -324,12 +324,12 @@ RSpec.shared_examples 'slack or mattermost notifications' do WebMock.stub_request(:post, webhook_url) end - context 'when commit comment event executed' do + context "when commit comment event executed" do let(:commit_note) do create(:note_on_commit, author: user, project: project, commit_id: project.repository.commit.id, - note: 'a comment on a commit') + note: "a comment on a commit") end it "calls Slack/Mattermost API for commit comment events" do @@ -340,7 +340,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - context 'when merge request comment event executed' do + context "when merge request comment event executed" do let(:merge_request_note) do create(:note_on_merge_request, project: project, note: "merge request note") @@ -354,7 +354,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - context 'when issue comment event executed' do + context "when issue comment event executed" do let(:issue_note) do create(:note_on_issue, project: project, note: "issue note") end @@ -368,7 +368,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - context 'when snippet comment event executed' do + context "when snippet comment event executed" do let(:snippet_note) do create(:note_on_project_snippet, project: project, note: "snippet note") @@ -383,14 +383,14 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - describe 'Pipeline events' do + describe "Pipeline events" do let(:user) { create(:user) } let(:project) { create(:project, :repository) } let(:pipeline) do create(:ci_pipeline, - project: project, status: status, - sha: project.commit.sha, ref: project.default_branch) + project: project, status: status, + sha: project.commit.sha, ref: project.default_branch) end before do @@ -401,12 +401,12 @@ RSpec.shared_examples 'slack or mattermost notifications' do ) end - shared_examples 'call Slack/Mattermost API' do + shared_examples "call Slack/Mattermost API" do before do WebMock.stub_request(:post, webhook_url) end - it 'calls Slack/Mattermost API for pipeline events' do + it "calls Slack/Mattermost API for pipeline events" do data = Gitlab::DataBuilder::Pipeline.build(pipeline) chat_service.execute(data) @@ -414,17 +414,17 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - context 'with failed pipeline' do - let(:status) { 'failed' } + context "with failed pipeline" do + let(:status) { "failed" } - it_behaves_like 'call Slack/Mattermost API' + it_behaves_like "call Slack/Mattermost API" end - context 'with succeeded pipeline' do - let(:status) { 'success' } + context "with succeeded pipeline" do + let(:status) { "success" } - context 'with default to notify_only_broken_pipelines' do - it 'does not call Slack/Mattermost API for pipeline events' do + context "with default to notify_only_broken_pipelines" do + it "does not call Slack/Mattermost API for pipeline events" do data = Gitlab::DataBuilder::Pipeline.build(pipeline) result = chat_service.execute(data) @@ -432,19 +432,19 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - context 'with setting notify_only_broken_pipelines to false' do + context "with setting notify_only_broken_pipelines to false" do before do chat_service.notify_only_broken_pipelines = false end - it_behaves_like 'call Slack/Mattermost API' + it_behaves_like "call Slack/Mattermost API" end end - context 'only notify for the default branch' do - context 'when enabled' do + context "only notify for the default branch" do + context "when enabled" do let(:pipeline) do - create(:ci_pipeline, :failed, project: project, ref: 'not-the-default-branch') + create(:ci_pipeline, :failed, project: project, ref: "not-the-default-branch") end before do @@ -452,7 +452,7 @@ RSpec.shared_examples 'slack or mattermost notifications' do WebMock.stub_request(:post, webhook_url) end - it 'does not call the Slack/Mattermost API for pipeline events' do + it "does not call the Slack/Mattermost API for pipeline events" do data = Gitlab::DataBuilder::Pipeline.build(pipeline) result = chat_service.execute(data) @@ -460,16 +460,16 @@ RSpec.shared_examples 'slack or mattermost notifications' do end end - context 'when disabled' do + context "when disabled" do let(:pipeline) do - create(:ci_pipeline, :failed, project: project, ref: 'not-the-default-branch') + create(:ci_pipeline, :failed, project: project, ref: "not-the-default-branch") end before do chat_service.notify_only_default_branch = false end - it_behaves_like 'call Slack/Mattermost API' + it_behaves_like "call Slack/Mattermost API" end end end diff --git a/spec/support/shared_examples/snippet_visibility.rb b/spec/support/shared_examples/snippet_visibility.rb index 3a7c69b7877..e7d5be3fe6e 100644 --- a/spec/support/shared_examples/snippet_visibility.rb +++ b/spec/support/shared_examples/snippet_visibility.rb @@ -1,4 +1,4 @@ -RSpec.shared_examples 'snippet visibility' do +RSpec.shared_examples "snippet visibility" do let!(:author) { create(:user) } let!(:member) { create(:user) } let!(:external) { create(:user, :external) } @@ -7,7 +7,7 @@ RSpec.shared_examples 'snippet visibility' do { public: Snippet::PUBLIC, internal: Snippet::INTERNAL, - private: Snippet::PRIVATE + private: Snippet::PRIVATE, } end @@ -18,7 +18,7 @@ RSpec.shared_examples 'snippet visibility' do external: external, non_member: create(:user), member: member, - author: author + author: author, } end @@ -26,7 +26,7 @@ RSpec.shared_examples 'snippet visibility' do { public: Gitlab::VisibilityLevel::PUBLIC, internal: Gitlab::VisibilityLevel::INTERNAL, - private: Gitlab::VisibilityLevel::PRIVATE + private: Gitlab::VisibilityLevel::PRIVATE, } end @@ -34,7 +34,7 @@ RSpec.shared_examples 'snippet visibility' do { enabled: ProjectFeature::ENABLED, private: ProjectFeature::PRIVATE, - disabled: ProjectFeature::DISABLED + disabled: ProjectFeature::DISABLED, } end @@ -221,7 +221,7 @@ RSpec.shared_examples 'snippet visibility' do [:private, :disabled, :author, :public, false], [:private, :disabled, :author, :internal, false], - [:private, :disabled, :author, :private, false] + [:private, :disabled, :author, :private, false], ] end @@ -237,23 +237,23 @@ RSpec.shared_examples 'snippet visibility' do end context "For #{params[:project_type]} project and #{params[:user_type]} users" do - it 'should agree with the read_project_snippet policy' do + it "should agree with the read_project_snippet policy" do expect(can?(user, :read_project_snippet, snippet)).to eq(outcome) end - it 'should return proper outcome' do + it "should return proper outcome" do results = described_class.new(user, project: project).execute expect(results.include?(snippet)).to eq(outcome) end end context "Without a given project and #{params[:user_type]} users" do - it 'should return proper outcome' do + it "should return proper outcome" do results = described_class.new(user).execute expect(results.include?(snippet)).to eq(outcome) end - it 'returns no snippets when the user cannot read cross project' do + it "returns no snippets when the user cannot read cross project" do allow(Ability).to receive(:allowed?).and_call_original allow(Ability).to receive(:allowed?).with(user, :read_cross_project) { false } @@ -265,13 +265,13 @@ RSpec.shared_examples 'snippet visibility' do end end - context 'For personal snippets' do + context "For personal snippets" do let!(:users) do { unauthenticated: nil, external: external, non_member: create(:user), - author: author + author: author, } end @@ -290,7 +290,7 @@ RSpec.shared_examples 'snippet visibility' do [:private, :unauthenticated, false], [:private, :external, false], [:private, :non_member, false], - [:private, :author, true] + [:private, :author, true], ] end @@ -299,16 +299,16 @@ RSpec.shared_examples 'snippet visibility' do let!(:snippet) { create(:personal_snippet, visibility_level: snippet_type_visibilities[snippet_visibility], author: author) } context "For personal and #{params[:snippet_visibility]} snippets with #{params[:user_type]} user" do - it 'should agree with read_personal_snippet policy' do + it "should agree with read_personal_snippet policy" do expect(can?(user, :read_personal_snippet, snippet)).to eq(outcome) end - it 'should return proper outcome' do + it "should return proper outcome" do results = described_class.new(user).execute expect(results.include?(snippet)).to eq(outcome) end - it 'should return personal snippets when the user cannot read cross project' do + it "should return personal snippets when the user cannot read cross project" do allow(Ability).to receive(:allowed?).and_call_original allow(Ability).to receive(:allowed?).with(user, :read_cross_project) { false } diff --git a/spec/support/shared_examples/snippets_shared_examples.rb b/spec/support/shared_examples/snippets_shared_examples.rb index 85f0facd5c3..0dcd7020790 100644 --- a/spec/support/shared_examples/snippets_shared_examples.rb +++ b/spec/support/shared_examples/snippets_shared_examples.rb @@ -1,18 +1,18 @@ # These shared examples expect a `snippets` array of snippets -RSpec.shared_examples 'paginated snippets' do |remote: false| +RSpec.shared_examples "paginated snippets" do |remote: false| it "is limited to #{Snippet.default_per_page} items per page" do - expect(page.all('.snippets-list-holder .snippet-row').count).to eq(Snippet.default_per_page) + expect(page.all(".snippets-list-holder .snippet-row").count).to eq(Snippet.default_per_page) end - context 'clicking on the link to the second page' do + context "clicking on the link to the second page" do before do - click_link('2') + click_link("2") wait_for_requests if remote end - it 'shows the remaining snippets' do + it "shows the remaining snippets" do remaining_snippets_count = [snippets.size - Snippet.default_per_page, Snippet.default_per_page].min - expect(page).to have_selector('.snippets-list-holder .snippet-row', count: remaining_snippets_count) + expect(page).to have_selector(".snippets-list-holder .snippet-row", count: remaining_snippets_count) end end end diff --git a/spec/support/shared_examples/taskable_shared_examples.rb b/spec/support/shared_examples/taskable_shared_examples.rb index 4056ff06b84..8d1d2502eb5 100644 --- a/spec/support/shared_examples/taskable_shared_examples.rb +++ b/spec/support/shared_examples/taskable_shared_examples.rb @@ -2,8 +2,8 @@ # # Requires a context containing: # subject { Issue or MergeRequest } -shared_examples 'a Taskable' do - describe 'with multiple tasks' do +shared_examples "a Taskable" do + describe "with multiple tasks" do before do subject.description = <<-EOT.strip_heredoc * [ ] Task 1 @@ -14,26 +14,26 @@ shared_examples 'a Taskable' do EOT end - it 'returns the correct task status' do - expect(subject.task_status).to match('2 of') - expect(subject.task_status).to match('5 tasks completed') - expect(subject.task_status_short).to match('2/') - expect(subject.task_status_short).to match('5 tasks') + it "returns the correct task status" do + expect(subject.task_status).to match("2 of") + expect(subject.task_status).to match("5 tasks completed") + expect(subject.task_status_short).to match("2/") + expect(subject.task_status_short).to match("5 tasks") end - describe '#tasks?' do - it 'returns true when object has tasks' do + describe "#tasks?" do + it "returns true when object has tasks" do expect(subject.tasks?).to eq true end - it 'returns false when object has no tasks' do - subject.description = 'Now I have no tasks' + it "returns false when object has no tasks" do + subject.description = "Now I have no tasks" expect(subject.tasks?).to eq false end end end - describe 'with nested tasks' do + describe "with nested tasks" do before do subject.description = <<-EOT.strip_heredoc - [ ] Task a @@ -49,30 +49,30 @@ shared_examples 'a Taskable' do EOT end - it 'returns the correct task status' do - expect(subject.task_status).to match('3 of') - expect(subject.task_status).to match('9 tasks completed') - expect(subject.task_status_short).to match('3/') - expect(subject.task_status_short).to match('9 tasks') + it "returns the correct task status" do + expect(subject.task_status).to match("3 of") + expect(subject.task_status).to match("9 tasks completed") + expect(subject.task_status_short).to match("3/") + expect(subject.task_status_short).to match("9 tasks") end end - describe 'with an incomplete task' do + describe "with an incomplete task" do before do subject.description = <<-EOT.strip_heredoc * [ ] Task 1 EOT end - it 'returns the correct task status' do - expect(subject.task_status).to match('0 of') - expect(subject.task_status).to match('1 task completed') - expect(subject.task_status_short).to match('0/') - expect(subject.task_status_short).to match('1 task') + it "returns the correct task status" do + expect(subject.task_status).to match("0 of") + expect(subject.task_status).to match("1 task completed") + expect(subject.task_status_short).to match("0/") + expect(subject.task_status_short).to match("1 task") end end - describe 'with tasks that are not formatted correctly' do + describe "with tasks that are not formatted correctly" do before do subject.description = <<-EOT.strip_heredoc [ ] task 1 @@ -83,26 +83,26 @@ shared_examples 'a Taskable' do EOT end - it 'returns the correct task status' do - expect(subject.task_status).to match('0 of') - expect(subject.task_status).to match('0 tasks completed') - expect(subject.task_status_short).to match('0/') - expect(subject.task_status_short).to match('0 task') + it "returns the correct task status" do + expect(subject.task_status).to match("0 of") + expect(subject.task_status).to match("0 tasks completed") + expect(subject.task_status_short).to match("0/") + expect(subject.task_status_short).to match("0 task") end end - describe 'with a complete task' do + describe "with a complete task" do before do subject.description = <<-EOT.strip_heredoc * [x] Task 1 EOT end - it 'returns the correct task status' do - expect(subject.task_status).to match('1 of') - expect(subject.task_status).to match('1 task completed') - expect(subject.task_status_short).to match('1/') - expect(subject.task_status_short).to match('1 task') + it "returns the correct task status" do + expect(subject.task_status).to match("1 of") + expect(subject.task_status).to match("1 task completed") + expect(subject.task_status_short).to match("1/") + expect(subject.task_status_short).to match("1 task") end end end diff --git a/spec/support/shared_examples/throttled_touch.rb b/spec/support/shared_examples/throttled_touch.rb index eba990d4037..2f13ad1c31a 100644 --- a/spec/support/shared_examples/throttled_touch.rb +++ b/spec/support/shared_examples/throttled_touch.rb @@ -1,13 +1,13 @@ -shared_examples_for 'throttled touch' do - describe '#touch' do - it 'updates the updated_at timestamp' do +shared_examples_for "throttled touch" do + describe "#touch" do + it "updates the updated_at timestamp" do Timecop.freeze do subject.touch expect(subject.updated_at).to be_like_time(Time.zone.now) end end - it 'updates the object at most once per minute' do + it "updates the object at most once per minute" do first_updated_at = Time.zone.now - (ThrottledTouch::TOUCH_INTERVAL * 2) second_updated_at = Time.zone.now - (ThrottledTouch::TOUCH_INTERVAL * 1.5) diff --git a/spec/support/shared_examples/time_tracking_shared_examples.rb b/spec/support/shared_examples/time_tracking_shared_examples.rb index 909d4e2ee8d..ca04817092b 100644 --- a/spec/support/shared_examples/time_tracking_shared_examples.rb +++ b/spec/support/shared_examples/time_tracking_shared_examples.rb @@ -1,85 +1,85 @@ -shared_examples 'issuable time tracker' do - it 'renders the sidebar component empty state' do - page.within '.time-tracking-no-tracking-pane' do - expect(page).to have_content 'No estimate or time spent' +shared_examples "issuable time tracker" do + it "renders the sidebar component empty state" do + page.within ".time-tracking-no-tracking-pane" do + expect(page).to have_content "No estimate or time spent" end end - it 'updates the sidebar component when estimate is added' do - submit_time('/estimate 3w 1d 1h') + it "updates the sidebar component when estimate is added" do + submit_time("/estimate 3w 1d 1h") wait_for_requests - page.within '.time-tracking-estimate-only-pane' do - expect(page).to have_content '3w 1d 1h' + page.within ".time-tracking-estimate-only-pane" do + expect(page).to have_content "3w 1d 1h" end end - it 'updates the sidebar component when spent is added' do - submit_time('/spend 3w 1d 1h') + it "updates the sidebar component when spent is added" do + submit_time("/spend 3w 1d 1h") wait_for_requests - page.within '.time-tracking-spend-only-pane' do - expect(page).to have_content '3w 1d 1h' + page.within ".time-tracking-spend-only-pane" do + expect(page).to have_content "3w 1d 1h" end end - it 'shows the comparison when estimate and spent are added' do - submit_time('/estimate 3w 1d 1h') - submit_time('/spend 3w 1d 1h') + it "shows the comparison when estimate and spent are added" do + submit_time("/estimate 3w 1d 1h") + submit_time("/spend 3w 1d 1h") wait_for_requests - page.within '.time-tracking-comparison-pane' do - expect(page).to have_content '3w 1d 1h' + page.within ".time-tracking-comparison-pane" do + expect(page).to have_content "3w 1d 1h" end end - it 'updates the sidebar component when estimate is removed' do - submit_time('/estimate 3w 1d 1h') - submit_time('/remove_estimate') + it "updates the sidebar component when estimate is removed" do + submit_time("/estimate 3w 1d 1h") + submit_time("/remove_estimate") - page.within '.time-tracking-component-wrap' do - expect(page).to have_content 'No estimate or time spent' + page.within ".time-tracking-component-wrap" do + expect(page).to have_content "No estimate or time spent" end end - it 'updates the sidebar component when spent is removed' do - submit_time('/spend 3w 1d 1h') - submit_time('/remove_time_spent') + it "updates the sidebar component when spent is removed" do + submit_time("/spend 3w 1d 1h") + submit_time("/remove_time_spent") - page.within '.time-tracking-component-wrap' do - expect(page).to have_content 'No estimate or time spent' + page.within ".time-tracking-component-wrap" do + expect(page).to have_content "No estimate or time spent" end end - it 'shows the help state when icon is clicked' do - page.within '.time-tracking-component-wrap' do - find('.help-button').click - expect(page).to have_content 'Track time with quick actions' - expect(page).to have_content 'Learn more' + it "shows the help state when icon is clicked" do + page.within ".time-tracking-component-wrap" do + find(".help-button").click + expect(page).to have_content "Track time with quick actions" + expect(page).to have_content "Learn more" end end - it 'hides the help state when close icon is clicked' do - page.within '.time-tracking-component-wrap' do - find('.help-button').click - find('.close-help-button').click + it "hides the help state when close icon is clicked" do + page.within ".time-tracking-component-wrap" do + find(".help-button").click + find(".close-help-button").click - expect(page).not_to have_content 'Track time with quick actions' - expect(page).not_to have_content 'Learn more' + expect(page).not_to have_content "Track time with quick actions" + expect(page).not_to have_content "Learn more" end end - it 'displays the correct help url' do - page.within '.time-tracking-component-wrap' do - find('.help-button').click + it "displays the correct help url" do + page.within ".time-tracking-component-wrap" do + find(".help-button").click - expect(find_link('Learn more')[:href]).to have_content('/help/workflow/time_tracking.md') + expect(find_link("Learn more")[:href]).to have_content("/help/workflow/time_tracking.md") end end end def submit_time(quick_action) - fill_in 'note[note]', with: quick_action - find('.js-comment-submit-button').click + fill_in "note[note]", with: quick_action + find(".js-comment-submit-button").click wait_for_requests end diff --git a/spec/support/shared_examples/unique_ip_check_shared_examples.rb b/spec/support/shared_examples/unique_ip_check_shared_examples.rb index e5c8ac6a004..6bab5404cb1 100644 --- a/spec/support/shared_examples/unique_ip_check_shared_examples.rb +++ b/spec/support/shared_examples/unique_ip_check_shared_examples.rb @@ -1,4 +1,4 @@ -shared_context 'unique ips sign in limit' do +shared_context "unique ips sign in limit" do include StubENV before do Gitlab::Redis::Cache.with(&:flushall) @@ -7,7 +7,7 @@ shared_context 'unique ips sign in limit' do end before do - stub_env('IN_MEMORY_APPLICATION_SETTINGS', 'false') + stub_env("IN_MEMORY_APPLICATION_SETTINGS", "false") Gitlab::CurrentSettings.update!( unique_ips_limit_enabled: true, @@ -31,38 +31,38 @@ shared_context 'unique ips sign in limit' do end end -shared_examples 'user login operation with unique ip limit' do - include_context 'unique ips sign in limit' do +shared_examples "user login operation with unique ip limit" do + include_context "unique ips sign in limit" do before do Gitlab::CurrentSettings.update!(unique_ips_limit_per_user: 1) end - it 'allows user authenticating from the same ip' do - expect { operation_from_ip('ip') }.not_to raise_error - expect { operation_from_ip('ip') }.not_to raise_error + it "allows user authenticating from the same ip" do + expect { operation_from_ip("ip") }.not_to raise_error + expect { operation_from_ip("ip") }.not_to raise_error end - it 'blocks user authenticating from two distinct ips' do - expect { operation_from_ip('ip') }.not_to raise_error - expect { operation_from_ip('ip2') }.to raise_error(Gitlab::Auth::TooManyIps) + it "blocks user authenticating from two distinct ips" do + expect { operation_from_ip("ip") }.not_to raise_error + expect { operation_from_ip("ip2") }.to raise_error(Gitlab::Auth::TooManyIps) end end end -shared_examples 'user login request with unique ip limit' do |success_status = 200| - include_context 'unique ips sign in limit' do +shared_examples "user login request with unique ip limit" do |success_status = 200| + include_context "unique ips sign in limit" do before do Gitlab::CurrentSettings.update!(unique_ips_limit_per_user: 1) end - it 'allows user authenticating from the same ip' do - expect(request_from_ip('ip')).to have_gitlab_http_status(success_status) - expect(request_from_ip('ip')).to have_gitlab_http_status(success_status) + it "allows user authenticating from the same ip" do + expect(request_from_ip("ip")).to have_gitlab_http_status(success_status) + expect(request_from_ip("ip")).to have_gitlab_http_status(success_status) end - it 'blocks user authenticating from two distinct ips' do - expect(request_from_ip('ip')).to have_gitlab_http_status(success_status) - expect(request_from_ip('ip2')).to have_gitlab_http_status(403) + it "blocks user authenticating from two distinct ips" do + expect(request_from_ip("ip")).to have_gitlab_http_status(success_status) + expect(request_from_ip("ip2")).to have_gitlab_http_status(403) end end end diff --git a/spec/support/shared_examples/update_invalid_issuable.rb b/spec/support/shared_examples/update_invalid_issuable.rb index 64568de424e..4edef0294c1 100644 --- a/spec/support/shared_examples/update_invalid_issuable.rb +++ b/spec/support/shared_examples/update_invalid_issuable.rb @@ -1,9 +1,9 @@ -shared_examples 'update invalid issuable' do |klass| +shared_examples "update invalid issuable" do |klass| let(:params) do { namespace_id: project.namespace.path, project_id: project.path, - id: issuable.iid + id: issuable.iid, } end @@ -13,42 +13,42 @@ shared_examples 'update invalid issuable' do |klass| before do if klass == Issue - params.merge!(issue: { title: "any" }) + params.merge!(issue: {title: "any"}) else - params.merge!(merge_request: { title: "any" }) + params.merge!(merge_request: {title: "any"}) end end - context 'when updating causes conflicts' do + context "when updating causes conflicts" do before do allow_any_instance_of(issuable.class).to receive(:save) .and_raise(ActiveRecord::StaleObjectError.new(issuable, :save)) end - it 'renders edit when format is html' do + it "renders edit when format is html" do put :update, params: params expect(response).to render_template(:edit) expect(assigns[:conflict]).to be_truthy end - it 'renders json error message when format is json' do + it "renders json error message when format is json" do params[:format] = "json" put :update, params: params expect(response.status).to eq(409) - expect(JSON.parse(response.body)).to have_key('errors') + expect(JSON.parse(response.body)).to have_key("errors") end end - context 'when updating an invalid issuable' do + context "when updating an invalid issuable" do before do key = klass == Issue ? :issue : :merge_request params[key][:title] = "" end - it 'renders edit when merge request is invalid' do + it "renders edit when merge request is invalid" do put :update, params: params expect(response).to render_template(:edit) diff --git a/spec/support/shared_examples/updating_mentions_shared_examples.rb b/spec/support/shared_examples/updating_mentions_shared_examples.rb index 5e3f19ba19e..2a9c45e593f 100644 --- a/spec/support/shared_examples/updating_mentions_shared_examples.rb +++ b/spec/support/shared_examples/updating_mentions_shared_examples.rb @@ -1,4 +1,4 @@ -RSpec.shared_examples 'updating mentions' do |service_class| +RSpec.shared_examples "updating mentions" do |service_class| let(:mentioned_user) { create(:user) } let(:service_class) { service_class } @@ -14,22 +14,22 @@ RSpec.shared_examples 'updating mentions' do |service_class| mentionable.reload end - context 'in title' do + context "in title" do before do update_mentionable(title: mentioned_user.to_reference) end - it 'emails only the newly-mentioned user' do + it "emails only the newly-mentioned user" do should_only_email(mentioned_user) end end - context 'in description' do + context "in description" do before do update_mentionable(description: mentioned_user.to_reference) end - it 'emails only the newly-mentioned user' do + it "emails only the newly-mentioned user" do should_only_email(mentioned_user) end end diff --git a/spec/support/shared_examples/uploaders/gitlab_uploader_shared_examples.rb b/spec/support/shared_examples/uploaders/gitlab_uploader_shared_examples.rb index 1190863d88e..d49303664f0 100644 --- a/spec/support/shared_examples/uploaders/gitlab_uploader_shared_examples.rb +++ b/spec/support/shared_examples/uploaders/gitlab_uploader_shared_examples.rb @@ -14,7 +14,7 @@ shared_examples "builds correct paths" do |**patterns| let(:patterns) { patterns } before do - allow(subject).to receive(:filename).and_return('<filename>') + allow(subject).to receive(:filename).and_return("<filename>") end describe "#store_dir" do @@ -34,8 +34,8 @@ shared_examples "builds correct paths" do |**patterns| end describe "#relative_path" do - it 'is relative' do - skip 'Path not set, skipping.' unless subject.path + it "is relative" do + skip "Path not set, skipping." unless subject.path expect(Pathname.new(subject.relative_path)).to be_relative end diff --git a/spec/support/shared_examples/uploaders/object_storage_shared_examples.rb b/spec/support/shared_examples/uploaders/object_storage_shared_examples.rb index 1bd176280c5..0ad0e815656 100644 --- a/spec/support/shared_examples/uploaders/object_storage_shared_examples.rb +++ b/spec/support/shared_examples/uploaders/object_storage_shared_examples.rb @@ -1,4 +1,4 @@ -shared_context 'with storage' do |store, **stub_params| +shared_context "with storage" do |store, **stub_params| before do subject.object_store = store end @@ -20,7 +20,7 @@ shared_examples "migrates" do |to_store:, from_store: nil| migrate(from) end - it 'returns corresponding file type' do + it "returns corresponding file type" do expect(subject).to be_an(CarrierWave::Uploader::Base) expect(subject).to be_a(ObjectStorage::Concern) @@ -29,29 +29,29 @@ shared_examples "migrates" do |to_store:, from_store: nil| elsif from == described_class::Store::LOCAL expect(subject.file).to be_a(CarrierWave::SanitizedFile) else - raise 'Unexpected file type' + raise "Unexpected file type" end end - it 'does nothing when migrating to the current store' do + it "does nothing when migrating to the current store" do expect { migrate(from) }.not_to change { subject.object_store }.from(from) end - it 'migrate to the specified store' do + it "migrate to the specified store" do from_checksum = checksum expect { migrate(to) }.to change { subject.object_store }.from(from).to(to) expect(checksum).to eq(from_checksum) end - it 'removes the original file after the migration' do + it "removes the original file after the migration" do original_file = subject.file.path migrate(to) expect(File.exist?(original_file)).to be_falsey end - it 'can access to the original file during migration' do + it "can access to the original file during migration" do file = subject.file allow(subject).to receive(:delete_migrated_file) { } # Remove as a callback of :migrate @@ -61,60 +61,60 @@ shared_examples "migrates" do |to_store:, from_store: nil| expect { migrate(to) }.not_to change { file.exists? } end - context 'when migrate! is not occupied by another process' do - it 'executes migrate!' do + context "when migrate! is not occupied by another process" do + it "executes migrate!" do expect(subject).to receive(:object_store=).at_least(1) migrate(to) end - it 'executes use_file' do + it "executes use_file" do expect(subject).to receive(:unsafe_use_file).once subject.use_file end end - context 'when migrate! is occupied by another process' do + context "when migrate! is occupied by another process" do include ExclusiveLeaseHelpers before do stub_exclusive_lease_taken(subject.exclusive_lease_key, timeout: 1.hour.to_i) end - it 'does not execute migrate!' do + it "does not execute migrate!" do expect(subject).not_to receive(:unsafe_migrate!) expect { migrate(to) }.to raise_error(ObjectStorage::ExclusiveLeaseTaken) end - it 'does not execute use_file' do + it "does not execute use_file" do expect(subject).not_to receive(:unsafe_use_file) expect { subject.use_file }.to raise_error(ObjectStorage::ExclusiveLeaseTaken) end end - context 'migration is unsuccessful' do + context "migration is unsuccessful" do shared_examples "handles gracefully" do |error:| - it 'does not update the object_store' do + it "does not update the object_store" do expect { migrate(to) }.to raise_error(error) expect(subject.object_store).to eq(from) end - it 'does not delete the original file' do + it "does not delete the original file" do expect { migrate(to) }.to raise_error(error) expect(subject.exists?).to be_truthy end end - context 'when the store is not supported' do + context "when the store is not supported" do let(:to) { -1 } # not a valid store include_examples "handles gracefully", error: ObjectStorage::UnknownStoreError end - context 'upon a fog failure' do + context "upon a fog failure" do before do storage_class = subject.send(:storage_for, to).class expect_any_instance_of(storage_class).to receive(:store!).and_raise("Store failure.") @@ -123,7 +123,7 @@ shared_examples "migrates" do |to_store:, from_store: nil| include_examples "handles gracefully", error: "Store failure." end - context 'upon a database failure' do + context "upon a database failure" do before do expect(uploader).to receive(:persist_object_store!).and_raise("ActiveRecord failure.") end diff --git a/spec/support/shared_examples/url_validator_examples.rb b/spec/support/shared_examples/url_validator_examples.rb index 1f7e2f7ff79..e7c779faf82 100644 --- a/spec/support/shared_examples/url_validator_examples.rb +++ b/spec/support/shared_examples/url_validator_examples.rb @@ -1,18 +1,18 @@ -RSpec.shared_examples 'url validator examples' do |protocols| +RSpec.shared_examples "url validator examples" do |protocols| let(:validator) { described_class.new(attributes: [:link_url], **options) } - let!(:badge) { build(:badge, link_url: 'http://www.example.com') } + let!(:badge) { build(:badge, link_url: "http://www.example.com") } subject { validator.validate_each(badge, :link_url, badge.link_url) } - describe '#validates_each' do - context 'with no options' do + describe "#validates_each" do + context "with no options" do let(:options) { {} } - it "allows #{protocols.join(',')} protocols by default" do + it "allows #{protocols.join(",")} protocols by default" do expect(validator.send(:default_options)[:protocols]).to eq protocols end - it 'checks that the url structure is valid' do + it "checks that the url structure is valid" do badge.link_url = "#{badge.link_url}:invalid_port" subject @@ -21,17 +21,17 @@ RSpec.shared_examples 'url validator examples' do |protocols| end end - context 'with protocols' do - let(:options) { { protocols: %w[http] } } + context "with protocols" do + let(:options) { {protocols: %w[http]} } - it 'allows urls with the defined protocols' do + it "allows urls with the defined protocols" do subject expect(badge.errors.empty?).to be true end - it 'add error if the url protocol does not match the selected ones' do - badge.link_url = 'https://www.example.com' + it "add error if the url protocol does not match the selected ones" do + badge.link_url = "https://www.example.com" subject diff --git a/spec/support/shared_examples/wiki_file_attachments_examples.rb b/spec/support/shared_examples/wiki_file_attachments_examples.rb index b6fb2a66b0e..162193bd729 100644 --- a/spec/support/shared_examples/wiki_file_attachments_examples.rb +++ b/spec/support/shared_examples/wiki_file_attachments_examples.rb @@ -3,85 +3,85 @@ # Requires a context containing: # project -shared_examples 'wiki file attachments' do +shared_examples "wiki file attachments" do include DropzoneHelper - context 'uploading attachments', :js do + context "uploading attachments", :js do let(:wiki) { project.wiki } def attach_with_dropzone(wait = false) - dropzone_file([Rails.root.join('spec', 'fixtures', 'dk.png')], 0, wait) + dropzone_file([Rails.root.join("spec", "fixtures", "dk.png")], 0, wait) end - context 'before uploading' do + context "before uploading" do it 'shows "Attach a file" button' do - expect(page).to have_button('Attach a file') - expect(page).not_to have_selector('.uploading-progress-container', visible: true) + expect(page).to have_button("Attach a file") + expect(page).not_to have_selector(".uploading-progress-container", visible: true) end end - context 'uploading is in progress' do + context "uploading is in progress" do it 'cancels uploading on clicking to "Cancel" button' do slow_requests do attach_with_dropzone - click_button 'Cancel' + click_button "Cancel" end - expect(page).to have_button('Attach a file') - expect(page).not_to have_button('Cancel') - expect(page).not_to have_selector('.uploading-progress-container', visible: true) + expect(page).to have_button("Attach a file") + expect(page).not_to have_button("Cancel") + expect(page).not_to have_selector(".uploading-progress-container", visible: true) end it 'shows "Attaching a file" message on uploading 1 file' do slow_requests do attach_with_dropzone - expect(page).to have_selector('.attaching-file-message', visible: true, text: 'Attaching a file -') + expect(page).to have_selector(".attaching-file-message", visible: true, text: "Attaching a file -") end end end - context 'uploading is complete' do + context "uploading is complete" do it 'shows "Attach a file" button on uploading complete' do attach_with_dropzone wait_for_requests - expect(page).to have_button('Attach a file') - expect(page).not_to have_selector('.uploading-progress-container', visible: true) + expect(page).to have_button("Attach a file") + expect(page).not_to have_selector(".uploading-progress-container", visible: true) end - it 'the markdown link is added to the page' do - fill_in(:wiki_content, with: '') + it "the markdown link is added to the page" do + fill_in(:wiki_content, with: "") attach_with_dropzone(true) wait_for_requests - expect(page.find('#wiki_content').value) + expect(page.find("#wiki_content").value) .to match(%r{\!\[dk\]\(uploads/\h{32}/dk\.png\)$}) end - it 'the links point to the wiki root url' do + it "the links point to the wiki root url" do attach_with_dropzone(true) wait_for_requests - find('.js-md-preview-button').click + find(".js-md-preview-button").click file_path = page.find('input[name="files[]"]', visible: :hidden).value - link = page.find('a.no-attachment-icon')['href'] - img_link = page.find('a.no-attachment-icon img')['src'] + link = page.find("a.no-attachment-icon")["href"] + img_link = page.find("a.no-attachment-icon img")["src"] expect(link).to eq img_link expect(URI.parse(link).path).to eq File.join(wiki.wiki_base_path, file_path) end - it 'the file has been added to the wiki repository' do - expect do + it "the file has been added to the wiki repository" do + expect { attach_with_dropzone(true) wait_for_requests - end.to change { wiki.repository.ls_files('HEAD').count }.by(1) + }.to change { wiki.repository.ls_files("HEAD").count }.by(1) file_path = page.find('input[name="files[]"]', visible: :hidden).value - expect(wiki.find_file(file_path, 'HEAD').path).not_to be_nil + expect(wiki.find_file(file_path, "HEAD").path).not_to be_nil end end end diff --git a/spec/support/shoulda/matchers/rails_shim.rb b/spec/support/shoulda/matchers/rails_shim.rb index 8d70598beb5..7a595111565 100644 --- a/spec/support/shoulda/matchers/rails_shim.rb +++ b/spec/support/shoulda/matchers/rails_shim.rb @@ -8,11 +8,11 @@ module Shoulda def self.serialized_attributes_for(model) if defined?(::ActiveRecord::Type::Serialized) # Rails 5+ - serialized_columns = model.columns.select do |column| + serialized_columns = model.columns.select { |column| model.type_for_attribute(column.name).is_a?( ::ActiveRecord::Type::Serialized ) - end + } serialized_columns.inject({}) do |hash, column| # rubocop:disable Style/EachWithObject hash[column.name.to_s] = model.type_for_attribute(column.name).coder diff --git a/spec/support/sidekiq.rb b/spec/support/sidekiq.rb index 6c4e11910d3..9f2b01ac6a7 100644 --- a/spec/support/sidekiq.rb +++ b/spec/support/sidekiq.rb @@ -1,4 +1,4 @@ -require 'sidekiq/testing/inline' +require "sidekiq/testing/inline" # If Sidekiq::Testing.inline! is used, SQL transactions done inside # Sidekiq worker are included in the SQL query limit (in a real diff --git a/spec/support/stored_repositories.rb b/spec/support/stored_repositories.rb index 55212355daa..492ae8947ef 100644 --- a/spec/support/stored_repositories.rb +++ b/spec/support/stored_repositories.rb @@ -1,7 +1,7 @@ RSpec.configure do |config| config.before(:each, :broken_storage) do allow(Gitlab::GitalyClient).to receive(:call) do - raise GRPC::Unavailable.new('Gitaly broken in this spec') + raise GRPC::Unavailable.new("Gitaly broken in this spec") end end end diff --git a/spec/support/stub_version.rb b/spec/support/stub_version.rb index 594ab64e7c6..1a106b7a3fb 100644 --- a/spec/support/stub_version.rb +++ b/spec/support/stub_version.rb @@ -2,7 +2,7 @@ module StubVersion def stub_version(version, revision) - stub_const('Gitlab::VERSION', version) + stub_const("Gitlab::VERSION", version) allow(Gitlab).to receive(:revision).and_return(revision) end end diff --git a/spec/support/test_reports/test_reports_helper.rb b/spec/support/test_reports/test_reports_helper.rb index 45c6e04dbf3..7478be2904e 100644 --- a/spec/support/test_reports/test_reports_helper.rb +++ b/spec/support/test_reports/test_reports_helper.rb @@ -1,39 +1,43 @@ module TestReportsHelper def create_test_case_rspec_success Gitlab::Ci::Reports::TestCase.new( - name: 'Test#sum when a is 1 and b is 3 returns summary', - classname: 'spec.test_spec', - file: './spec/test_spec.rb', + name: "Test#sum when a is 1 and b is 3 returns summary", + classname: "spec.test_spec", + file: "./spec/test_spec.rb", execution_time: 1.11, - status: Gitlab::Ci::Reports::TestCase::STATUS_SUCCESS) + status: Gitlab::Ci::Reports::TestCase::STATUS_SUCCESS + ) end def create_test_case_rspec_failed Gitlab::Ci::Reports::TestCase.new( - name: 'Test#sum when a is 2 and b is 2 returns summary', - classname: 'spec.test_spec', - file: './spec/test_spec.rb', + name: "Test#sum when a is 2 and b is 2 returns summary", + classname: "spec.test_spec", + file: "./spec/test_spec.rb", execution_time: 2.22, system_output: sample_rspec_failed_message, - status: Gitlab::Ci::Reports::TestCase::STATUS_FAILED) + status: Gitlab::Ci::Reports::TestCase::STATUS_FAILED + ) end def create_test_case_rspec_skipped Gitlab::Ci::Reports::TestCase.new( - name: 'Test#sum when a is 3 and b is 3 returns summary', - classname: 'spec.test_spec', - file: './spec/test_spec.rb', + name: "Test#sum when a is 3 and b is 3 returns summary", + classname: "spec.test_spec", + file: "./spec/test_spec.rb", execution_time: 3.33, - status: Gitlab::Ci::Reports::TestCase::STATUS_SKIPPED) + status: Gitlab::Ci::Reports::TestCase::STATUS_SKIPPED + ) end def create_test_case_rspec_error Gitlab::Ci::Reports::TestCase.new( - name: 'Test#sum when a is 4 and b is 4 returns summary', - classname: 'spec.test_spec', - file: './spec/test_spec.rb', + name: "Test#sum when a is 4 and b is 4 returns summary", + classname: "spec.test_spec", + file: "./spec/test_spec.rb", execution_time: 4.44, - status: Gitlab::Ci::Reports::TestCase::STATUS_ERROR) + status: Gitlab::Ci::Reports::TestCase::STATUS_ERROR + ) end def sample_rspec_failed_message @@ -50,35 +54,39 @@ module TestReportsHelper def create_test_case_java_success Gitlab::Ci::Reports::TestCase.new( - name: 'addTest', - classname: 'CalculatorTest', + name: "addTest", + classname: "CalculatorTest", execution_time: 5.55, - status: Gitlab::Ci::Reports::TestCase::STATUS_SUCCESS) + status: Gitlab::Ci::Reports::TestCase::STATUS_SUCCESS + ) end def create_test_case_java_failed Gitlab::Ci::Reports::TestCase.new( - name: 'subtractTest', - classname: 'CalculatorTest', + name: "subtractTest", + classname: "CalculatorTest", execution_time: 6.66, system_output: sample_java_failed_message, - status: Gitlab::Ci::Reports::TestCase::STATUS_FAILED) + status: Gitlab::Ci::Reports::TestCase::STATUS_FAILED + ) end def create_test_case_java_skipped Gitlab::Ci::Reports::TestCase.new( - name: 'multiplyTest', - classname: 'CalculatorTest', + name: "multiplyTest", + classname: "CalculatorTest", execution_time: 7.77, - status: Gitlab::Ci::Reports::TestCase::STATUS_SKIPPED) + status: Gitlab::Ci::Reports::TestCase::STATUS_SKIPPED + ) end def create_test_case_java_error Gitlab::Ci::Reports::TestCase.new( - name: 'divideTest', - classname: 'CalculatorTest', + name: "divideTest", + classname: "CalculatorTest", execution_time: 8.88, - status: Gitlab::Ci::Reports::TestCase::STATUS_ERROR) + status: Gitlab::Ci::Reports::TestCase::STATUS_ERROR + ) end def sample_java_failed_message diff --git a/spec/support/trace/trace_helpers.rb b/spec/support/trace/trace_helpers.rb index c7802bbcb94..2b0bea8a092 100644 --- a/spec/support/trace/trace_helpers.rb +++ b/spec/support/trace/trace_helpers.rb @@ -1,6 +1,6 @@ module TraceHelpers def create_legacy_trace(build, content) - File.open(legacy_trace_path(build), 'wb') { |stream| stream.write(content) } + File.open(legacy_trace_path(build), "wb") { |stream| stream.write(content) } end def create_legacy_trace_in_db(build, content) @@ -19,9 +19,9 @@ module TraceHelpers def archived_trace_path(job_artifact) disk_hash = Digest::SHA2.hexdigest(job_artifact.project_id.to_s) - creation_date = job_artifact.created_at.utc.strftime('%Y_%m_%d') + creation_date = job_artifact.created_at.utc.strftime("%Y_%m_%d") File.join(Gitlab.config.artifacts.path, disk_hash[0..1], disk_hash[2..3], disk_hash, - creation_date, job_artifact.job_id.to_s, job_artifact.id.to_s, 'job.log') + creation_date, job_artifact.job_id.to_s, job_artifact.id.to_s, "job.log") end end diff --git a/spec/support/unpack-gitlab-git-test b/spec/support/unpack-gitlab-git-test index d5b4912457d..38243f9ae21 100755 --- a/spec/support/unpack-gitlab-git-test +++ b/spec/support/unpack-gitlab-git-test @@ -1,36 +1,36 @@ #!/usr/bin/env ruby -require 'fileutils' +require "fileutils" -REPO = 'spec/support/gitlab-git-test.git'.freeze -PACK_DIR = REPO + '/objects/pack' +REPO = "spec/support/gitlab-git-test.git".freeze +PACK_DIR = REPO + "/objects/pack" GIT = %W[git --git-dir=#{REPO}].freeze -BASE_PACK = 'pack-691247af2a6acb0b63b73ac0cb90540e93614043'.freeze +BASE_PACK = "pack-691247af2a6acb0b63b73ac0cb90540e93614043".freeze def main unpack # We want to store the refs in a packed-refs file because if we don't # they can get mangled by filesystems. - abort unless system(*GIT, *%w[pack-refs --all]) - abort unless system(*GIT, 'fsck') + abort unless system(*GIT, "pack-refs", "--all") + abort unless system(*GIT, "fsck") end # We don't want contributors to commit new pack files because those # create unnecessary churn. def unpack - pack_files = Dir[File.join(PACK_DIR, '*')].reject do |pack| + pack_files = Dir[File.join(PACK_DIR, "*")].reject { |pack| pack.start_with?(File.join(PACK_DIR, BASE_PACK)) - end + } return if pack_files.empty? pack_files.each do |pack| - unless pack.end_with?('.pack') + unless pack.end_with?(".pack") FileUtils.rm(pack) next end - File.open(pack, 'rb') do |open_pack| + File.open(pack, "rb") do |open_pack| File.unlink(pack) - abort unless system(*GIT, 'unpack-objects', in: open_pack) + abort unless system(*GIT, "unpack-objects", in: open_pack) end end end diff --git a/spec/support/webmock.rb b/spec/support/webmock.rb index af2906b7568..2c144b646d1 100644 --- a/spec/support/webmock.rb +++ b/spec/support/webmock.rb @@ -1,4 +1,4 @@ -require 'webmock' -require 'webmock/rspec' +require "webmock" +require "webmock/rspec" WebMock.disable_net_connect!(allow_localhost: true) |