From cfd475a45ee2655fa0148b0b561f95b44fe8641b Mon Sep 17 00:00:00 2001
From: Tiago Botelho <tiagonbotelho@hotmail.com>
Date: Tue, 15 Aug 2017 11:27:37 +0100
Subject: [PATCH] Removes default scope from sortable

---
 .../admin/broadcast_messages_controller.rb         |  2 +-
 app/controllers/admin/dashboard_controller.rb      |  6 +++---
 app/controllers/admin/users_controller.rb          |  2 +-
 app/controllers/dashboard/groups_controller.rb     |  4 +++-
 app/controllers/profiles/emails_controller.rb      |  2 +-
 app/controllers/profiles/keys_controller.rb        |  2 +-
 .../projects/merge_requests/diffs_controller.rb    |  2 +-
 .../projects/project_members_controller.rb         |  4 ++++
 app/finders/move_to_project_finder.rb              |  1 +
 app/finders/projects_finder.rb                     |  2 +-
 app/finders/todos_finder.rb                        |  2 +-
 app/helpers/issues_helper.rb                       |  2 +-
 app/helpers/search_helper.rb                       |  4 ++--
 app/models/broadcast_message.rb                    |  2 +-
 app/models/concerns/sortable.rb                    |  4 ----
 app/models/user.rb                                 | 10 ++++++----
 app/services/quick_actions/interpret_service.rb    |  2 +-
 .../projects/project_members/import.html.haml      |  2 +-
 .../23079-remove-default-scope-in-sortable.yml     |  5 +++++
 features/steps/project/fork.rb                     |  2 +-
 lib/api/broadcast_messages.rb                      |  2 +-
 lib/api/merge_request_diffs.rb                     |  2 +-
 lib/api/milestone_responses.rb                     |  2 +-
 lib/api/v3/merge_request_diffs.rb                  |  2 +-
 lib/api/v3/milestones.rb                           |  1 +
 lib/api/v3/projects.rb                             |  2 +-
 .../projects/import_export/import_file_spec.rb     |  7 +++----
 spec/finders/group_members_finder_spec.rb          |  4 ++--
 spec/finders/members_finder_spec.rb                |  2 +-
 spec/models/namespace_spec.rb                      |  2 +-
 spec/models/user_spec.rb                           |  2 +-
 spec/requests/api/merge_request_diffs_spec.rb      |  2 +-
 spec/requests/api/projects_spec.rb                 |  4 ++--
 spec/requests/api/v3/merge_request_diffs_spec.rb   |  2 +-
 .../projects/cycle_analytics_events_spec.rb        |  2 +-
 spec/services/notification_service_spec.rb         |  4 ++--
 .../githubish_import_controller_shared_examples.rb | 14 ++++++++------
 spec/workers/post_receive_spec.rb                  |  2 ++
 38 files changed, 67 insertions(+), 53 deletions(-)
 create mode 100644 changelogs/unreleased/23079-remove-default-scope-in-sortable.yml

diff --git a/app/controllers/admin/broadcast_messages_controller.rb b/app/controllers/admin/broadcast_messages_controller.rb
index 762e36ee2e9..c49b6459452 100644
--- a/app/controllers/admin/broadcast_messages_controller.rb
+++ b/app/controllers/admin/broadcast_messages_controller.rb
@@ -2,7 +2,7 @@ class Admin::BroadcastMessagesController < Admin::ApplicationController
   before_action :finder, only: [:edit, :update, :destroy]
 
   def index
-    @broadcast_messages = BroadcastMessage.reorder("ends_at DESC").page(params[:page])
+    @broadcast_messages = BroadcastMessage.order(ends_at: :desc).page(params[:page])
     @broadcast_message  = BroadcastMessage.new
   end
 
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb
index 05e749c00c0..e85cdcb8db7 100644
--- a/app/controllers/admin/dashboard_controller.rb
+++ b/app/controllers/admin/dashboard_controller.rb
@@ -1,7 +1,7 @@
 class Admin::DashboardController < Admin::ApplicationController
   def index
-    @projects = Project.without_deleted.with_route.limit(10)
-    @users = User.limit(10)
-    @groups = Group.with_route.limit(10)
+    @projects = Project.order_id_desc.without_deleted.with_route.limit(10)
+    @users = User.order_id_desc.limit(10)
+    @groups = Group.order_id_desc.with_route.limit(10)
   end
 end
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb
index a99563b7100..9ec7719fabb 100644
--- a/app/controllers/admin/users_controller.rb
+++ b/app/controllers/admin/users_controller.rb
@@ -17,7 +17,7 @@ class Admin::UsersController < Admin::ApplicationController
   end
 
   def keys
-    @keys = user.keys
+    @keys = user.keys.order_id_desc
   end
 
   def new
diff --git a/app/controllers/dashboard/groups_controller.rb b/app/controllers/dashboard/groups_controller.rb
index 742157d113d..8057a0b455c 100644
--- a/app/controllers/dashboard/groups_controller.rb
+++ b/app/controllers/dashboard/groups_controller.rb
@@ -1,5 +1,7 @@
 class Dashboard::GroupsController < Dashboard::ApplicationController
   def index
+    @sort = params[:sort] || 'id_desc'
+
     @groups =
       if params[:parent_id] && Group.supports_nested_groups?
         parent = Group.find_by(id: params[:parent_id])
@@ -15,7 +17,7 @@ class Dashboard::GroupsController < Dashboard::ApplicationController
 
     @groups = @groups.search(params[:filter_groups]) if params[:filter_groups].present?
     @groups = @groups.includes(:route)
-    @groups = @groups.sort(@sort = params[:sort])
+    @groups = @groups.sort(@sort)
     @groups = @groups.page(params[:page])
 
     respond_to do |format|
diff --git a/app/controllers/profiles/emails_controller.rb b/app/controllers/profiles/emails_controller.rb
index 17b66df43e7..ddb67d1c4d1 100644
--- a/app/controllers/profiles/emails_controller.rb
+++ b/app/controllers/profiles/emails_controller.rb
@@ -1,7 +1,7 @@
 class Profiles::EmailsController < Profiles::ApplicationController
   def index
     @primary = current_user.email
-    @emails = current_user.emails
+    @emails = current_user.emails.order_id_desc
   end
 
   def create
diff --git a/app/controllers/profiles/keys_controller.rb b/app/controllers/profiles/keys_controller.rb
index 88f49da555a..f9f0e8eef83 100644
--- a/app/controllers/profiles/keys_controller.rb
+++ b/app/controllers/profiles/keys_controller.rb
@@ -2,7 +2,7 @@ class Profiles::KeysController < Profiles::ApplicationController
   skip_before_action :authenticate_user!, only: [:get_keys]
 
   def index
-    @keys = current_user.keys
+    @keys = current_user.keys.order_id_desc
     @key = Key.new
   end
 
diff --git a/app/controllers/projects/merge_requests/diffs_controller.rb b/app/controllers/projects/merge_requests/diffs_controller.rb
index 330b7df4541..63d61c98f34 100644
--- a/app/controllers/projects/merge_requests/diffs_controller.rb
+++ b/app/controllers/projects/merge_requests/diffs_controller.rb
@@ -27,7 +27,7 @@ class Projects::MergeRequests::DiffsController < Projects::MergeRequests::Applic
         @merge_request.merge_request_diff
       end
 
-    @merge_request_diffs = @merge_request.merge_request_diffs.viewable.select_without_diff
+    @merge_request_diffs = @merge_request.merge_request_diffs.viewable.select_without_diff.order_id_desc
     @comparable_diffs = @merge_request_diffs.select { |diff| diff.id < @merge_request_diff.id }
 
     if params[:start_sha].present?
diff --git a/app/controllers/projects/project_members_controller.rb b/app/controllers/projects/project_members_controller.rb
index f8ff7413b53..d925dcd21ff 100644
--- a/app/controllers/projects/project_members_controller.rb
+++ b/app/controllers/projects/project_members_controller.rb
@@ -47,6 +47,10 @@ class Projects::ProjectMembersController < Projects::ApplicationController
     end
   end
 
+  def import
+    @projects = current_user.authorized_projects.order_id_desc
+  end
+
   def apply_import
     source_project = Project.find(params[:source_project_id])
 
diff --git a/app/finders/move_to_project_finder.rb b/app/finders/move_to_project_finder.rb
index 79eb45568be..038d5565a1e 100644
--- a/app/finders/move_to_project_finder.rb
+++ b/app/finders/move_to_project_finder.rb
@@ -9,6 +9,7 @@ class MoveToProjectFinder
     projects = @user.projects_where_can_admin_issues
     projects = projects.search(search) if search.present?
     projects = projects.excluding_project(from_project)
+    projects = projects.order_id_desc
 
     # infinite scroll using offset
     projects = projects.where('projects.id < ?', offset_id) if offset_id.present?
diff --git a/app/finders/projects_finder.rb b/app/finders/projects_finder.rb
index fa6fea2588a..eac6095d8dc 100644
--- a/app/finders/projects_finder.rb
+++ b/app/finders/projects_finder.rb
@@ -121,7 +121,7 @@ class ProjectsFinder < UnionFinder
   end
 
   def sort(items)
-    params[:sort].present? ? items.sort(params[:sort]) : items
+    params[:sort].present? ? items.sort(params[:sort]) : items.order_id_desc
   end
 
   def by_archived(projects)
diff --git a/app/finders/todos_finder.rb b/app/finders/todos_finder.rb
index b276116f0c6..3502bf08971 100644
--- a/app/finders/todos_finder.rb
+++ b/app/finders/todos_finder.rb
@@ -118,7 +118,7 @@ class TodosFinder
   end
 
   def sort(items)
-    params[:sort] ? items.sort(params[:sort]) : items.reorder(id: :desc)
+    params[:sort] ? items.sort(params[:sort]) : items.order_id_desc
   end
 
   def by_action(items)
diff --git a/app/helpers/issues_helper.rb b/app/helpers/issues_helper.rb
index 3d0fdce6a43..212cdbb8157 100644
--- a/app/helpers/issues_helper.rb
+++ b/app/helpers/issues_helper.rb
@@ -56,7 +56,7 @@ module IssuesHelper
   end
 
   def project_options(issuable, current_user, ability: :read_project)
-    projects = current_user.authorized_projects
+    projects = current_user.authorized_projects.order_id_desc
     projects = projects.select do |project|
       current_user.can?(ability, project)
     end
diff --git a/app/helpers/search_helper.rb b/app/helpers/search_helper.rb
index ae0e0aa3cf9..e1309dc0761 100644
--- a/app/helpers/search_helper.rb
+++ b/app/helpers/search_helper.rb
@@ -85,7 +85,7 @@ module SearchHelper
 
   # Autocomplete results for the current user's groups
   def groups_autocomplete(term, limit = 5)
-    current_user.authorized_groups.search(term).limit(limit).map do |group|
+    current_user.authorized_groups.order_id_desc.search(term).limit(limit).map do |group|
       {
         category: "Groups",
         id: group.id,
@@ -97,7 +97,7 @@ module SearchHelper
 
   # Autocomplete results for the current user's projects
   def projects_autocomplete(term, limit = 5)
-    current_user.authorized_projects.search_by_title(term)
+    current_user.authorized_projects.order_id_desc.search_by_title(term)
       .sorted_by_stars.non_archived.limit(limit).map do |p|
       {
         category: "Projects",
diff --git a/app/models/broadcast_message.rb b/app/models/broadcast_message.rb
index fdc5a2adea0..0b561203914 100644
--- a/app/models/broadcast_message.rb
+++ b/app/models/broadcast_message.rb
@@ -33,7 +33,7 @@ class BroadcastMessage < ActiveRecord::Base
   end
 
   def self.current_and_future_messages
-    where('ends_at > :now', now: Time.zone.now).reorder(id: :asc)
+    where('ends_at > :now', now: Time.zone.now).order_id_asc
   end
 
   def active?
diff --git a/app/models/concerns/sortable.rb b/app/models/concerns/sortable.rb
index a155a064032..db3cd257584 100644
--- a/app/models/concerns/sortable.rb
+++ b/app/models/concerns/sortable.rb
@@ -6,10 +6,6 @@ module Sortable
   extend ActiveSupport::Concern
 
   included do
-    # By default all models should be ordered
-    # by created_at field starting from newest
-    default_scope { order_id_desc }
-
     scope :order_id_desc, -> { reorder(id: :desc) }
     scope :order_id_asc, -> { reorder(id: :asc) }
     scope :order_created_desc, -> { reorder(created_at: :desc) }
diff --git a/app/models/user.rb b/app/models/user.rb
index c5b5f09722f..1ac5b029c81 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -70,7 +70,7 @@ class User < ActiveRecord::Base
   #
 
   # Namespace for personal projects
-  has_one :namespace, -> { where type: nil }, dependent: :destroy, foreign_key: :owner_id, autosave: true # rubocop:disable Cop/ActiveRecordDependent
+  has_one :namespace, -> { where(type: nil) }, dependent: :destroy, foreign_key: :owner_id, autosave: true # rubocop:disable Cop/ActiveRecordDependent
 
   # Profile
   has_many :keys, -> do
@@ -255,11 +255,13 @@ class User < ActiveRecord::Base
     end
 
     def sort(method)
-      case method.to_s
+      order_method = method || 'id_desc'
+
+      case order_method.to_s
       when 'recent_sign_in' then order_recent_sign_in
       when 'oldest_sign_in' then order_oldest_sign_in
       else
-        order_by(method)
+        order_by(order_method)
       end
     end
 
@@ -367,7 +369,7 @@ class User < ActiveRecord::Base
 
     # Returns a user for the given SSH key.
     def find_by_ssh_key_id(key_id)
-      find_by(id: Key.unscoped.select(:user_id).where(id: key_id))
+      Key.find_by(id: key_id)&.user
     end
 
     def find_by_full_path(path, follow_redirects: false)
diff --git a/app/services/quick_actions/interpret_service.rb b/app/services/quick_actions/interpret_service.rb
index 9cdb9935bea..a077b3584b0 100644
--- a/app/services/quick_actions/interpret_service.rb
+++ b/app/services/quick_actions/interpret_service.rb
@@ -115,7 +115,7 @@ module QuickActions
         if issuable.allows_multiple_assignees?
           issuable.assignees.pluck(:id) + users.map(&:id)
         else
-          [users.last.id]
+          [users.first.id]
         end
     end
 
diff --git a/app/views/projects/project_members/import.html.haml b/app/views/projects/project_members/import.html.haml
index f6ca8d5a921..755128af565 100644
--- a/app/views/projects/project_members/import.html.haml
+++ b/app/views/projects/project_members/import.html.haml
@@ -8,7 +8,7 @@
 = form_tag apply_import_project_project_members_path(@project), method: 'post', class: 'form-horizontal' do
   .form-group
     = label_tag :source_project_id, "Project", class: 'control-label'
-    .col-sm-10= select_tag(:source_project_id, options_from_collection_for_select(current_user.authorized_projects, :id, :name_with_namespace), prompt: "Select project", class: "select2 lg", required: true)
+    .col-sm-10= select_tag(:source_project_id, options_from_collection_for_select(@projects, :id, :name_with_namespace), prompt: "Select project", class: "select2 lg", required: true)
 
   .form-actions
     = button_tag 'Import project members', class: "btn btn-create"
diff --git a/changelogs/unreleased/23079-remove-default-scope-in-sortable.yml b/changelogs/unreleased/23079-remove-default-scope-in-sortable.yml
new file mode 100644
index 00000000000..abb9e33d626
--- /dev/null
+++ b/changelogs/unreleased/23079-remove-default-scope-in-sortable.yml
@@ -0,0 +1,5 @@
+---
+title: Removes Sortable default scope.
+merge_request: 13558
+author:
+type: fixed
diff --git a/features/steps/project/fork.rb b/features/steps/project/fork.rb
index 3b8d9af96c1..7b6f464c779 100644
--- a/features/steps/project/fork.rb
+++ b/features/steps/project/fork.rb
@@ -52,7 +52,7 @@ class Spinach::Features::ProjectFork < Spinach::FeatureSteps
   end
 
   step 'I visit the forks page of the "Shop" project' do
-    @project = Project.where(name: 'Shop').last
+    @project = Project.where(name: 'Shop').first
     visit project_forks_path(@project)
   end
 
diff --git a/lib/api/broadcast_messages.rb b/lib/api/broadcast_messages.rb
index 0b45621ce7b..d7138b2f2fe 100644
--- a/lib/api/broadcast_messages.rb
+++ b/lib/api/broadcast_messages.rb
@@ -20,7 +20,7 @@ module API
         use :pagination
       end
       get do
-        messages = BroadcastMessage.all
+        messages = BroadcastMessage.all.order_id_desc
 
         present paginate(messages), with: Entities::BroadcastMessage
       end
diff --git a/lib/api/merge_request_diffs.rb b/lib/api/merge_request_diffs.rb
index c3affcc6c6b..95ef8f42954 100644
--- a/lib/api/merge_request_diffs.rb
+++ b/lib/api/merge_request_diffs.rb
@@ -21,7 +21,7 @@ module API
       get ":id/merge_requests/:merge_request_iid/versions" do
         merge_request = find_merge_request_with_access(params[:merge_request_iid])
 
-        present paginate(merge_request.merge_request_diffs), with: Entities::MergeRequestDiff
+        present paginate(merge_request.merge_request_diffs.order_id_desc), with: Entities::MergeRequestDiff
       end
 
       desc 'Get a single merge request diff version' do
diff --git a/lib/api/milestone_responses.rb b/lib/api/milestone_responses.rb
index ef09d9505d2..c570eace862 100644
--- a/lib/api/milestone_responses.rb
+++ b/lib/api/milestone_responses.rb
@@ -28,7 +28,7 @@ module API
         end
 
         def list_milestones_for(parent)
-          milestones = parent.milestones
+          milestones = parent.milestones.order_id_desc
           milestones = Milestone.filter_by_state(milestones, params[:state])
           milestones = filter_by_iid(milestones, params[:iids]) if params[:iids].present?
           milestones = filter_by_search(milestones, params[:search]) if params[:search]
diff --git a/lib/api/v3/merge_request_diffs.rb b/lib/api/v3/merge_request_diffs.rb
index 35f462e907b..22866fc2845 100644
--- a/lib/api/v3/merge_request_diffs.rb
+++ b/lib/api/v3/merge_request_diffs.rb
@@ -20,7 +20,7 @@ module API
         get ":id/merge_requests/:merge_request_id/versions" do
           merge_request = find_merge_request_with_access(params[:merge_request_id])
 
-          present merge_request.merge_request_diffs, with: ::API::Entities::MergeRequestDiff
+          present merge_request.merge_request_diffs.order_id_desc, with: ::API::Entities::MergeRequestDiff
         end
 
         desc 'Get a single merge request diff version' do
diff --git a/lib/api/v3/milestones.rb b/lib/api/v3/milestones.rb
index 4c7061d4939..9be4cf9d22a 100644
--- a/lib/api/v3/milestones.rb
+++ b/lib/api/v3/milestones.rb
@@ -34,6 +34,7 @@ module API
           milestones = user_project.milestones
           milestones = filter_milestones_state(milestones, params[:state])
           milestones = filter_by_iid(milestones, params[:iid]) if params[:iid].present?
+          milestones = milestones.order_id_desc
 
           present paginate(milestones), with: ::API::Entities::Milestone
         end
diff --git a/lib/api/v3/projects.rb b/lib/api/v3/projects.rb
index 449876c10d9..6b338ce2d6a 100644
--- a/lib/api/v3/projects.rb
+++ b/lib/api/v3/projects.rb
@@ -119,7 +119,7 @@ module API
         get do
           authenticate!
 
-          present_projects current_user.authorized_projects,
+          present_projects current_user.authorized_projects.order_id_desc,
             with: ::API::V3::Entities::ProjectWithAccess
         end
 
diff --git a/spec/features/projects/import_export/import_file_spec.rb b/spec/features/projects/import_export/import_file_spec.rb
index ad2db1a34f4..e5c7781a096 100644
--- a/spec/features/projects/import_export/import_file_spec.rb
+++ b/spec/features/projects/import_export/import_file_spec.rb
@@ -18,7 +18,7 @@ feature 'Import/Export - project import integration test', js: true do
 
   context 'when selecting the namespace' do
     let(:user) { create(:admin) }
-    let!(:namespace) { create(:namespace, name: 'asd', owner: user) }
+    let!(:namespace) { user.namespace }
     let(:project_path) { 'test-project-path' + SecureRandom.hex }
 
     context 'prefilled the path' do
@@ -66,12 +66,11 @@ feature 'Import/Export - project import integration test', js: true do
   end
 
   scenario 'invalid project' do
-    namespace = create(:namespace, name: 'asdf', owner: user)
-    project = create(:project, namespace: namespace)
+    project = create(:project, namespace: user.namespace)
 
     visit new_project_path
 
-    select2(namespace.id, from: '#project_namespace_id')
+    select2(user.namespace.id, from: '#project_namespace_id')
     fill_in :project_path, with: project.name, visible: true
     click_link 'GitLab export'
     attach_file('file', file)
diff --git a/spec/finders/group_members_finder_spec.rb b/spec/finders/group_members_finder_spec.rb
index db3fcc23475..9f285e28535 100644
--- a/spec/finders/group_members_finder_spec.rb
+++ b/spec/finders/group_members_finder_spec.rb
@@ -15,7 +15,7 @@ describe GroupMembersFinder, '#execute' do
 
     result = described_class.new(group).execute
 
-    expect(result.to_a).to eq([member3, member2, member1])
+    expect(result.to_a).to match_array([member3, member2, member1])
   end
 
   it 'returns members for nested group', :nested_groups do
@@ -27,6 +27,6 @@ describe GroupMembersFinder, '#execute' do
 
     result = described_class.new(nested_group).execute
 
-    expect(result.to_a).to eq([member4, member3, member1])
+    expect(result.to_a).to match_array([member1, member3, member4])
   end
 end
diff --git a/spec/finders/members_finder_spec.rb b/spec/finders/members_finder_spec.rb
index 300ba8422e8..7bb1f45322e 100644
--- a/spec/finders/members_finder_spec.rb
+++ b/spec/finders/members_finder_spec.rb
@@ -17,6 +17,6 @@ describe MembersFinder, '#execute' do
 
     result = described_class.new(project, user2).execute
 
-    expect(result.to_a).to eq([member3, member2, member1])
+    expect(result.to_a).to match_array([member1, member2, member3])
   end
 end
diff --git a/spec/models/namespace_spec.rb b/spec/models/namespace_spec.rb
index 69286eff984..f5f83f0f114 100644
--- a/spec/models/namespace_spec.rb
+++ b/spec/models/namespace_spec.rb
@@ -404,6 +404,6 @@ describe Namespace do
     let!(:project1) { create(:project_empty_repo, namespace: group) }
     let!(:project2) { create(:project_empty_repo, namespace: child) }
 
-    it { expect(group.all_projects.to_a).to eq([project2, project1]) }
+    it { expect(group.all_projects.to_a).to match_array([project2, project1]) }
   end
 end
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index fd83a58ed9f..765ffb69623 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -1517,7 +1517,7 @@ describe User do
       developer_project = create(:project) { |p| p.add_developer(user) }
       master_project    = create(:project) { |p| p.add_master(user) }
 
-      expect(user.projects_where_can_admin_issues.to_a).to eq([master_project, developer_project, reporter_project])
+      expect(user.projects_where_can_admin_issues.to_a).to match_array([master_project, developer_project, reporter_project])
       expect(user.can?(:admin_issue, master_project)).to eq(true)
       expect(user.can?(:admin_issue, developer_project)).to eq(true)
       expect(user.can?(:admin_issue, reporter_project)).to eq(true)
diff --git a/spec/requests/api/merge_request_diffs_spec.rb b/spec/requests/api/merge_request_diffs_spec.rb
index d1b22179888..d9da94d4713 100644
--- a/spec/requests/api/merge_request_diffs_spec.rb
+++ b/spec/requests/api/merge_request_diffs_spec.rb
@@ -14,7 +14,7 @@ describe API::MergeRequestDiffs, 'MergeRequestDiffs' do
   describe 'GET /projects/:id/merge_requests/:merge_request_iid/versions' do
     it 'returns 200 for a valid merge request' do
       get api("/projects/#{project.id}/merge_requests/#{merge_request.iid}/versions", user)
-      merge_request_diff = merge_request.merge_request_diffs.first
+      merge_request_diff = merge_request.merge_request_diffs.last
 
       expect(response.status).to eq 200
       expect(response).to include_pagination_headers
diff --git a/spec/requests/api/projects_spec.rb b/spec/requests/api/projects_spec.rb
index 4490e50702b..bf2a123e7cd 100644
--- a/spec/requests/api/projects_spec.rb
+++ b/spec/requests/api/projects_spec.rb
@@ -574,7 +574,7 @@ describe API::Projects do
       expect { post api("/projects/user/#{user.id}", admin), name: 'Foo Project' }.to change {Project.count}.by(1)
       expect(response).to have_http_status(201)
 
-      project = Project.first
+      project = Project.last
 
       expect(project.name).to eq('Foo Project')
       expect(project.path).to eq('foo-project')
@@ -585,7 +585,7 @@ describe API::Projects do
         .to change { Project.count }.by(1)
       expect(response).to have_http_status(201)
 
-      project = Project.first
+      project = Project.last
 
       expect(project.name).to eq('Foo Project')
       expect(project.path).to eq('path-project-Foo')
diff --git a/spec/requests/api/v3/merge_request_diffs_spec.rb b/spec/requests/api/v3/merge_request_diffs_spec.rb
index 8020ddab4c8..3f21ff40726 100644
--- a/spec/requests/api/v3/merge_request_diffs_spec.rb
+++ b/spec/requests/api/v3/merge_request_diffs_spec.rb
@@ -14,7 +14,7 @@ describe API::V3::MergeRequestDiffs, 'MergeRequestDiffs' do
   describe 'GET /projects/:id/merge_requests/:merge_request_id/versions' do
     it 'returns 200 for a valid merge request' do
       get v3_api("/projects/#{project.id}/merge_requests/#{merge_request.id}/versions", user)
-      merge_request_diff = merge_request.merge_request_diffs.first
+      merge_request_diff = merge_request.merge_request_diffs.last
 
       expect(response.status).to eq 200
       expect(json_response.size).to eq(merge_request.merge_request_diffs.size)
diff --git a/spec/requests/projects/cycle_analytics_events_spec.rb b/spec/requests/projects/cycle_analytics_events_spec.rb
index e5d9d3df5a8..6667ce771bd 100644
--- a/spec/requests/projects/cycle_analytics_events_spec.rb
+++ b/spec/requests/projects/cycle_analytics_events_spec.rb
@@ -93,7 +93,7 @@ describe 'cycle analytics events' do
 
     context 'with private project and builds' do
       before do
-        project.members.first.update(access_level: Gitlab::Access::GUEST)
+        project.members.last.update(access_level: Gitlab::Access::GUEST)
       end
 
       it 'does not list the test events' do
diff --git a/spec/services/notification_service_spec.rb b/spec/services/notification_service_spec.rb
index 5b349017c8b..3e493148b32 100644
--- a/spec/services/notification_service_spec.rb
+++ b/spec/services/notification_service_spec.rb
@@ -1237,7 +1237,7 @@ describe NotificationService, :mailer do
       end
 
       it do
-        group_member = group.members.first
+        group_member = group.members.last
 
         expect do
           notification.decline_group_invite(group_member)
@@ -1285,7 +1285,7 @@ describe NotificationService, :mailer do
       end
 
       it do
-        project_member = project.members.first
+        project_member = project.members.last
 
         expect do
           notification.decline_project_invite(project_member)
diff --git a/spec/support/controllers/githubish_import_controller_shared_examples.rb b/spec/support/controllers/githubish_import_controller_shared_examples.rb
index 4eec3127464..b23d81a226a 100644
--- a/spec/support/controllers/githubish_import_controller_shared_examples.rb
+++ b/spec/support/controllers/githubish_import_controller_shared_examples.rb
@@ -140,9 +140,14 @@ shared_examples 'a GitHub-ish import controller: POST create' do
     end
 
     context "when a namespace with the provider user's username already exists" do
-      let!(:existing_namespace) { create(:namespace, name: other_username, owner: user) }
+      let!(:existing_namespace) { user.namespace }
 
       context "when the namespace is owned by the GitLab user" do
+        before do
+          user.username = other_username
+          user.save
+        end
+
         it "takes the existing namespace" do
           expect(Gitlab::GithubImport::ProjectCreator)
             .to receive(:new).with(provider_repo, provider_repo.name, existing_namespace, user, access_params, type: provider)
@@ -153,12 +158,9 @@ shared_examples 'a GitHub-ish import controller: POST create' do
       end
 
       context "when the namespace is not owned by the GitLab user" do
-        before do
-          existing_namespace.owner = create(:user)
-          existing_namespace.save
-        end
-
         it "creates a project using user's namespace" do
+          create(:user, username: other_username)
+
           expect(Gitlab::GithubImport::ProjectCreator)
             .to receive(:new).with(provider_repo, provider_repo.name, user.namespace, user, access_params, type: provider)
               .and_return(double(execute: true))
diff --git a/spec/workers/post_receive_spec.rb b/spec/workers/post_receive_spec.rb
index af6a3c9f6c7..d3707a3cc11 100644
--- a/spec/workers/post_receive_spec.rb
+++ b/spec/workers/post_receive_spec.rb
@@ -127,6 +127,7 @@ describe PostReceive do
 
     it "asks the project to trigger all hooks" do
       allow(Project).to receive(:find_by).and_return(project)
+
       expect(project).to receive(:execute_hooks).twice
       expect(project).to receive(:execute_services).twice
 
@@ -135,6 +136,7 @@ describe PostReceive do
 
     it "enqueues a UpdateMergeRequestsWorker job" do
       allow(Project).to receive(:find_by).and_return(project)
+
       expect(UpdateMergeRequestsWorker).to receive(:perform_async).with(project.id, project.owner.id, any_args)
 
       described_class.new.perform(gl_repository, key_id, base64_changes)
-- 
GitLab