Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Submodules
  class UpdateService < Commits::CreateService
    include Gitlab::Utils::StrongMemoize

    def initialize(*args)
      super

      @start_branch = @branch_name
      @commit_sha = params[:commit_sha].presence
      @submodule = params[:submodule].presence
      @commit_message = params[:commit_message].presence || "Update submodule #{@submodule} with oid #{@commit_sha}"
    end

    def validate!
      super

      raise ValidationError, 'The repository is empty' if repository.empty?
    end

    def execute
      super
    rescue StandardError => e
      error(e.message)
    end

    def create_commit!
      repository.update_submodule(
        current_user,
        @submodule,
        @commit_sha,
        message: @commit_message,
        branch: @branch_name
      )
    rescue ArgumentError, TypeError
      raise ValidationError, 'Invalid parameters'
    end
  end
end

```

Response:
# frozen_string_literal: true
require 'spec_helper'

RSpec.describe Submodules::UpdateService, feature_category: :source_code_management do
  let(:project) { create(:project, :repository) }
  let(:repository) { project.repository }
  let(:user) { create(:user, :commit_email) }
  let(:branch_name) { project.default_branch }
  let(:submodule) { 'six' }
  let(:commit_sha) { 'e25eda1fece24ac7a03624ed1320f82396f35bd8' }
  let(:commit_message) { 'whatever' }
  let(:current_sha) { repository.blob_at('HEAD', submodule).id }
  let(:commit_params) do
    {
      submodule: submodule,
      commit_message: commit_message,
      commit_sha: commit_sha,
      branch_name: branch_name
    }
  end

  subject { described_class.new(project, user, commit_params) }

  describe "#execute" do
    shared_examples 'returns error result' do
      it do
        result = subject.execute

        expect(result[:status]).to eq :error
        expect(result[:message]).to eq error_message
      end
    end

    context 'when the user is not authorized' do
      it_behaves_like 'returns error result' do
        let(:error_message) { 'You are not allowed to push into this branch' }
      end
    end

    context 'when the user is authorized' do
      before do
        project.add_maintainer(user)
      end

      context 'when the branch is protected' do
        before do
          create(:protected_branch, :no_one_can_push, project: project, name: branch_name)
        end

        it_behaves_like 'returns error result' do
          let(:error_message) { 'You are not allowed to push into this branch' }
        end
      end

      context 'validations' do
        context 'when submodule' do
          context 'is empty' do
            let(:submodule) { '' }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid parameters' }
            end
          end

          context 'is not present' do
            let(:submodule) { nil }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid parameters' }
            end
          end

          context 'is invalid' do
            let(:submodule) { 'VERSION' }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid submodule path' }
            end
          end

          context 'does not exist' do
            let(:submodule) { 'non-existent-submodule' }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid submodule path' }
            end
          end

          # Can be re-enabled when problem from https://gitlab.com/gitlab-org/gitlab/-/issues/413964#note_1421909142
          # is fixed
          # context 'has traversal path' do
          #   let(:submodule) { '../six' }

          #   it_behaves_like 'returns error result' do
          #     let(:error_message) { 'Invalid submodule path' }
          #   end
          # end
        end

        context 'commit_sha' do
          context 'is empty' do
            let(:commit_sha) { '' }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid parameters' }
            end
          end

          context 'is not present' do
            let(:commit_sha) { nil }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid parameters' }
            end
          end

          context 'is invalid' do
            let(:commit_sha) { '1' }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid parameters' }
            end
          end

          context 'is the same as the current ref' do
            let(:commit_sha) { current_sha }

            it_behaves_like 'returns error result' do
              let(:error_message) { "The submodule #{submodule} is already at #{commit_sha}" }
            end
          end
        end

        context 'branch_name' do
          context 'is empty' do
            let(:branch_name) { '' }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'You can only create or edit files when you are on a branch' }
            end
          end

          context 'is not present' do
            let(:branch_name) { nil }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'Invalid parameters' }
            end
          end

          context 'does not exist' do
            let(:branch_name) { 'non/existent-branch' }

            it_behaves_like 'returns error result' do
              let(:error_message) { 'You can only create or edit files when you are on a branch' }
            end
          end

          context 'when commit message is empty' do
            let(:commit_message) { '' }

            it 'a default commit message is set' do
              message = "Update submodule #{submodule} with oid #{commit_sha}"

              expect(repository).to receive(:update_submodule).with(any_args, hash_including(message: message))

              subject.execute
            end
          end
        end
      end

      context 'when there is an unexpected error' do
        before do
          allow(repository).to receive(:update_submodule).and_raise(StandardError, 'error message')
        end

        it_behaves_like 'returns error result' do
          let(:error_message) { 'error message' }
        end
      end

      it 'updates the submodule reference' do
        result = subject.execute

        expect(result[:status]).to eq :success
        expect(result[:result]).to eq repository.head_commit.id
        expect(repository.blob_at('HEAD', submodule).id).to eq commit_sha
      end

      context 'when submodule is inside a directory' do
        let(:submodule) { 'test_inside_folder/another_folder/six' }
        let(:branch_name) { 'submodule_inside_folder' }

        it 'updates the submodule reference' do
          expect(repository.blob_at(branch_name, submodule).id).not_to eq commit_sha

          subject.execute

          expect(repository.blob_at(branch_name, submodule).id).to eq commit_sha
        end
      end

      context 'when repository is empty' do
        let(:project) { create(:project, :empty_repo) }
        let(:branch_name) { 'master' }

        it_behaves_like 'returns error result' do
          let(:error_message) { 'The repository is empty' }
        end
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

# This service copies AwardEmoji from one Awardable to another.
#
# It expects the calling code to have performed the necessary authorization
# checks in order to allow the copy to happen.
module AwardEmojis
  class CopyService
    def initialize(from_awardable, to_awardable)
      raise ArgumentError, 'Awardables must be different' if from_awardable == to_awardable

      @from_awardable = from_awardable
      @to_awardable = to_awardable
    end

    def execute
      from_awardable.award_emoji.find_each do |award|
        new_award = award.dup
        new_award.awardable = to_awardable
        new_award.save!
      end

      ServiceResponse.success
    end

    private

    attr_accessor :from_awardable, :to_awardable
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe AwardEmojis::CopyService, feature_category: :team_planning do
  let_it_be(:from_awardable) do
    create(
      :issue,
      award_emoji: [
        build(:award_emoji, name: 'thumbsup'),
        build(:award_emoji, name: 'thumbsdown')
      ])
  end

  describe '#initialize' do
    it 'validates that we cannot copy AwardEmoji to the same Awardable' do
      expect { described_class.new(from_awardable, from_awardable) }.to raise_error(ArgumentError)
    end
  end

  describe '#execute' do
    let(:to_awardable) { create(:issue) }

    subject(:execute_service) { described_class.new(from_awardable, to_awardable).execute }

    it 'copies AwardEmojis', :aggregate_failures do
      expect { execute_service }.to change { AwardEmoji.count }.by(2)
      expect(to_awardable.award_emoji.map(&:name)).to match_array(%w[thumbsup thumbsdown])
    end

    it 'returns success', :aggregate_failures do
      expect(execute_service).to be_kind_of(ServiceResponse)
      expect(execute_service).to be_success
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

# Class for retrieving information about emoji awarded _by_ a particular user.
module AwardEmojis
  class CollectUserEmojiService
    attr_reader :current_user

    # current_user - The User to generate the data for.
    def initialize(current_user = nil)
      @current_user = current_user
    end

    def execute
      return [] unless current_user

      # We want the resulting data set to be an Array containing the emoji names
      # in descending order, based on how often they were awarded.
      AwardEmoji
        .award_counts_for_user(current_user)
        .map { |name, _| { name: name } }
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe AwardEmojis::CollectUserEmojiService, feature_category: :team_planning do
  describe '#execute' do
    it 'returns an Array containing the awarded emoji names' do
      user = create(:user)

      create(:award_emoji, user: user, name: 'thumbsup')
      create(:award_emoji, user: user, name: 'thumbsup')
      create(:award_emoji, user: user, name: 'thumbsdown')

      awarded = described_class.new(user).execute

      expect(awarded).to eq([{ name: 'thumbsup' }, { name: 'thumbsdown' }])
    end

    it 'returns an empty Array when no user is given' do
      awarded = described_class.new.execute

      expect(awarded).to be_empty
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module AwardEmojis
  class AddService < AwardEmojis::BaseService
    include Gitlab::Utils::StrongMemoize

    def execute
      unless awardable.user_can_award?(current_user)
        return error('User cannot add emoji reactions to awardable', status: :forbidden)
      end

      unless awardable.emoji_awardable?
        return error('Awardable cannot add emoji reactions', status: :unprocessable_entity)
      end

      award = awardable.award_emoji.create(name: name, user: current_user)

      if award.persisted?
        after_create(award)
        success(award: award)
      else
        error(award.errors.full_messages, award: award)
      end
    end

    private

    def after_create(award)
      TodoService.new.new_award_emoji(todoable, current_user) if todoable

      execute_hooks(award, 'award')
    end

    def todoable
      strong_memoize(:todoable) do
        case awardable
        when Note
          # We don't create todos for personal snippet comments for now
          awardable.noteable unless awardable.for_personal_snippet?
        when MergeRequest, Issue
          awardable
        else
          # No todos for all other awardables
          nil
        end
      end
    end
  end
end

AwardEmojis::AddService.prepend_mod_with('AwardEmojis::AddService')

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe AwardEmojis::AddService, feature_category: :team_planning do
  let_it_be(:user) { create(:user) }
  let_it_be(:project) { create(:project) }
  let_it_be(:awardable) { create(:note, project: project) }

  let(:name) { 'thumbsup' }

  subject(:service) { described_class.new(awardable, name, user) }

  describe '#execute' do
    context 'when user is not authorized' do
      it 'does not add an emoji' do
        expect { service.execute }.not_to change { AwardEmoji.count }
      end

      it 'returns an error state' do
        result = service.execute

        expect(result[:status]).to eq(:error)
        expect(result[:http_status]).to eq(:forbidden)
      end
    end

    context 'when user is authorized' do
      before do
        project.add_developer(user)
      end

      it 'creates an award emoji' do
        expect { service.execute }.to change { AwardEmoji.count }.by(1)
      end

      it 'returns the award emoji' do
        result = service.execute

        expect(result[:award]).to be_kind_of(AwardEmoji)
      end

      it 'return a success status' do
        result = service.execute

        expect(result[:status]).to eq(:success)
      end

      it 'sets the correct properties on the award emoji' do
        award = service.execute[:award]

        expect(award.name).to eq(name)
        expect(award.user).to eq(user)
      end

      it 'executes hooks' do
        expect(service).to receive(:execute_hooks).with(kind_of(AwardEmoji), 'award')

        service.execute
      end

      describe 'marking Todos as done' do
        subject { service.execute }

        include_examples 'creating award emojis marks Todos as done'
      end

      context 'when the awardable cannot have emoji awarded to it' do
        before do
          expect(awardable).to receive(:emoji_awardable?).and_return(false)
        end

        it 'does not add an emoji' do
          expect { service.execute }.not_to change { AwardEmoji.count }
        end

        it 'returns an error status' do
          result = service.execute

          expect(result[:status]).to eq(:error)
          expect(result[:http_status]).to eq(:unprocessable_entity)
        end
      end

      context 'when the awardable is invalid' do
        before do
          expect_next_instance_of(AwardEmoji) do |award|
            expect(award).to receive(:valid?).and_return(false)
            expect(award).to receive_message_chain(:errors, :full_messages).and_return(['Error 1', 'Error 2'])
          end
        end

        it 'does not add an emoji' do
          expect { service.execute }.not_to change { AwardEmoji.count }
        end

        it 'returns an error status' do
          result = service.execute

          expect(result[:status]).to eq(:error)
        end

        it 'returns an error message' do
          result = service.execute

          expect(result[:message]).to eq('Error 1 and Error 2')
        end
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module AwardEmojis
  class BaseService < ::BaseService
    attr_accessor :awardable, :name

    def initialize(awardable, name, current_user)
      @awardable = awardable
      @name = normalize_name(name)

      super(awardable.project, current_user)
    end

    def execute_hooks(award_emoji, action)
      return unless awardable.project&.has_active_hooks?(:emoji_hooks)

      hook_data = Gitlab::DataBuilder::Emoji.build(award_emoji, current_user, action)
      awardable.project.execute_hooks(hook_data, :emoji_hooks)
    end

    private

    def normalize_name(name)
      TanukiEmoji.find_by_alpha_code(name)&.name || name
    end

    # Provide more error state data than what BaseService allows.
    # - An array of errors
    # - The `AwardEmoji` if present
    def error(errors, award: nil, status: nil)
      errors = Array.wrap(errors)

      super(errors.to_sentence.presence, status).merge({
        award: award,
        errors: errors
      })
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe AwardEmojis::BaseService, feature_category: :team_planning do
  let_it_be(:group) { create(:group) }
  let_it_be(:project) { create(:project, group: group) }
  let_it_be(:current_user) { create(:user) }
  let_it_be_with_reload(:awardable) { create(:note, project: project) }

  let(:emoji_name) { 'horse' }

  describe '.initialize' do
    subject { described_class }

    it 'uses same emoji name if not an alias' do
      expect(subject.new(awardable, emoji_name, current_user).name).to eq(emoji_name)
    end

    it 'uses emoji original name if its an alias' do
      emoji_alias = 'small_airplane'
      emoji_name = 'airplane_small'

      expect(subject.new(awardable, emoji_alias, current_user).name).to eq(emoji_name)
    end
  end

  describe '.execute_hooks' do
    let(:award_emoji) { create(:award_emoji, awardable: awardable) }
    let(:action) { 'award' }

    subject { described_class.new(awardable, emoji_name, current_user) }

    context 'with no emoji hooks configured' do
      it 'does not build hook_data' do
        expect(Gitlab::DataBuilder::Emoji).not_to receive(:build)
        expect(award_emoji.awardable.project).not_to receive(:execute_hooks)

        subject.execute_hooks(award_emoji, action)
      end
    end

    context 'with emoji hooks configured' do
      it 'builds hook_data and calls execute_hooks for project' do
        hook_data = {}
        create(:project_hook, project: project, emoji_events: true)
        expect(Gitlab::DataBuilder::Emoji).to receive(:build).and_return(hook_data)
        expect(award_emoji.awardable.project).to receive(:execute_hooks).with(hook_data, :emoji_hooks)

        subject.execute_hooks(award_emoji, action)
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module AwardEmojis
  class DestroyService < AwardEmojis::BaseService
    def execute
      unless awardable.user_can_award?(current_user)
        return error('User cannot destroy emoji on the awardable', status: :forbidden)
      end

      awards = AwardEmojisFinder.new(awardable, name: name, awarded_by: current_user).execute

      if awards.empty?
        return error("User has not awarded emoji of type #{name} on the awardable", status: :forbidden)
      end

      award = awards.destroy_all.first # rubocop: disable Cop/DestroyAll
      after_destroy(award)

      success(award: award)
    end

    private

    def after_destroy(award)
      execute_hooks(award, 'revoke')
    end
  end
end

AwardEmojis::DestroyService.prepend_mod_with('AwardEmojis::DestroyService')

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe AwardEmojis::DestroyService, feature_category: :team_planning do
  let_it_be(:user) { create(:user) }
  let_it_be(:awardable) { create(:note) }
  let_it_be(:project) { awardable.project }

  let(:name) { 'thumbsup' }
  let!(:award_from_other_user) do
    create(:award_emoji, name: name, awardable: awardable, user: create(:user))
  end

  subject(:service) { described_class.new(awardable, name, user) }

  describe '#execute' do
    shared_examples_for 'a service that does not authorize the user' do |error:|
      it 'does not remove the emoji' do
        expect { service.execute }.not_to change { AwardEmoji.count }
      end

      it 'returns an error state' do
        result = service.execute

        expect(result[:status]).to eq(:error)
        expect(result[:http_status]).to eq(:forbidden)
      end

      it 'returns a nil award' do
        result = service.execute

        expect(result).to have_key(:award)
        expect(result[:award]).to be_nil
      end

      it 'returns the error' do
        result = service.execute

        expect(result[:message]).to eq(error)
        expect(result[:errors]).to eq([error])
      end
    end

    context 'when user is not authorized' do
      it_behaves_like 'a service that does not authorize the user',
        error: 'User cannot destroy emoji on the awardable'
    end

    context 'when the user is authorized' do
      before do
        project.add_developer(user)
      end

      context 'when user has not awarded an emoji to the awardable' do
        let!(:award_from_user) { create(:award_emoji, name: name, user: user) }

        it_behaves_like 'a service that does not authorize the user',
          error: 'User has not awarded emoji of type thumbsup on the awardable'
      end

      context 'when user has awarded an emoji to the awardable' do
        let!(:award_from_user) { create(:award_emoji, name: name, awardable: awardable, user: user) }

        it 'removes the emoji' do
          expect { service.execute }.to change { AwardEmoji.count }.by(-1)
        end

        it 'returns a success status' do
          result = service.execute

          expect(result[:status]).to eq(:success)
        end

        it 'returns no errors' do
          result = service.execute

          expect(result).not_to have_key(:error)
          expect(result).not_to have_key(:errors)
        end

        it 'returns the destroyed award' do
          result = service.execute

          expect(result[:award]).to eq(award_from_user)
          expect(result[:award]).to be_destroyed
        end

        it 'executes hooks' do
          expect(service).to receive(:execute_hooks).with(award_from_user, 'revoke')

          service.execute
        end
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module AwardEmojis
  class ToggleService < AwardEmojis::BaseService
    def execute
      if awardable.awarded_emoji?(name, current_user)
        DestroyService.new(awardable, name, current_user).execute
      else
        AddService.new(awardable, name, current_user).execute
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe AwardEmojis::ToggleService, feature_category: :team_planning do
  let_it_be(:user) { create(:user) }
  let_it_be(:project) { create(:project, :public) }
  let_it_be(:awardable) { create(:note, project: project) }

  let(:name) { 'thumbsup' }

  subject(:service) { described_class.new(awardable, name, user) }

  describe '#execute' do
    context 'when user has awarded an emoji' do
      let!(:award_from_other_user) { create(:award_emoji, name: name, awardable: awardable, user: create(:user)) }
      let!(:award) { create(:award_emoji, name: name, awardable: awardable, user: user) }

      it 'calls AwardEmojis::DestroyService' do
        expect(AwardEmojis::AddService).not_to receive(:new)

        expect_next_instance_of(AwardEmojis::DestroyService) do |service|
          expect(service).to receive(:execute)
        end

        service.execute
      end

      it 'destroys an AwardEmoji' do
        expect { service.execute }.to change { AwardEmoji.count }.by(-1)
      end

      it 'returns the result of DestroyService#execute' do
        mock_result = double(foo: true)

        expect_next_instance_of(AwardEmojis::DestroyService) do |service|
          expect(service).to receive(:execute).and_return(mock_result)
        end

        result = service.execute

        expect(result).to eq(mock_result)
      end
    end

    context 'when user has not awarded an emoji' do
      it 'calls AwardEmojis::AddService' do
        expect_next_instance_of(AwardEmojis::AddService) do |service|
          expect(service).to receive(:execute)
        end

        expect(AwardEmojis::DestroyService).not_to receive(:new)

        service.execute
      end

      it 'creates an AwardEmoji' do
        expect { service.execute }.to change { AwardEmoji.count }.by(1)
      end

      it 'returns the result of AddService#execute' do
        mock_result = double(foo: true)

        expect_next_instance_of(AwardEmojis::AddService) do |service|
          expect(service).to receive(:execute).and_return(mock_result)
        end

        result = service.execute

        expect(result).to eq(mock_result)
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module VsCode
  module Settings
    class CreateOrUpdateService
      def initialize(current_user:, params: {})
        @current_user = current_user
        @params = params
      end

      def execute
        # The GitLab VSCode settings API does not support creating or updating
        # machines.
        return ServiceResponse.success(payload: DEFAULT_MACHINE) if @params[:setting_type] == 'machines'

        setting = VsCodeSetting.by_user(current_user).by_setting_type(params[:setting_type]).first

        if setting.nil?
          merged_params = params.merge(user: current_user, uuid: SecureRandom.uuid)
          setting = VsCodeSetting.new(merged_params)
        else
          setting.content = params[:content]
          setting.uuid = SecureRandom.uuid
        end

        if setting.save
          ServiceResponse.success(payload: setting)
        else
          ServiceResponse.error(
            message: setting.errors.full_messages.to_sentence,
            payload: { setting: setting }
          )
        end
      end

      private

      attr_reader :current_user, :params
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe VsCode::Settings::CreateOrUpdateService, feature_category: :web_ide do
  describe '#execute' do
    let_it_be(:user) { create(:user) }

    let(:opts) do
      {
        setting_type: "settings",
        content: '{ "editor.fontSize": 12 }'
      }
    end

    subject { described_class.new(current_user: user, params: opts).execute }

    context 'when setting_type is machines' do
      it 'returns default machine as a successful response' do
        opts = { setting_type: "machines", machines: '[]' }
        result = described_class.new(current_user: user, params: opts).execute

        expect(result.payload).to eq(VsCode::Settings::DEFAULT_MACHINE)
      end
    end

    it 'creates a new record when a record with the setting does not exist' do
      expect { subject }.to change { User.find(user.id).vscode_settings.count }.from(0).to(1)
      record = User.find(user.id).vscode_settings.by_setting_type('settings').first
      expect(record.content).to eq('{ "editor.fontSize": 12 }')
    end

    it 'updates the existing record if setting exists' do
      setting = create(:vscode_setting, user: user)

      expect { subject }.to change {
        VsCode::Settings::VsCodeSetting.find(setting.id).content
      }.from(setting.content).to(opts[:content])
    end

    it 'fails if an invalid value is passed' do
      invalid_opts = { setting_type: nil, content: nil }
      result = described_class.new(current_user: user, params: invalid_opts).execute

      expect(result.status).to eq(:error)
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module VsCode
  module Settings
    class DeleteService
      def initialize(current_user:)
        @current_user = current_user
      end

      def execute
        VsCodeSetting.by_user(current_user).delete_all

        ServiceResponse.success
      end

      private

      attr_reader :current_user
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe VsCode::Settings::DeleteService, feature_category: :web_ide do
  describe '#execute' do
    let_it_be(:user) { create(:user) }
    let_it_be(:other_user) { create(:user) }
    let_it_be(:setting_one) { create(:vscode_setting, user: user) }
    let_it_be(:setting_two) { create(:vscode_setting, setting_type: 'extensions', user: user) }
    let_it_be(:setting_three) { create(:vscode_setting, setting_type: 'extensions', user: other_user) }

    subject { described_class.new(current_user: user).execute }

    it 'deletes all vscode_settings belonging to the current user' do
      expect { subject }
        .to change { User.find(user.id).vscode_settings.count }.from(2).to(0)
        .and not_change { User.find(other_user.id).vscode_settings.count }
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class FindOrCreateService
    attr_accessor :project, :current_user, :params

    def initialize(project, user, params = {})
      @project = project
      @current_user = user
      @params = params.dup
    end

    def execute
      find_milestone || create_milestone
    end

    private

    # rubocop: disable CodeReuse/ActiveRecord
    def find_milestone
      groups = project.group&.self_and_ancestors_ids
      Milestone.for_projects_and_groups([project.id], groups).find_by(title: params["title"])
    end
    # rubocop: enable CodeReuse/ActiveRecord

    def create_milestone
      return unless current_user.can?(:admin_milestone, project)

      new_milestone if new_milestone.persisted?
    end

    def new_milestone
      @new_milestone ||= CreateService.new(project, current_user, params).execute
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::FindOrCreateService, feature_category: :team_planning do
  describe '#execute' do
    subject(:service) { described_class.new(project, user, params) }

    let(:user)    { create(:user) }
    let(:group)   { create(:group) }
    let(:project) { create(:project, namespace: group) }
    let(:params) do
      {
        title: '1.0',
        description: 'First Release',
        start_date: Date.today,
        due_date: Date.today + 1.month
      }.with_indifferent_access
    end

    context 'when finding milestone on project level' do
      let!(:existing_project_milestone) { create(:milestone, project: project, title: '1.0') }

      it 'returns existing milestone' do
        expect(service.execute).to eq(existing_project_milestone)
      end
    end

    context 'when finding milestone on group level' do
      let!(:existing_group_milestone) { create(:milestone, group: group, title: '1.0') }

      it 'returns existing milestone' do
        expect(service.execute).to eq(existing_group_milestone)
      end
    end

    context 'when not finding milestone' do
      context 'when user has permissions' do
        before do
          project.add_developer(user)
        end

        context 'when params are valid' do
          it 'creates a new milestone at project level using params' do
            expect { service.execute }.to change(project.milestones, :count).by(1)

            milestone = project.reload.milestones.last

            expect(milestone.title).to eq(params[:title])
            expect(milestone.description).to eq(params[:description])
            expect(milestone.start_date).to eq(params[:start_date])
            expect(milestone.due_date).to eq(params[:due_date])
          end
        end

        context 'when params are not valid' do
          before do
            params[:start_date] = Date.today + 2.months
          end

          it 'returns nil' do
            expect(service.execute).to be_nil
          end
        end
      end

      context 'when user does not have permissions' do
        before do
          project.add_guest(user)
        end

        it 'does not create a new milestone' do
          expect { service.execute }.not_to change(project.milestones, :count)
        end

        it 'returns nil' do
          expect(service.execute).to be_nil
        end
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class MergeRequestsCountService < BaseCountService
    def initialize(milestone)
      @milestone = milestone
    end

    def cache_key
      "milestone_merge_requests_count_#{@milestone.milestoneish_id}"
    end

    def relation_for_count
      @milestone.merge_requests
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::MergeRequestsCountService, :use_clean_rails_memory_store_caching,
  feature_category: :team_planning do
  let_it_be(:project) { create(:project, :empty_repo) }
  let_it_be(:milestone) { create(:milestone, project: project) }

  before_all do
    create(:merge_request, milestone: milestone, source_project: project)
    create(:merge_request, :closed, milestone: milestone, source_project: project)
  end

  subject { described_class.new(milestone) }

  it_behaves_like 'a counter caching service'

  it 'counts all merge requests' do
    expect(subject.count).to eq(2)
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class ClosedIssuesCountService < BaseCountService
    def initialize(milestone)
      @milestone = milestone
    end

    def cache_key
      "milestone_closed_issues_count_#{@milestone.milestoneish_id}"
    end

    def relation_for_count
      @milestone.issues.closed
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::ClosedIssuesCountService, :use_clean_rails_memory_store_caching,
  feature_category: :team_planning do
  let(:project) { create(:project) }
  let(:milestone) { create(:milestone, project: project) }

  before do
    create(:issue, milestone: milestone, project: project)
    create(:issue, :confidential, milestone: milestone, project: project)

    create(:issue, :closed, milestone: milestone, project: project)
    create(:issue, :closed, :confidential, milestone: milestone, project: project)
  end

  subject { described_class.new(milestone) }

  it_behaves_like 'a counter caching service'

  it 'counts closed issues including confidential' do
    expect(subject.count).to eq(2)
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class PromoteService < Milestones::BaseService
    PromoteMilestoneError = Class.new(StandardError)

    def execute(milestone)
      check_project_milestone!(milestone)

      Milestone.transaction do
        group_milestone = clone_project_milestone(milestone)

        move_children_to_group_milestone(group_milestone)

        # Destroy all milestones with same title across projects
        destroy_old_milestones(milestone)

        # Rollback if milestone is not valid
        unless group_milestone.valid?
          raise_error(group_milestone.errors.full_messages.to_sentence)
        end

        group_milestone
      end
    end

    private

    def milestone_ids_for_merge(group_milestone)
      # Pluck need to be used here instead of select so the array of ids
      # is persistent after old milestones gets deleted.
      @milestone_ids_for_merge ||= begin
        search_params = { title: group_milestone.title, project_ids: group_project_ids, state: 'all' }
        milestones = MilestonesFinder.new(search_params).execute
        milestones.pluck_primary_key
      end
    end

    def move_children_to_group_milestone(group_milestone)
      milestone_ids_for_merge(group_milestone).in_groups_of(100, false) do |milestone_ids|
        update_children(group_milestone, milestone_ids)
      end
    end

    def check_project_milestone!(milestone)
      raise_error(s_('PromoteMilestone|Only project milestones can be promoted.')) unless milestone.project_milestone?
    end

    def clone_project_milestone(milestone)
      params = milestone.slice(:title, :description, :start_date, :due_date, :state_event)

      create_service = CreateService.new(group, current_user, params)

      milestone = create_service.execute

      # milestone won't be valid here because of duplicated title
      milestone.save(validate: false)

      milestone
    end

    # rubocop: disable CodeReuse/ActiveRecord
    def update_children(group_milestone, milestone_ids)
      issues = Issue.where(project_id: group_project_ids, milestone_id: milestone_ids)
      merge_requests = MergeRequest.where(source_project_id: group_project_ids, milestone_id: milestone_ids)

      [issues, merge_requests].each do |issuable_collection|
        issuable_collection.update_all(milestone_id: group_milestone.id)
      end
    end
    # rubocop: enable CodeReuse/ActiveRecord

    def group
      @group ||= parent.group || raise_error(s_('PromoteMilestone|Project does not belong to a group.'))
    end

    # rubocop: disable CodeReuse/ActiveRecord
    def destroy_old_milestones(milestone)
      Milestone.where(id: milestone_ids_for_merge(milestone)).destroy_all # rubocop: disable Cop/DestroyAll
    end
    # rubocop: enable CodeReuse/ActiveRecord

    def group_project_ids
      group.projects.select(:id)
    end

    def raise_error(message)
      raise PromoteMilestoneError, s_("PromoteMilestone|Promotion failed - %{message}") % { message: message }
    end
  end
end

Milestones::PromoteService.prepend_mod_with('Milestones::PromoteService')

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::PromoteService, feature_category: :team_planning do
  let(:group) { create(:group) }
  let(:project) { create(:project, namespace: group) }
  let(:user) { create(:user) }
  let(:milestone_title) { 'project milestone' }
  let(:milestone) { create(:milestone, project: project, title: milestone_title) }
  let(:service) { described_class.new(project, user) }

  describe '#execute' do
    before do
      group.add_maintainer(user)
    end

    context 'validations' do
      it 'raises error if milestone does not belong to a project' do
        allow(milestone).to receive(:project_milestone?).and_return(false)

        expect { service.execute(milestone) }.to raise_error(described_class::PromoteMilestoneError)
      end

      it 'raises error if project does not belong to a group' do
        project.update!(namespace: user.namespace)

        expect { service.execute(milestone) }.to raise_error(described_class::PromoteMilestoneError)
      end

      it 'does not promote milestone and update issuables if promoted milestone is not valid' do
        issue = create(:issue, milestone: milestone, project: project)
        merge_request = create(:merge_request, milestone: milestone, source_project: project)
        allow_next_instance_of(Milestone) do |instance|
          allow(instance).to receive(:valid?).and_return(false)
        end

        expect { service.execute(milestone) }.to raise_error(described_class::PromoteMilestoneError)

        expect(milestone.reload).to be_persisted
        expect(issue.reload.milestone).to eq(milestone)
        expect(merge_request.reload.milestone).to eq(milestone)
      end
    end

    context 'without duplicated milestone titles across projects' do
      it 'promotes project milestone to group milestone' do
        promoted_milestone = service.execute(milestone)

        expect(promoted_milestone).to be_group_milestone
      end

      it 'does not update issuables without milestone with the new promoted milestone' do
        issue_without_milestone = create(:issue, project: project, milestone: nil)
        merge_request_without_milestone = create(:merge_request, milestone: nil, source_project: project)

        service.execute(milestone)

        expect(issue_without_milestone.reload.milestone).to be_nil
        expect(merge_request_without_milestone.reload.milestone).to be_nil
      end

      it 'sets issuables with new promoted milestone' do
        issue = create(:issue, milestone: milestone, project: project)
        merge_request = create(:merge_request, milestone: milestone, source_project: project)

        promoted_milestone = service.execute(milestone)

        expect(promoted_milestone).to be_group_milestone
        expect(issue.reload.milestone).to eq(promoted_milestone)
        expect(merge_request.reload.milestone).to eq(promoted_milestone)
      end
    end

    context 'with duplicated milestone titles across projects' do
      let(:project_2) { create(:project, namespace: group) }
      let!(:milestone_2) { create(:milestone, project: project_2, title: milestone_title) }

      it 'deletes project milestones with the same title' do
        promoted_milestone = service.execute(milestone)

        expect(promoted_milestone).to be_group_milestone
        expect(promoted_milestone).to be_valid
        expect(Milestone.exists?(milestone.id)).to be_falsy
        expect(Milestone.exists?(milestone_2.id)).to be_falsy
      end

      it 'does not update issuables without milestone with the new promoted milestone' do
        issue_without_milestone_1 = create(:issue, project: project, milestone: nil)
        issue_without_milestone_2 = create(:issue, project: project_2, milestone: nil)
        merge_request_without_milestone_1 = create(:merge_request, milestone: nil, source_project: project)
        merge_request_without_milestone_2 = create(:merge_request, milestone: nil, source_project: project_2)

        service.execute(milestone)

        expect(issue_without_milestone_1.reload.milestone).to be_nil
        expect(issue_without_milestone_2.reload.milestone).to be_nil
        expect(merge_request_without_milestone_1.reload.milestone).to be_nil
        expect(merge_request_without_milestone_2.reload.milestone).to be_nil
      end

      it 'sets all issuables with new promoted milestone' do
        issue = create(:issue, milestone: milestone, project: project)
        issue_2 = create(:issue, milestone: milestone_2, project: project_2)
        merge_request = create(:merge_request, milestone: milestone, source_project: project)
        merge_request_2 = create(:merge_request, milestone: milestone_2, source_project: project_2)

        promoted_milestone = service.execute(milestone)

        expect(issue.reload.milestone).to eq(promoted_milestone)
        expect(issue_2.reload.milestone).to eq(promoted_milestone)
        expect(merge_request.reload.milestone).to eq(promoted_milestone)
        expect(merge_request_2.reload.milestone).to eq(promoted_milestone)
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class IssuesCountService < BaseCountService
    def initialize(milestone)
      @milestone = milestone
    end

    def cache_key
      "milestone_total_issues_count_#{@milestone.milestoneish_id}"
    end

    def relation_for_count
      @milestone.issues
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::IssuesCountService, :use_clean_rails_memory_store_caching,
  feature_category: :team_planning do
  let(:project) { create(:project) }
  let(:milestone) { create(:milestone, project: project) }

  before do
    create(:issue, milestone: milestone, project: project)
    create(:issue, :confidential, milestone: milestone, project: project)

    create(:issue, :closed, milestone: milestone, project: project)
    create(:issue, :closed, milestone: milestone, project: project)
  end

  subject { described_class.new(milestone) }

  it_behaves_like 'a counter caching service'

  it 'counts all issues including confidential' do
    expect(subject.count).to eq(4)
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

# Milestones::TransferService class
#
# Used for recreating the missing group milestones at project level when
# transferring a project to a new namespace
#
module Milestones
  class TransferService
    attr_reader :current_user, :old_group, :project

    def initialize(current_user, old_group, project)
      @current_user = current_user
      @old_group = old_group
      @project = project
    end

    def execute
      return unless old_group.present?

      Milestone.transaction do
        milestones_to_transfer.find_each do |milestone|
          new_milestone = find_or_create_milestone(milestone)

          update_issues_milestone(milestone, new_milestone)
          update_merge_requests_milestone(milestone.id, new_milestone&.id)

          delete_milestone_counts_caches(milestone)
          delete_milestone_counts_caches(new_milestone)
        end
      end
    end

    private

    # rubocop: disable CodeReuse/ActiveRecord
    def milestones_to_transfer
      Milestone.from_union([group_milestones_applied_to_issues, group_milestones_applied_to_merge_requests])
        .reorder(nil)
        .distinct
    end
    # rubocop: enable CodeReuse/ActiveRecord

    # rubocop: disable CodeReuse/ActiveRecord
    def group_milestones_applied_to_issues
      Milestone.joins(:issues)
        .where(
          issues: { project_id: project.id },
          group_id: old_group.self_and_ancestors
        )
    end
    # rubocop: enable CodeReuse/ActiveRecord

    # rubocop: disable CodeReuse/ActiveRecord
    def group_milestones_applied_to_merge_requests
      Milestone.joins(:merge_requests)
        .where(
          merge_requests: { target_project_id: project.id },
          group_id: old_group.self_and_ancestors
        )
    end
    # rubocop: enable CodeReuse/ActiveRecord

    def find_or_create_milestone(milestone)
      params = milestone.attributes.slice('title', 'description', 'start_date', 'due_date', 'state')

      FindOrCreateService.new(project, current_user, params).execute
    end

    # rubocop: disable CodeReuse/ActiveRecord
    def update_issues_milestone(old_milestone, new_milestone)
      Issue.where(project: project, milestone_id: old_milestone.id)
        .update_all(milestone_id: new_milestone&.id)
    end
    # rubocop: enable CodeReuse/ActiveRecord

    # rubocop: disable CodeReuse/ActiveRecord
    def update_merge_requests_milestone(old_milestone_id, new_milestone_id)
      MergeRequest.where(project: project, milestone_id: old_milestone_id)
        .update_all(milestone_id: new_milestone_id)
    end
    # rubocop: enable CodeReuse/ActiveRecord

    def delete_milestone_counts_caches(milestone)
      return unless milestone

      Milestones::IssuesCountService.new(milestone).delete_cache
      Milestones::ClosedIssuesCountService.new(milestone).delete_cache
      Milestones::MergeRequestsCountService.new(milestone).delete_cache
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::TransferService, feature_category: :team_planning do
  describe '#execute' do
    subject(:service) { described_class.new(user, old_group, project) }

    context 'when old_group is present' do
      let(:user) { create(:admin) }
      let(:new_group) { create(:group) }
      let(:old_group) { create(:group) }
      let(:project) { create(:project, namespace: old_group) }
      let(:group_milestone) { create(:milestone, :closed, group: old_group) }
      let(:group_milestone2) { create(:milestone, group: old_group) }
      let(:project_milestone) { create(:milestone, project: project) }
      let!(:issue_with_group_milestone) { create(:issue, project: project, milestone: group_milestone) }
      let!(:issue_with_project_milestone) { create(:issue, project: project, milestone: project_milestone) }
      let!(:mr_with_group_milestone) { create(:merge_request, source_project: project, source_branch: 'branch-1', milestone: group_milestone) }
      let!(:mr_with_project_milestone) { create(:merge_request, source_project: project, source_branch: 'branch-2', milestone: project_milestone) }

      before do
        new_group.add_maintainer(user)
        project.add_maintainer(user)
        # simulate project transfer
        project.update!(group: new_group)
      end

      context 'without existing milestone at the new group level' do
        it 'recreates the missing group milestones at project level' do
          expect { service.execute }.to change(project.milestones, :count).by(1)
        end

        it 'applies new project milestone to issues with group milestone' do
          service.execute
          new_milestone = issue_with_group_milestone.reload.milestone

          expect(new_milestone).not_to eq(group_milestone)
          expect(new_milestone.title).to eq(group_milestone.title)
          expect(new_milestone.project_milestone?).to be_truthy
          expect(new_milestone.state).to eq("closed")
        end

        context 'when milestone is from an ancestor group' do
          let(:old_group_ancestor) { create(:group) }
          let(:old_group) { create(:group, parent: old_group_ancestor) }
          let(:group_milestone) { create(:milestone, group: old_group_ancestor) }

          it 'recreates the missing group milestones at project level' do
            expect { service.execute }.to change(project.milestones, :count).by(1)
          end
        end

        it 'deletes milestone counters cache for both milestones' do
          new_milestone = create(:milestone, project: project, title: group_milestone.title)

          expect_next_instance_of(Milestones::IssuesCountService, group_milestone) do |service|
            expect(service).to receive(:delete_cache).and_call_original
          end
          expect_next_instance_of(Milestones::ClosedIssuesCountService, group_milestone) do |service|
            expect(service).to receive(:delete_cache).and_call_original
          end
          expect_next_instance_of(Milestones::MergeRequestsCountService, group_milestone) do |service|
            expect(service).to receive(:delete_cache).and_call_original
          end
          expect_next_instance_of(Milestones::IssuesCountService, new_milestone) do |service|
            expect(service).to receive(:delete_cache).and_call_original
          end
          expect_next_instance_of(Milestones::ClosedIssuesCountService, new_milestone) do |service|
            expect(service).to receive(:delete_cache).and_call_original
          end
          expect_next_instance_of(Milestones::MergeRequestsCountService, new_milestone) do |service|
            expect(service).to receive(:delete_cache).and_call_original
          end

          service.execute
        end

        it 'does not apply new project milestone to issues with project milestone' do
          service.execute

          expect(issue_with_project_milestone.reload.milestone).to eq(project_milestone)
        end

        it 'applies new project milestone to merge_requests with group milestone' do
          service.execute
          new_milestone = mr_with_group_milestone.reload.milestone

          expect(new_milestone).not_to eq(group_milestone)
          expect(new_milestone.title).to eq(group_milestone.title)
          expect(new_milestone.project_milestone?).to be_truthy
          expect(new_milestone.state).to eq("closed")
        end

        it 'does not apply new project milestone to issuables with project milestone' do
          service.execute

          expect(mr_with_project_milestone.reload.milestone).to eq(project_milestone)
        end

        it 'does not recreate missing group milestones that are not applied to issues or merge requests' do
          service.execute
          new_milestone_title = project.reload.milestones.pluck(:title)

          expect(new_milestone_title).to include(group_milestone.title)
          expect(new_milestone_title).not_to include(group_milestone2.title)
        end

        context 'when find_or_create_milestone returns nil' do
          before do
            allow_next_instance_of(Milestones::FindOrCreateService) do |instance|
              allow(instance).to receive(:execute).and_return(nil)
            end
          end

          it 'removes issues group milestone' do
            service.execute

            expect(mr_with_group_milestone.reload.milestone).to be_nil
          end

          it 'removes merge requests group milestone' do
            service.execute

            expect(issue_with_group_milestone.reload.milestone).to be_nil
          end
        end
      end

      context 'with existing milestone at the new group level' do
        let!(:existing_milestone) { create(:milestone, group: new_group, title: group_milestone.title) }

        it 'does not create a new milestone' do
          expect { service.execute }.not_to change(project.milestones, :count)
        end

        it 'applies existing milestone to issues with group milestone' do
          service.execute

          expect(issue_with_group_milestone.reload.milestone).to eq(existing_milestone)
        end

        it 'applies existing milestone to merge_requests with group milestone' do
          service.execute

          expect(mr_with_group_milestone.reload.milestone).to eq(existing_milestone)
        end
      end
    end
  end

  context 'when old_group is not present' do
    let(:user)        { create(:admin) }
    let(:old_group)   { project.group }
    let(:project)     { create(:project, namespace: user.namespace) }

    it 'returns nil' do
      expect(described_class.new(user, old_group, project).execute).to be_nil
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class CloseService < Milestones::BaseService
    def execute(milestone)
      if milestone.close && milestone.project_milestone?
        event_service.close_milestone(milestone, current_user)
      end

      milestone
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::CloseService, feature_category: :team_planning do
  let(:user) { create(:user) }
  let(:project) { create(:project) }
  let(:milestone) { create(:milestone, title: "Milestone v1.2", project: project) }

  before do
    project.add_maintainer(user)
  end

  describe '#execute' do
    before do
      described_class.new(project, user, {}).execute(milestone)
    end

    it { expect(milestone).to be_valid }
    it { expect(milestone).to be_closed }

    describe 'event' do
      let(:event) { Event.recent.first }

      it { expect(event.milestone).to be_truthy }
      it { expect(event.target).to eq(milestone) }
      it { expect(event.action_name).to eq('closed') }
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class DestroyService < Milestones::BaseService
    def execute(milestone)
      Milestone.transaction do
        update_params = { milestone_id: nil, skip_milestone_email: true }

        milestone.issues.each do |issue|
          Issues::UpdateService.new(container: parent, current_user: current_user, params: update_params).execute(issue)
        end

        milestone.merge_requests.each do |merge_request|
          MergeRequests::UpdateService.new(project: parent, current_user: current_user, params: update_params).execute(merge_request)
        end

        log_destroy_event_for(milestone)

        milestone.destroy
      end
    end

    def log_destroy_event_for(milestone)
      return if milestone.group_milestone?

      event_service.destroy_milestone(milestone, current_user)

      Event.for_milestone_id(milestone.id).each do |event|
        event.target_id = nil
        event.save
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::DestroyService, feature_category: :team_planning do
  let(:user) { create(:user) }
  let(:project) { create(:project, :repository) }
  let(:milestone) { create(:milestone, title: 'Milestone v1.0', project: project) }

  before do
    project.add_maintainer(user)
  end

  def service
    described_class.new(project, user, {})
  end

  describe '#execute' do
    it 'deletes milestone' do
      service.execute(milestone)

      expect { milestone.reload }.to raise_error ActiveRecord::RecordNotFound
    end

    context 'with an existing merge request' do
      let!(:issue) { create(:issue, project: project, milestone: milestone) }
      let!(:merge_request) { create(:merge_request, source_project: project, milestone: milestone) }

      it 'deletes milestone id from issuables' do
        service.execute(milestone)

        expect(issue.reload.milestone).to be_nil
        expect(merge_request.reload.milestone).to be_nil
      end
    end

    it 'logs destroy event' do
      service.execute(milestone)

      event = Event.where(project_id: milestone.project_id, target_type: 'Milestone')

      expect(event.count).to eq(1)
    end

    context 'group milestones' do
      let(:group) { create(:group) }
      let(:group_milestone) { create(:milestone, group: group) }

      before do
        project.update!(namespace: group)
        group.add_developer(user)
      end

      it { expect(service.execute(group_milestone)).to eq(group_milestone) }

      it 'deletes milestone id from issuables' do
        issue = create(:issue, project: project, milestone: group_milestone)
        merge_request = create(:merge_request, source_project: project, milestone: group_milestone)

        service.execute(group_milestone)

        expect(issue.reload.milestone).to be_nil
        expect(merge_request.reload.milestone).to be_nil
      end

      it 'does not log destroy event' do
        expect { service.execute(group_milestone) }.not_to change { Event.count }
      end
    end

    context 'when a release is tied to a milestone' do
      it 'destroys the milestone but not the associated release' do
        release = create(
          :release,
          tag: 'v1.0',
          project: project,
          milestones: [milestone]
        )

        expect { service.execute(milestone) }.not_to change { Release.count }
        expect(release.reload).to be_persisted
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class UpdateService < Milestones::BaseService
    def execute(milestone)
      state = params[:state_event]

      case state
      when 'activate'
        Milestones::ReopenService.new(parent, current_user, {}).execute(milestone)
      when 'close'
        Milestones::CloseService.new(parent, current_user, {}).execute(milestone)
      end

      if params.present?
        milestone.assign_attributes(params.except(:state_event))
      end

      if milestone.changed?
        before_update(milestone)
      end

      milestone.save
      milestone
    end

    private

    def before_update(milestone)
      milestone.check_for_spam(user: current_user, action: :update)
    end
  end
end

Milestones::UpdateService.prepend_mod_with('Milestones::UpdateService')

```

Response:
# frozen_string_literal: true
require 'spec_helper'

RSpec.describe Milestones::UpdateService, feature_category: :team_planning do
  let_it_be(:user) { create(:user) }
  let_it_be(:project) { create(:project) }
  let_it_be(:milestone) { create(:milestone, project: project) }
  let_it_be(:params) { { title: 'New Title' } }

  subject(:update_milestone) { described_class.new(project, user, params) }

  describe '#execute' do
    context 'when state_event is "activate"' do
      let(:params) { { state_event: 'activate' } }

      it 'calls Milestones::ReopenService' do
        reopen_service = instance_double(Milestones::ReopenService)
        expect(Milestones::ReopenService).to receive(:new).with(project, user, {}).and_return(reopen_service)
        expect(reopen_service).to receive(:execute).with(milestone)

        update_milestone.execute(milestone)
      end
    end

    context 'when state_event is "close"' do
      let(:params) { { state_event: 'close' } }

      it 'calls Milestones::CloseService' do
        close_service = instance_double(Milestones::CloseService)
        expect(Milestones::CloseService).to receive(:new).with(project, user, {}).and_return(close_service)
        expect(close_service).to receive(:execute).with(milestone)

        update_milestone.execute(milestone)
      end
    end

    context 'when params are present' do
      it 'assigns the params to the milestone' do
        expect(milestone).to receive(:assign_attributes).with(params.except(:state_event))

        update_milestone.execute(milestone)
      end
    end

    context 'when milestone is changed' do
      before do
        allow(milestone).to receive(:changed?).and_return(true)
      end

      it 'calls before_update' do
        expect(update_milestone).to receive(:before_update).with(milestone)

        update_milestone.execute(milestone)
      end
    end

    context 'when milestone is not changed' do
      before do
        allow(milestone).to receive(:changed?).and_return(false)
      end

      it 'does not call before_update' do
        expect(update_milestone).not_to receive(:before_update)

        update_milestone.execute(milestone)
      end
    end

    it 'saves the milestone' do
      expect(milestone).to receive(:save)

      update_milestone.execute(milestone)
    end

    it 'returns the milestone' do
      expect(update_milestone.execute(milestone)).to eq(milestone)
    end
  end

  describe '#before_update' do
    it 'checks for spam' do
      expect(milestone).to receive(:check_for_spam).with(user: user, action: :update)

      update_milestone.send(:before_update, milestone)
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Milestones
  class CreateService < Milestones::BaseService
    def execute
      milestone = parent.milestones.new(params)

      before_create(milestone)

      if milestone.save && milestone.project_milestone?
        event_service.open_milestone(milestone, current_user)
      end

      milestone
    end

    private

    def before_create(milestone)
      milestone.check_for_spam(user: current_user, action: :create)
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Milestones::CreateService, feature_category: :team_planning do
  let_it_be(:user) { create(:user) }
  let_it_be(:project) { create(:project) }
  let_it_be(:params) { { title: 'New Milestone', description: 'Description' } }

  subject(:create_milestone) { described_class.new(project, user, params) }

  describe '#execute' do
    context 'when milestone is saved successfully' do
      it 'creates a new milestone' do
        expect { create_milestone.execute }.to change { Milestone.count }.by(1)
      end

      it 'opens the milestone if it is a project milestone' do
        expect_next_instance_of(EventCreateService) do |instance|
          expect(instance).to receive(:open_milestone)
        end

        create_milestone.execute
      end

      it 'returns the created milestone' do
        milestone = create_milestone.execute
        expect(milestone).to be_a(Milestone)
        expect(milestone.title).to eq('New Milestone')
        expect(milestone.description).to eq('Description')
      end
    end

    context 'when milestone fails to save' do
      before do
        allow_next_instance_of(Milestone) do |instance|
          allow(instance).to receive(:save).and_return(false)
        end
      end

      it 'does not create a new milestone' do
        expect { create_milestone.execute }.not_to change { Milestone.count }
      end

      it 'does not open the milestone' do
        expect(EventCreateService).not_to receive(:open_milestone)

        create_milestone.execute
      end

      it 'returns the unsaved milestone' do
        milestone = create_milestone.execute
        expect(milestone).to be_a(Milestone)
        expect(milestone.title).to eq('New Milestone')
        expect(milestone.persisted?).to be_falsey
      end
    end

    it 'calls before_create method' do
      expect(create_milestone).to receive(:before_create)
      create_milestone.execute
    end
  end

  describe '#before_create' do
    it 'checks for spam' do
      milestone = build(:milestone)
      expect(milestone).to receive(:check_for_spam).with(user: user, action: :create)
      subject.send(:before_create, milestone)
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Applications
  class CreateService
    attr_reader :current_user, :params

    def initialize(current_user, params)
      @current_user = current_user
      @params = params.except(:ip_address)
    end

    # EE would override and use `request` arg
    def execute(request)
      @application = Doorkeeper::Application.new(params)

      unless params[:scopes].present?
        @application.errors.add(:base, _("Scopes can't be blank"))

        return @application
      end

      @application.save
      @application
    end
  end
end

Applications::CreateService.prepend_mod_with('Applications::CreateService')

```

Response:
# frozen_string_literal: true

require "spec_helper"

RSpec.describe ::Applications::CreateService do
  include TestRequestHelpers

  let(:user) { create(:user) }

  subject { described_class.new(user, params) }

  context 'when scopes are present' do
    let(:params) { attributes_for(:application, scopes: ['read_user']) }

    it { expect { subject.execute(test_request) }.to change { Doorkeeper::Application.count }.by(1) }
  end

  context 'when scopes are missing' do
    let(:params) { attributes_for(:application) }

    it { expect { subject.execute(test_request) }.not_to change { Doorkeeper::Application.count } }

    it 'includes blank scopes error message' do
      application = subject.execute(test_request)

      expect(application.errors.full_messages).to include "Scopes can't be blank"
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module JiraConnect
  class CreateAsymmetricJwtService
    ARGUMENT_ERROR_MESSAGE = 'jira_connect_installation is not a proxy installation'

    def initialize(jira_connect_installation, event: :installed)
      raise ArgumentError, ARGUMENT_ERROR_MESSAGE unless jira_connect_installation.proxy?

      @jira_connect_installation = jira_connect_installation
      @event = event
    end

    def execute
      JWT.encode(jwt_claims, private_key, 'RS256', jwt_headers)
    end

    private

    def jwt_claims
      { aud: aud_claim, iss: iss_claim, qsh: qsh_claim }
    end

    def aud_claim
      @jira_connect_installation.audience_url
    end

    def iss_claim
      @jira_connect_installation.client_key
    end

    def qsh_claim
      Atlassian::Jwt.create_query_string_hash(
        audience_event_url,
        'POST',
        @jira_connect_installation.audience_url
      )
    end

    def audience_event_url
      return @jira_connect_installation.audience_uninstalled_event_url if @event == :uninstalled

      @jira_connect_installation.audience_installed_event_url
    end

    def private_key
      @private_key ||= OpenSSL::PKey::RSA.generate(3072)
    end

    def public_key_storage
      @public_key_storage ||= JiraConnect::PublicKey.create!(key: private_key.public_key)
    end

    def jwt_headers
      { kid: public_key_storage.uuid }
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe JiraConnect::CreateAsymmetricJwtService, feature_category: :integrations do
  describe '#execute' do
    let_it_be(:jira_connect_installation) { create(:jira_connect_installation) }

    let(:service) { described_class.new(jira_connect_installation) }

    subject(:jwt_token) { service.execute }

    it 'raises an error' do
      expect { jwt_token }.to raise_error(ArgumentError, 'jira_connect_installation is not a proxy installation')
    end

    context 'with proxy installation' do
      let_it_be(:jira_connect_installation) { create(:jira_connect_installation, instance_url: 'https://gitlab.test') }

      let(:public_key_id) { Atlassian::Jwt.decode(jwt_token, nil, false, algorithm: 'RS256').last['kid'] }
      let(:public_key_cdn) { 'https://gitlab.com/-/jira_connect/public_keys/' }
      let(:event_url) { 'https://gitlab.test/-/jira_connect/events/installed' }
      let(:jwt_verification_claims) do
        {
          aud: 'https://gitlab.test/-/jira_connect',
          iss: jira_connect_installation.client_key,
          qsh: Atlassian::Jwt.create_query_string_hash(event_url, 'POST', 'https://gitlab.test/-/jira_connect')
        }
      end

      subject(:jwt_token) { service.execute }

      shared_examples 'produces a valid JWT' do
        it 'produces a valid JWT' do
          public_key = OpenSSL::PKey.read(JiraConnect::PublicKey.find(public_key_id).key)
          options = jwt_verification_claims.except(:qsh).merge({ verify_aud: true, verify_iss: true,
                                                                 algorithm: 'RS256' })

          decoded_token = Atlassian::Jwt.decode(jwt_token, public_key, true, options).first

          expect(decoded_token).to eq(jwt_verification_claims.stringify_keys)
        end
      end

      it 'stores the public key' do
        expect { JiraConnect::PublicKey.find(public_key_id) }.not_to raise_error
      end

      it_behaves_like 'produces a valid JWT'

      context 'with uninstalled event option' do
        let(:service) { described_class.new(jira_connect_installation, event: :uninstalled) }
        let(:event_url) { 'https://gitlab.test/-/jira_connect/events/uninstalled' }

        it_behaves_like 'produces a valid JWT'
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module JiraConnect
  class SyncService
    def initialize(project)
      self.project = project
    end

    # Parameters: see Atlassian::JiraConnect::Client#send_info
    # Includes: update_sequence_id, commits, branches, merge_requests, pipelines
    def execute(**args)
      preload_reviewers_for_merge_requests(args[:merge_requests]) if args.key?(:merge_requests)

      JiraConnectInstallation.for_project(project).flat_map do |installation|
        client = Atlassian::JiraConnect::Client.new(installation.base_url, installation.shared_secret)

        responses = client.send_info(project: project, **args)

        responses.each { |r| log_response(r) }
      end
    end

    private

    attr_accessor :project

    def log_response(response)
      message = {
        message: 'response from jira dev_info api',
        integration: 'JiraConnect',
        project_id: project.id,
        project_path: project.full_path,
        jira_response: response&.to_json
      }

      has_errors = response && (response['errorMessage'].present? || response['errorMessages'].present?)

      if has_errors
        logger.error(message)
      else
        logger.info(message)
      end
    end

    def logger
      Gitlab::IntegrationsLogger
    end

    def preload_reviewers_for_merge_requests(merge_requests)
      ActiveRecord::Associations::Preloader.new(
        records: merge_requests, associations: [:approvals, { merge_request_reviewers: :reviewer }]
      ).call
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe JiraConnect::SyncService, feature_category: :integrations do
  include AfterNextHelpers

  describe '#execute' do
    let_it_be(:project) { create(:project, :repository) }
    let_it_be(:merge_request) { create(:merge_request, source_project: project) }
    let_it_be(:merge_request_reviewer) { create(:merge_request_reviewer, merge_request: merge_request) }

    let(:client) { Atlassian::JiraConnect::Client }
    let(:info) { { a: 'Some', b: 'Info', merge_requests: [merge_request] } }

    subject do
      described_class.new(project).execute(**info)
    end

    before do
      create(:jira_connect_subscription, namespace: project.namespace)
    end

    def store_info(return_values = [{ 'status': 'success' }])
      receive(:send_info).with(project: project, **info).and_return(return_values)
    end

    def expect_log(type, message)
      expect(Gitlab::IntegrationsLogger)
        .to receive(type).with(
          {
            message: 'response from jira dev_info api',
            integration: 'JiraConnect',
            project_id: project.id,
            project_path: project.full_path,
            jira_response: message&.to_json
          }
        )
    end

    it 'calls Atlassian::JiraConnect::Client#store_dev_info and logs the response' do
      expect_next(client).to store_info

      expect_log(:info, { 'status': 'success' })

      subject
    end

    it 'does not execute any queries for preloaded reviewers' do
      expect_next(client).to store_info

      expect_log(:info, { 'status': 'success' })

      amount = ActiveRecord::QueryRecorder
        .new { info[:merge_requests].flat_map(&:merge_request_reviewers).map(&:reviewer) }
        .count

      expect(amount).to be_zero

      subject
    end

    context 'when a request returns errors' do
      it 'logs each response as an error' do
        expect_next(client).to store_info(
          [
            { 'errorMessages' => ['some error message'] },
            { 'errorMessage' => 'a single error message' },
            { 'errorMessages' => [] },
            { 'errorMessage' => '' }
          ])

        expect_log(:error, { 'errorMessages' => ['some error message'] })
        expect_log(:error, { 'errorMessage' => 'a single error message' })

        subject
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Files
  class BaseService < Commits::CreateService
    FileChangedError = Class.new(StandardError)

    def initialize(*args)
      super

      git_user = Gitlab::Git::User.from_gitlab(current_user) if current_user.present?

      @author_email = commit_email(git_user)
      @author_name = params[:author_name] || git_user&.name
      @commit_message = params[:commit_message]
      @last_commit_sha = params[:last_commit_sha]

      @file_path = params[:file_path]
      @previous_path = params[:previous_path]

      @file_content = params[:file_content]
      @file_content = Base64.decode64(@file_content) if params[:file_content_encoding] == 'base64'

      @execute_filemode = params[:execute_filemode]
    end

    def file_has_changed?(path, commit_id)
      return false unless commit_id

      last_commit_from_branch = get_last_commit_for_path(ref: @start_branch, path: path)

      return false unless last_commit_from_branch

      last_commit_from_commit_id = get_last_commit_for_path(ref: commit_id, path: path)

      return false unless last_commit_from_commit_id

      last_commit_from_branch.sha != last_commit_from_commit_id.sha
    end

    private

    def get_last_commit_for_path(ref:, path:)
      Gitlab::Git::Commit.last_for_path(@start_project.repository, ref, path, literal_pathspec: true)
    end

    def commit_email(git_user)
      return params[:author_email] if params[:author_email].present?
      return unless current_user

      namespace_commit_email = current_user.namespace_commit_email_for_project(@start_project)

      return namespace_commit_email.email.email if namespace_commit_email

      git_user.email
    end
  end
end

```

Response:
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Files::BaseService, feature_category: :source_code_management do
  let_it_be(:group) { create(:group) }
  let_it_be(:project) { create(:project, group: group) }
  let_it_be(:user) { create(:user) }
  let(:params) { {} }

  subject(:author_email) { described_class.new(project, user, params).instance_variable_get(:@author_email) }

  before do
    group.add_developer(user)
  end

  context 'with no namespace_commit_emails' do
    it 'sets @author_email to user default email' do
      expect(author_email).to eq(user.email)
    end
  end

  context 'with an author_email in params and namespace_commit_email' do
    let(:params) { { author_email: 'email_from_params@example.com' } }

    before do
      create(:namespace_commit_email, user: user, namespace: group)
    end

    it 'gives precedence to the parameter value for @author_email' do
      expect(author_email).to eq('email_from_params@example.com')
    end
  end

  context 'with a project namespace_commit_email' do
    it 'sets @author_email to the project namespace_commit_email' do
      namespace_commit_email = create(:namespace_commit_email, user: user, namespace: project.project_namespace)

      expect(author_email).to eq(namespace_commit_email.email.email)
    end
  end

  context 'with a group namespace_commit_email' do
    it 'sets @author_email to the group namespace_commit_email' do
      namespace_commit_email = create(:namespace_commit_email, user: user, namespace: group)

      expect(author_email).to eq(namespace_commit_email.email.email)
    end
  end

  context 'with a project and group namespace_commit_email' do
    it 'sets @author_email to the project namespace_commit_email' do
      namespace_commit_email = create(:namespace_commit_email, user: user, namespace: project.project_namespace)
      create(:namespace_commit_email, user: user, namespace: group)

      expect(author_email).to eq(namespace_commit_email.email.email)
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Files
  class MultiService < Files::BaseService
    UPDATE_FILE_ACTIONS = %w[update move delete chmod].freeze

    def create_commit!
      transformer = Lfs::FileTransformer.new(project, repository, @branch_name)

      actions = actions_after_lfs_transformation(transformer, params[:actions])
      actions = transform_move_actions(actions)

      commit_actions!(actions)
    end

    private

    def actions_after_lfs_transformation(transformer, actions)
      actions.map do |action|
        if action[:action] == 'create'
          result = transformer.new_file(action[:file_path], action[:content], encoding: action[:encoding])
          action[:content] = result.content
          action[:encoding] = result.encoding
        end

        action
      end
    end

    # When moving a file, `content: nil` means "use the contents of the previous
    # file", while `content: ''` means "move the file and set it to empty"
    def transform_move_actions(actions)
      actions.map do |action|
        action[:infer_content] = true if action[:content].nil?

        action
      end
    end

    def commit_actions!(actions)
      repository.commit_files(
        current_user,
        message: @commit_message,
        branch_name: @branch_name,
        actions: actions,
        author_email: @author_email,
        author_name: @author_name,
        start_project: @start_project,
        start_branch_name: @start_branch,
        start_sha: @start_sha,
        force: force?
      )
    rescue ArgumentError => e
      raise_error(e)
    end

    def validate!
      super

      params[:actions].each { |action| validate_file_status!(action) }
    end

    def validate_file_status!(action)
      return unless UPDATE_FILE_ACTIONS.include?(action[:action])

      file_path = action[:previous_path] || action[:file_path]

      if file_has_changed?(file_path, action[:last_commit_id])
        raise_error("The file has changed since you started editing it: #{file_path}")
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Files::MultiService, feature_category: :source_code_management do
  subject { described_class.new(project, user, commit_params) }

  let(:project) { create(:project, :repository) }
  let(:repository) { project.repository }
  let(:user) { create(:user) }
  let(:branch_name) { project.default_branch }
  let(:original_file_path) { 'files/ruby/popen.rb' }
  let(:new_file_path) { 'files/ruby/popen.rb' }
  let(:file_content) { 'New content' }
  let(:action) { 'update' }
  let(:commit_message) { 'Update File' }

  let!(:original_commit_id) do
    Gitlab::Git::Commit.last_for_path(project.repository, branch_name, original_file_path).sha
  end

  let(:branch_commit_id) do
    Gitlab::Git::Commit.find(project.repository, branch_name).sha
  end

  let(:default_action) do
    {
      action: action,
      file_path: new_file_path,
      previous_path: original_file_path,
      content: file_content,
      last_commit_id: original_commit_id
    }
  end

  let(:actions) { [default_action] }

  let(:commit_params) do
    {
      commit_message: commit_message,
      branch_name: branch_name,
      start_branch: branch_name,
      actions: actions
    }
  end

  before do
    project.add_maintainer(user)
  end

  describe '#execute' do
    context 'with a valid action' do
      it 'returns a hash with the :success status' do
        results = subject.execute

        expect(results[:status]).to eq(:success)
      end
    end

    context 'with an invalid action' do
      let(:action) { 'rename' }

      it 'returns a hash with the :error status' do
        results = subject.execute

        expect(results[:status]).to eq(:error)
        expect(results[:message]).to match(/Unknown action/)
      end
    end

    describe 'Updating files' do
      context 'when the file has been previously updated' do
        before do
          update_file(original_file_path)
        end

        it 'rejects the commit' do
          results = subject.execute

          expect(results[:status]).to eq(:error)
          expect(results[:message]).to match(new_file_path)
        end
      end

      context 'when file not changed, but later commit id is used' do
        let(:actions) { [default_action.merge(last_commit_id: branch_commit_id)] }

        it 'accepts the commit' do
          results = subject.execute

          expect(results[:status]).to eq(:success)
        end
      end

      context 'when the file have not been modified' do
        it 'accepts the commit' do
          results = subject.execute

          expect(results[:status]).to eq(:success)
        end
      end
    end

    describe 'changing execute_filemode of a file' do
      let(:commit_message) { 'Chmod +x file' }
      let(:file_path) { original_file_path }
      let(:default_action) do
        {
          action: 'chmod',
          file_path: file_path,
          execute_filemode: true
        }
      end

      it 'accepts the commit' do
        results = subject.execute

        expect(results[:status]).to eq(:success)
      end

      it 'updates the execute_filemode of the file' do
        expect { subject.execute }.to change { repository.blob_at_branch(branch_name, file_path).mode }.from('100644').to('100755')
      end

      context "when the file doesn't exists" do
        let(:file_path) { 'files/wrong_path.rb' }

        it 'rejects the commit' do
          results = subject.execute

          expect(results[:status]).to eq(:error)
          expect(results[:message]).to eq("A file with this name doesn't exist")
        end
      end
    end

    context 'when moving a file' do
      let(:action) { 'move' }
      let(:new_file_path) { 'files/ruby/new_popen.rb' }

      let(:result) { subject.execute }
      let(:blob) { repository.blob_at_branch(branch_name, new_file_path) }

      context 'when original file has been updated' do
        before do
          update_file(original_file_path)
        end

        it 'rejects the commit' do
          expect(result[:status]).to eq(:error)
          expect(result[:message]).to match(original_file_path)
        end
      end

      context 'when original file has not been updated' do
        it 'moves the file' do
          expect(result[:status]).to eq(:success)
          expect(blob).to be_present
          expect(blob.data).to eq(file_content)
        end

        context 'when content is nil' do
          let(:file_content) { nil }

          it 'moves the existing content untouched' do
            original_content = repository.blob_at_branch(branch_name, original_file_path).data

            expect(result[:status]).to eq(:success)
            expect(blob).to be_present
            expect(blob.data).to eq(original_content)
          end
        end

        context 'when content is an empty string' do
          let(:file_content) { '' }

          it 'moves the file and empties it' do
            expect(result[:status]).to eq(:success)
            expect(blob).not_to be_nil
            expect(blob.data).to eq('')
          end
        end
      end
    end

    context 'when creating a file matching an LFS filter' do
      let(:action) { 'create' }
      let(:branch_name) { 'lfs' }
      let(:new_file_path) { 'test_file.lfs' }

      before do
        allow(project).to receive(:lfs_enabled?).and_return(true)
      end

      it 'creates an LFS pointer' do
        subject.execute

        blob = repository.blob_at('lfs', new_file_path)

        expect(blob.data).to start_with(Gitlab::Git::LfsPointerFile::VERSION_LINE)
      end

      it "creates an LfsObject with the file's content" do
        subject.execute

        expect(LfsObject.last.file.read).to eq file_content
      end

      context 'with base64 encoded content' do
        let(:raw_file_content) { 'Raw content' }
        let(:file_content) { Base64.encode64(raw_file_content) }
        let(:actions) { [default_action.merge(encoding: 'base64')] }

        it 'creates an LFS pointer' do
          subject.execute

          blob = repository.blob_at('lfs', new_file_path)

          expect(blob.data).to start_with(Gitlab::Git::LfsPointerFile::VERSION_LINE)
        end

        it "creates an LfsObject with the file's content" do
          subject.execute

          expect(LfsObject.last.file.read).to eq raw_file_content
        end
      end

      it 'links the LfsObject to the project' do
        expect do
          subject.execute
        end.to change { project.lfs_objects.count }.by(1)
      end
    end

    context 'when file status validation is skipped' do
      let(:action) { 'create' }
      let(:new_file_path) { 'files/ruby/new_file.rb' }

      it 'does not check the last commit' do
        expect(Gitlab::Git::Commit).not_to receive(:last_for_path)

        subject.execute
      end

      it 'creates the file' do
        subject.execute

        blob = project.repository.blob_at_branch(branch_name, new_file_path)

        expect(blob).to be_present
      end
    end

    context 'when force is set to true and branch already exists' do
      let(:commit_params) do
        {
          commit_message: commit_message,
          branch_name: 'feature',
          start_branch: 'master',
          actions: actions,
          force: true
        }
      end

      it 'is still a success' do
        expect(subject.execute[:status]).to eq(:success)
      end
    end
  end

  def update_file(path)
    params = {
      file_path: path,
      start_branch: branch_name,
      branch_name: branch_name,
      commit_message: 'Update file',
      file_content: 'New content'
    }

    Files::UpdateService.new(project, user, params).execute
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Files
  class UpdateService < Files::BaseService
    def create_commit!
      repository.update_file(
        current_user,
        @file_path,
        @file_content,
        message: @commit_message,
        branch_name: @branch_name,
        previous_path: @previous_path,
        author_email: @author_email,
        author_name: @author_name,
        start_project: @start_project,
        start_branch_name: @start_branch,
        execute_filemode: @execute_filemode
      )
    end

    private

    def validate!
      super

      if file_has_changed?(@file_path, @last_commit_sha)
        raise FileChangedError, _('You are attempting to update a file that has changed since you started editing it.')
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Files::UpdateService, feature_category: :source_code_management do
  subject { described_class.new(project, user, commit_params) }

  let(:project) { create(:project, :repository) }
  let(:user) { create(:user, :commit_email) }
  let(:file_path) { 'files/ruby/popen.rb' }
  let(:new_contents) { 'New Content' }
  let(:branch_name) { project.default_branch }
  let(:last_commit_sha) { nil }
  let(:commit) { project.repository.commit }

  let(:commit_params) do
    {
      file_path: file_path,
      commit_message: "Update File",
      file_content: new_contents,
      file_content_encoding: "text",
      last_commit_sha: last_commit_sha,
      start_project: project,
      start_branch: project.default_branch,
      branch_name: branch_name
    }
  end

  before do
    project.add_maintainer(user)
  end

  describe "#execute" do
    context "when the file's last commit sha is earlier than the latest change for that branch" do
      let(:last_commit_sha) { Gitlab::Git::Commit.last_for_path(project.repository, project.default_branch, file_path).parent_id }

      it "returns a hash with the correct error message and a :error status" do
        expect { subject.execute }
          .to raise_error(
            Files::UpdateService::FileChangedError,
            "You are attempting to update a file that has changed since you started editing it."
          )
      end
    end

    context "when the file's last commit sha does match the supplied last_commit_sha" do
      let(:last_commit_sha) { Gitlab::Git::Commit.last_for_path(project.repository, project.default_branch, file_path).sha }

      it "returns a hash with the :success status" do
        results = subject.execute

        expect(results[:status]).to match(:success)
      end

      it "updates the file with the new contents" do
        subject.execute

        results = project.repository.blob_at_branch(project.default_branch, file_path)

        expect(results.data).to eq(new_contents)
      end

      it 'uses the commit email' do
        subject.execute

        expect(user.commit_email).not_to eq(user.email)
        expect(commit.author_email).to eq(user.commit_email)
        expect(commit.committer_email).to eq(user.commit_email)
      end
    end

    context "when the last_commit_sha is not supplied" do
      it "returns a hash with the :success status" do
        results = subject.execute

        expect(results[:status]).to match(:success)
      end

      it "updates the file with the new contents" do
        subject.execute

        results = project.repository.blob_at_branch(project.default_branch, file_path)

        expect(results.data).to eq(new_contents)
      end
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Files
  class CreateService < Files::BaseService
    def create_commit!
      transformer = Lfs::FileTransformer.new(project, repository, @branch_name)

      result = transformer.new_file(@file_path, @file_content)

      create_transformed_commit(result.content)
    end

    private

    def create_transformed_commit(content_or_lfs_pointer)
      repository.create_file(
        current_user,
        @file_path,
        content_or_lfs_pointer,
        message: @commit_message,
        branch_name: @branch_name,
        author_email: @author_email,
        author_name: @author_name,
        start_project: @start_project,
        start_branch_name: @start_branch,
        execute_filemode: @execute_filemode)
    end
  end
end

```

Response:
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Files::CreateService, feature_category: :source_code_management do
  let(:project) { create(:project, :repository) }
  let(:repository) { project.repository }
  let(:user) { create(:user, :commit_email) }
  let(:file_content) { 'Test file content' }
  let(:branch_name) { project.default_branch }
  let(:start_branch) { branch_name }

  let(:commit_params) do
    {
      file_path: file_path,
      commit_message: "Update File",
      file_content: file_content,
      file_content_encoding: "text",
      start_project: project,
      start_branch: start_branch,
      branch_name: branch_name
    }
  end

  let(:commit) { repository.head_commit }

  subject { described_class.new(project, user, commit_params) }

  before do
    project.add_maintainer(user)
  end

  describe "#execute" do
    context 'when file matches LFS filter' do
      let(:file_path) { 'test_file.lfs' }
      let(:branch_name) { 'lfs' }

      context 'with LFS disabled' do
        it 'skips gitattributes check' do
          expect(repository).not_to receive(:attributes_at)

          subject.execute
        end

        it "doesn't create LFS pointers" do
          subject.execute

          blob = repository.blob_at('lfs', file_path)

          expect(blob.data).not_to start_with(Gitlab::Git::LfsPointerFile::VERSION_LINE)
          expect(blob.data).to eq(file_content)
        end
      end

      context 'with LFS enabled' do
        before do
          allow(project).to receive(:lfs_enabled?).and_return(true)
        end

        it 'creates an LFS pointer' do
          subject.execute

          blob = repository.blob_at('lfs', file_path)

          expect(blob.data).to start_with(Gitlab::Git::LfsPointerFile::VERSION_LINE)
        end

        it "creates an LfsObject with the file's content" do
          subject.execute

          expect(LfsObject.last.file.read).to eq file_content
        end

        it 'links the LfsObject to the project' do
          expect do
            subject.execute
          end.to change { project.lfs_objects.count }.by(1)
        end
      end
    end
  end

  context 'commit attribute' do
    let(:file_path) { 'test-commit-attributes.txt' }

    it 'uses the commit email' do
      subject.execute

      expect(user.commit_email).not_to eq(user.email)
      expect(commit.author_email).to eq(user.commit_email)
      expect(commit.committer_email).to eq(user.commit_email)
    end
  end
end


Instruction:
Write RSpec test file for following ruby class
```ruby
# frozen_string_literal: true

module Files
  class DeleteService < Files::BaseService
    def create_commit!
      repository.delete_file(
        current_user,
        @file_path,
        message: @commit_message,
        branch_name: @branch_name,
        author_email: @author_email,
        author_name: @author_name,
        start_project: @start_project,
        start_branch_name: @start_branch)
    end

    private

    def validate!
      super

      if file_has_changed?(@file_path, @last_commit_sha)
        raise FileChangedError, _("You are attempting to delete a file that has been previously updated.")
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Files::DeleteService, feature_category: :source_code_management do
  subject { described_class.new(project, user, commit_params) }

  let(:project) { create(:project, :repository) }
  let(:user) { create(:user, :commit_email) }
  let(:file_path) { 'files/ruby/popen.rb' }
  let(:branch_name) { project.default_branch }
  let(:last_commit_sha) { nil }
  let(:commit) { project.repository.head_commit }

  let(:commit_params) do
    {
      file_path: file_path,
      commit_message: "Delete File",
      last_commit_sha: last_commit_sha,
      start_project: project,
      start_branch: project.default_branch,
      branch_name: branch_name
    }
  end

  shared_examples 'successfully deletes the file' do
    it 'returns a hash with the :success status' do
      results = subject.execute

      expect(results[:status]).to match(:success)
    end

    it 'deletes the file' do
      subject.execute

      blob = project.repository.blob_at_branch(project.default_branch, file_path)

      expect(blob).to be_nil
    end

    it 'uses the commit email' do
      subject.execute

      expect(user.commit_email).not_to eq(user.email)
      expect(commit.author_email).to eq(user.commit_email)
      expect(commit.committer_email).to eq(user.commit_email)
    end
  end

  before do
    project.add_maintainer(user)
  end

  describe "#execute" do
    context "when the file's last commit is earlier than the latest commit for this branch" do
      let(:last_commit_sha) { Gitlab::Git::Commit.last_for_path(project.repository, project.default_branch, file_path).parent_id }

      it "returns a hash with the correct error message and a :error status" do
        expect { subject.execute }.to raise_error(
          Files::UpdateService::FileChangedError,
          "You are attempting to delete a file that has been previously updated."
        )
      end
    end

    context "when the file's last commit sha does match the supplied last_commit_sha" do
      let(:last_commit_sha) { Gitlab::Git::Commit.last_for_path(project.repository, project.default_branch, file_path).sha }

      it_behaves_like 'successfully deletes the file'
    end

    context "when the last_commit_sha is not supplied" do
      it_behaves_like 'successfully deletes the file'
    end
  end
end