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

module Notes
  class CreateService < ::Notes::BaseService
    include IncidentManagement::UsageData

    def execute(skip_capture_diff_note_position: false, skip_merge_status_trigger: false, skip_set_reviewed: false)
      note = Notes::BuildService.new(project, current_user, params.except(:merge_request_diff_head_sha)).execute

      # n+1: https://gitlab.com/gitlab-org/gitlab-foss/issues/37440
      note_valid = Gitlab::GitalyClient.allow_n_plus_1_calls do
        # We may set errors manually in Notes::BuildService for this reason
        # we also need to check for already existing errors.
        note.errors.empty? && note.valid?
      end

      return note unless note_valid

      # We execute commands (extracted from `params[:note]`) on the noteable
      # **before** we save the note because if the note consists of commands
      # only, there is no need be create a note!

      execute_quick_actions(note) do |only_commands|
        note.check_for_spam(action: :create, user: current_user) unless only_commands

        note.run_after_commit do
          # Finish the harder work in the background
          NewNoteWorker.perform_async(note.id)
        end

        note_saved = note.with_transaction_returning_status do
          break false if only_commands

          note.save.tap do
            update_discussions(note)
          end
        end

        if note_saved
          when_saved(
            note,
            skip_capture_diff_note_position: skip_capture_diff_note_position,
            skip_merge_status_trigger: skip_merge_status_trigger,
            skip_set_reviewed: skip_set_reviewed
          )
        end
      end

      note
    end

    private

    def execute_quick_actions(note)
      return yield(false) unless quick_actions_supported?(note)

      content, update_params, message, command_names = quick_actions_service.execute(note, quick_action_options)
      only_commands = content.empty?
      note.note = content
      note.command_names = command_names

      yield(only_commands)

      do_commands(note, update_params, message, command_names, only_commands)
    end

    def quick_actions_supported?(note)
      quick_actions_service.supported?(note)
    end

    def quick_actions_service
      @quick_actions_service ||= QuickActionsService.new(project, current_user)
    end

    def update_discussions(note)
      # Ensure that individual notes that are promoted into discussions are
      # updated in a transaction with the note creation to avoid inconsistencies:
      # https://gitlab.com/gitlab-org/gitlab/-/issues/301237
      if note.part_of_discussion? && note.discussion.can_convert_to_discussion?
        note.discussion.convert_to_discussion!.save
        note.clear_memoization(:discussion)
      end
    end

    def when_saved(
      note, skip_capture_diff_note_position: false, skip_merge_status_trigger: false,
      skip_set_reviewed: false)
      todo_service.new_note(note, current_user)
      clear_noteable_diffs_cache(note)
      Suggestions::CreateService.new(note).execute
      increment_usage_counter(note)
      track_event(note, current_user)

      if note.for_merge_request? && note.start_of_discussion?
        set_reviewed(note) unless skip_set_reviewed

        if !skip_capture_diff_note_position && note.diff_note?
          Discussions::CaptureDiffNotePositionService.new(note.noteable, note.diff_file&.paths).execute(note.discussion)
        end

        if !skip_merge_status_trigger && note.to_be_resolved?
          GraphqlTriggers.merge_request_merge_status_updated(note.noteable)
        end
      end
    end

    def do_commands(note, update_params, message, command_names, only_commands)
      return if quick_actions_service.commands_executed_count.to_i == 0

      update_error = quick_actions_update_errors(note, update_params)
      if update_error
        note.errors.add(:validation, update_error)
        message = update_error
      end

      # We must add the error after we call #save because errors are reset
      # when #save is called
      if only_commands
        note.errors.add(:commands_only, message.presence || _('Failed to apply commands.'))
        note.errors.add(:command_names, command_names.flatten)
        # Allow consumers to detect problems applying commands
        note.errors.add(:commands, _('Failed to apply commands.')) unless message.present?
      end
    end

    def quick_actions_update_errors(note, params)
      return unless params.present?

      invalid_message = validate_commands(note, params)
      return invalid_message if invalid_message

      service_response = quick_actions_service.apply_updates(params, note)
      note.commands_changes = params
      return if service_response.success?

      service_response.message.join(', ')
    end

    def quick_action_options
      {
        merge_request_diff_head_sha: params[:merge_request_diff_head_sha],
        review_id: params[:review_id]
      }
    end

    def validate_commands(note, update_params)
      if invalid_reviewers?(update_params)
        "Reviewers #{note.noteable.class.max_number_of_assignees_or_reviewers_message}"
      elsif invalid_assignees?(update_params)
        "Assignees #{note.noteable.class.max_number_of_assignees_or_reviewers_message}"
      end
    end

    def invalid_reviewers?(update_params)
      if update_params.key?(:reviewer_ids)
        possible_reviewers = update_params[:reviewer_ids]&.uniq&.size

        possible_reviewers > ::Issuable::MAX_NUMBER_OF_ASSIGNEES_OR_REVIEWERS
      else
        false
      end
    end

    def invalid_assignees?(update_params)
      if update_params.key?(:assignee_ids)
        possible_assignees = update_params[:assignee_ids]&.uniq&.size

        possible_assignees > ::Issuable::MAX_NUMBER_OF_ASSIGNEES_OR_REVIEWERS
      else
        false
      end
    end

    def track_event(note, user)
      track_note_creation_usage_for_issues(note) if note.for_issue?
      track_note_creation_usage_for_merge_requests(note) if note.for_merge_request?
      track_incident_action(user, note.noteable, 'incident_comment') if note.for_issue?
      track_note_creation_in_ipynb(note)
      track_note_creation_visual_review(note)

      metric_key_path = 'counts.commit_comment'

      Gitlab::Tracking.event(
        'Notes::CreateService',
        'create_commit_comment',
        project: project,
        namespace: project&.namespace,
        user: user,
        label: metric_key_path,
        context: [Gitlab::Usage::MetricDefinition.context_for(metric_key_path).to_context]
      )
    end

    def tracking_data_for(note)
      label = Gitlab.ee? && note.author == Users::Internal.visual_review_bot ? 'anonymous_visual_review_note' : 'note'

      {
        label: label,
        value: note.id
      }
    end

    def track_note_creation_usage_for_issues(note)
      Gitlab::UsageDataCounters::IssueActivityUniqueCounter.track_issue_comment_added_action(
        author: note.author,
        project: project
      )
    end

    def track_note_creation_usage_for_merge_requests(note)
      Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter.track_create_comment_action(note: note)
    end

    def should_track_ipynb_notes?(note)
      note.respond_to?(:diff_file) && note.diff_file&.ipynb?
    end

    def track_note_creation_in_ipynb(note)
      return unless should_track_ipynb_notes?(note)

      Gitlab::UsageDataCounters::IpynbDiffActivityCounter.note_created(note)
    end

    def track_note_creation_visual_review(note)
      Gitlab::Tracking.event('Notes::CreateService', 'execute', **tracking_data_for(note))
    end

    def set_reviewed(note)
      return if Feature.enabled?(:mr_request_changes, current_user)

      ::MergeRequests::UpdateReviewerStateService.new(project: project, current_user: current_user)
        .execute(note.noteable, "reviewed")
    end
  end
end

Notes::CreateService.prepend_mod_with('Notes::CreateService')

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Notes::CreateService, feature_category: :team_planning do
  let_it_be(:group) { create(:group) }
  let_it_be(:project) { create(:project, :repository, group: group) }
  let_it_be(:issue) { create(:issue, project: project) }
  let_it_be(:user) { create(:user) }

  let(:base_opts) { { note: 'Awesome comment', noteable_type: 'Issue', noteable_id: issue.id } }
  let(:opts) { base_opts.merge(confidential: true) }

  describe '#execute' do
    subject(:note) { described_class.new(project, user, opts).execute }

    before_all do
      group.add_maintainer(user)
    end

    context "valid params" do
      context 'when noteable is an issue that belongs directly to a group' do
        it 'creates a note without a project and correct namespace', :aggregate_failures do
          group_issue = create(:issue, :group_level, namespace: group)
          note_params = { note: 'test note', noteable: group_issue }

          expect do
            described_class.new(nil, user, note_params).execute
          end.to change { Note.count }.by(1)

          created_note = Note.last

          expect(created_note.namespace).to eq(group)
          expect(created_note.project).to be_nil
        end
      end

      context 'when noteable is a work item that belongs directly to a group' do
        it 'creates a note without a project and correct namespace', :aggregate_failures do
          group_work_item = create(:work_item, :group_level, namespace: group)
          note_params = { note: 'test note', noteable: group_work_item }

          expect do
            described_class.new(nil, user, note_params).execute
          end.to change { Note.count }.by(1)

          created_note = Note.last

          expect(created_note.namespace).to eq(group)
          expect(created_note.project).to be_nil
        end
      end

      it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do
        let(:action) { note }
      end

      it 'returns a valid note' do
        expect(note).to be_valid
      end

      it 'returns a persisted note' do
        expect(note).to be_persisted
      end

      it 'checks for spam' do
        expect_next_instance_of(Note) do |instance|
          expect(instance).to receive(:check_for_spam).with(action: :create, user: user)
        end

        note
      end

      it 'does not persist when spam' do
        expect_next_instance_of(Note) do |instance|
          expect(instance).to receive(:check_for_spam).with(action: :create, user: user) do
            instance.spam!
          end
        end

        expect(note).not_to be_persisted
      end

      context 'with internal parameter' do
        context 'when confidential' do
          let(:opts) { base_opts.merge(internal: true) }

          it 'returns a confidential note' do
            expect(note).to be_confidential
          end
        end

        context 'when not confidential' do
          let(:opts) { base_opts.merge(internal: false) }

          it 'returns a confidential note' do
            expect(note).not_to be_confidential
          end
        end
      end

      context 'with confidential parameter' do
        context 'when confidential' do
          let(:opts) { base_opts.merge(confidential: true) }

          it 'returns a confidential note' do
            expect(note).to be_confidential
          end
        end

        context 'when not confidential' do
          let(:opts) { base_opts.merge(confidential: false) }

          it 'returns a confidential note' do
            expect(note).not_to be_confidential
          end
        end
      end

      context 'with confidential and internal parameter set' do
        let(:opts) { base_opts.merge(internal: true, confidential: false) }

        it 'prefers the internal parameter' do
          expect(note).to be_confidential
        end
      end

      it 'note has valid content' do
        expect(note.note).to eq(opts[:note])
      end

      it 'note belongs to the correct project' do
        expect(note.project).to eq(project)
      end

      it 'TodoService#new_note is called' do
        note = build(:note, project: project, noteable: issue)
        allow(Note).to receive(:new).with(opts) { note }

        expect_any_instance_of(TodoService).to receive(:new_note).with(note, user)

        described_class.new(project, user, opts).execute
      end

      it 'enqueues NewNoteWorker' do
        note = build(:note, id: non_existing_record_id, project: project, noteable: issue)
        allow(Note).to receive(:new).with(opts) { note }

        expect(NewNoteWorker).to receive(:perform_async).with(note.id)

        described_class.new(project, user, opts).execute
      end

      context 'issue is an incident' do
        let(:issue) { create(:incident, project: project) }

        it_behaves_like 'an incident management tracked event', :incident_management_incident_comment do
          let(:current_user) { user }
        end

        it_behaves_like 'Snowplow event tracking with RedisHLL context' do
          let(:namespace) { issue.namespace }
          let(:category) { described_class.to_s }
          let(:action) { 'incident_management_incident_comment' }
          let(:label) { 'redis_hll_counters.incident_management.incident_management_total_unique_counts_monthly' }
        end
      end

      context 'in a commit', :snowplow do
        let_it_be(:commit) { create(:commit, project: project) }
        let(:opts) { { note: 'Awesome comment', noteable_type: 'Commit', commit_id: commit.id } }

        let(:counter) { Gitlab::UsageDataCounters::NoteCounter }

        let(:execute_create_service) { described_class.new(project, user, opts).execute }

        it 'tracks commit comment usage data', :clean_gitlab_redis_shared_state do
          expect(counter).to receive(:count).with(:create, 'Commit').and_call_original

          expect do
            execute_create_service
          end.to change { counter.read(:create, 'Commit') }.by(1)
        end

        it_behaves_like 'Snowplow event tracking with Redis context' do
          let(:category) { described_class.name }
          let(:action) { 'create_commit_comment' }
          let(:label) { 'counts.commit_comment' }
          let(:namespace) { project.namespace }
        end
      end

      describe 'event tracking', :snowplow do
        let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_COMMENT_ADDED }
        let(:execute_create_service) { described_class.new(project, user, opts).execute }

        it 'tracks issue comment usage data', :clean_gitlab_redis_shared_state do
          counter = Gitlab::UsageDataCounters::HLLRedisCounter

          expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).to receive(:track_issue_comment_added_action)
                                                                             .with(author: user, project: project)
                                                                             .and_call_original
          expect do
            execute_create_service
          end.to change {
                   counter.unique_events(event_names: event, start_date: Date.today.beginning_of_week, end_date: 1.week.from_now)
                 }.by(1)
        end

        it 'does not track merge request usage data' do
          expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter).not_to receive(:track_create_comment_action)

          execute_create_service
        end

        it_behaves_like 'internal event tracking' do
          let(:event) { Gitlab::UsageDataCounters::IssueActivityUniqueCounter::ISSUE_COMMENT_ADDED }
          let(:namespace) { project.namespace }
          subject(:service_action) { execute_create_service }
        end
      end

      context 'in a merge request' do
        let_it_be(:project_with_repo) { create(:project, :repository) }
        let_it_be(:merge_request) do
          create(:merge_request, source_project: project_with_repo, target_project: project_with_repo)
        end

        let(:new_opts) { opts.merge(noteable_type: 'MergeRequest', noteable_id: merge_request.id) }

        context 'when mr_request_changes feature flag is disabled' do
          before do
            stub_feature_flags(mr_request_changes: false)
          end

          it 'calls MergeRequests::UpdateReviewerStateService service' do
            expect_next_instance_of(
              MergeRequests::UpdateReviewerStateService,
              project: project_with_repo, current_user: user
            ) do |service|
              expect(service).to receive(:execute).with(merge_request, "reviewed")
            end

            described_class.new(project_with_repo, user, new_opts).execute
          end

          it 'does not call MergeRequests::UpdateReviewerStateService service when skip_set_reviewed is true' do
            expect(MergeRequests::UpdateReviewerStateService).not_to receive(:new)

            described_class.new(project_with_repo, user, new_opts).execute(skip_set_reviewed: true)
          end
        end

        context 'when mr_request_changes feature flag is enabled' do
          it 'does not call MergeRequests::UpdateReviewerStateService service when skip_set_reviewed is true' do
            expect(MergeRequests::UpdateReviewerStateService).not_to receive(:new)

            described_class.new(project_with_repo, user, new_opts).execute(skip_set_reviewed: true)
          end
        end

        context 'noteable highlight cache clearing' do
          let(:position) do
            Gitlab::Diff::Position.new(
              old_path: "files/ruby/popen.rb",
              new_path: "files/ruby/popen.rb",
              old_line: nil,
              new_line: 14,
              diff_refs: merge_request.diff_refs
            )
          end

          let(:new_opts) do
            opts.merge(
              in_reply_to_discussion_id: nil,
              type: 'DiffNote',
              noteable_type: 'MergeRequest',
              noteable_id: merge_request.id,
              position: position.to_h,
              confidential: false
            )
          end

          before do
            allow_any_instance_of(Gitlab::Diff::Position)
              .to receive(:unfolded_diff?) { true }
          end

          it 'does not track issue comment usage data' do
            expect(Gitlab::UsageDataCounters::IssueActivityUniqueCounter).not_to receive(:track_issue_comment_added_action)

            described_class.new(project_with_repo, user, new_opts).execute
          end

          it 'tracks merge request usage data' do
            expect(Gitlab::UsageDataCounters::MergeRequestActivityUniqueCounter).to receive(:track_create_comment_action).with(note: kind_of(Note))

            described_class.new(project_with_repo, user, new_opts).execute
          end

          it 'clears noteable diff cache when it was unfolded for the note position' do
            expect_any_instance_of(Gitlab::Diff::HighlightCache).to receive(:clear)

            described_class.new(project_with_repo, user, new_opts).execute
          end

          it 'does not clear cache when note is not the first of the discussion' do
            prev_note =
              create(:diff_note_on_merge_request, noteable: merge_request, project: project_with_repo)
            reply_opts =
              opts.merge(
                in_reply_to_discussion_id: prev_note.discussion_id,
                type: 'DiffNote',
                noteable_type: 'MergeRequest',
                noteable_id: merge_request.id,
                position: position.to_h,
                confidential: false
              )

            expect(merge_request).not_to receive(:diffs)

            described_class.new(project_with_repo, user, reply_opts).execute
          end
        end

        context 'note diff file' do
          let(:line_number) { 14 }
          let(:position) do
            Gitlab::Diff::Position.new(
              old_path: "files/ruby/popen.rb",
              new_path: "files/ruby/popen.rb",
              old_line: nil,
              new_line: line_number,
              diff_refs: merge_request.diff_refs
            )
          end

          let(:previous_note) do
            create(:diff_note_on_merge_request, noteable: merge_request, project: project_with_repo)
          end

          before do
            project_with_repo.add_maintainer(user)
          end
          context 'when eligible to have a note diff file' do
            let(:new_opts) do
              opts.merge(
                in_reply_to_discussion_id: nil,
                type: 'DiffNote',
                noteable_type: 'MergeRequest',
                noteable_id: merge_request.id,
                position: position.to_h,
                confidential: false
              )
            end

            it_behaves_like 'triggers GraphQL subscription mergeRequestMergeStatusUpdated' do
              let(:action) { described_class.new(project_with_repo, user, new_opts).execute }
            end

            it 'note is associated with a note diff file' do
              MergeRequests::MergeToRefService.new(project: merge_request.project, current_user: merge_request.author).execute(merge_request)

              note = described_class.new(project_with_repo, user, new_opts).execute

              expect(note).to be_persisted
              expect(note.note_diff_file).to be_present
              expect(note.diff_note_positions).to be_present
            end

            context 'when skip_capture_diff_note_position execute option is set to true' do
              it 'does not execute Discussions::CaptureDiffNotePositionService' do
                expect(Discussions::CaptureDiffNotePositionService).not_to receive(:new)

                described_class.new(project_with_repo, user, new_opts).execute(skip_capture_diff_note_position: true)
              end
            end

            context 'when skip_merge_status_trigger execute option is set to true' do
              it_behaves_like 'does not trigger GraphQL subscription mergeRequestMergeStatusUpdated' do
                let(:action) do
                  described_class
                    .new(project_with_repo, user, new_opts)
                    .execute(skip_merge_status_trigger: true)
                end
              end
            end

            it 'does not track ipynb note usage data' do
              expect(::Gitlab::UsageDataCounters::IpynbDiffActivityCounter).not_to receive(:note_created)

              described_class.new(project_with_repo, user, new_opts).execute
            end

            context 'is ipynb file' do
              before do
                allow_any_instance_of(::Gitlab::Diff::File).to receive(:ipynb?).and_return(true)
              end

              it 'tracks ipynb diff note creation' do
                expect(::Gitlab::UsageDataCounters::IpynbDiffActivityCounter).to receive(:note_created)

                described_class.new(project_with_repo, user, new_opts).execute
              end
            end
          end

          context 'when DiffNote is a reply' do
            let(:new_opts) do
              opts.merge(
                in_reply_to_discussion_id: previous_note.discussion_id,
                type: 'DiffNote',
                noteable_type: 'MergeRequest',
                noteable_id: merge_request.id,
                position: position.to_h,
                confidential: false
              )
            end

            it 'note is not associated with a note diff file' do
              expect(Discussions::CaptureDiffNotePositionService).not_to receive(:new)

              note = described_class.new(project_with_repo, user, new_opts).execute

              expect(note).to be_persisted
              expect(note.note_diff_file).to be_nil
            end

            context 'when DiffNote from an image' do
              let(:image_position) do
                Gitlab::Diff::Position.new(
                  old_path: "files/images/6049019_460s.jpg",
                  new_path: "files/images/6049019_460s.jpg",
                  width: 100,
                  height: 100,
                  x: 1,
                  y: 100,
                  diff_refs: merge_request.diff_refs,
                  position_type: 'image'
                )
              end

              let(:new_opts) do
                opts.merge(
                  in_reply_to_discussion_id: nil,
                  type: 'DiffNote',
                  noteable_type: 'MergeRequest',
                  noteable_id: merge_request.id,
                  position: image_position.to_h,
                  confidential: false
                )
              end

              it 'note is not associated with a note diff file' do
                note = described_class.new(project_with_repo, user, new_opts).execute

                expect(note).to be_persisted
                expect(note.note_diff_file).to be_nil
              end
            end
          end
        end
      end
    end

    context 'note with commands' do
      context 'all quick actions' do
        let_it_be(:milestone) { create(:milestone, project: project, title: "sprint") }
        let_it_be(:bug_label) { create(:label, project: project, title: 'bug') }
        let_it_be(:to_be_copied_label) { create(:label, project: project, title: 'to be copied') }
        let_it_be(:feature_label) { create(:label, project: project, title: 'feature') }
        let_it_be(:issue, reload: true) { create(:issue, project: project, labels: [bug_label], due_date: '2019-01-01') }
        let_it_be(:issue_2) { create(:issue, project: project, labels: [bug_label, to_be_copied_label]) }

        context 'for issues' do
          let(:issuable) { issue }
          let(:note_params) { opts }
          let(:issue_quick_actions) do
            [
              QuickAction.new(
                action_text: '/confidential',
                expectation: ->(noteable, can_use_quick_action) {
                  if can_use_quick_action
                    expect(noteable).to be_confidential
                  else
                    expect(noteable).not_to be_confidential
                  end
                }
              ),
              QuickAction.new(
                action_text: '/due 2016-08-28',
                expectation: ->(noteable, can_use_quick_action) {
                  expect(noteable.due_date == Date.new(2016, 8, 28)).to eq(can_use_quick_action)
                }
              ),
              QuickAction.new(
                action_text: '/remove_due_date',
                expectation: ->(noteable, can_use_quick_action) {
                  if can_use_quick_action
                    expect(noteable.due_date).to be_nil
                  else
                    expect(noteable.due_date).not_to be_nil
                  end
                }
              ),
              QuickAction.new(
                action_text: "/duplicate #{issue_2.to_reference}",
                before_action: -> {
                  issuable.reopen
                },
                expectation: ->(noteable, can_use_quick_action) {
                  expect(noteable.closed?).to eq(can_use_quick_action)
                }
              )
            ]
          end

          it_behaves_like 'issuable quick actions' do
            let(:quick_actions) { issuable_quick_actions + issue_quick_actions }
          end
        end

        context 'for merge requests', feature_category: :code_review_workflow do
          let_it_be(:merge_request) { create(:merge_request, source_project: project, labels: [bug_label]) }

          let(:issuable) { merge_request }
          let(:note_params) { opts.merge(noteable_type: 'MergeRequest', noteable_id: merge_request.id, confidential: false) }
          let(:merge_request_quick_actions) do
            [
              QuickAction.new(
                action_text: "/target_branch fix",
                expectation: ->(noteable, can_use_quick_action) {
                  expect(noteable.target_branch == "fix").to eq(can_use_quick_action)
                }
              ),
              # Set Draft status
              QuickAction.new(
                action_text: "/draft",
                before_action: -> {
                  issuable.reload.update!(title: "title")
                },
                expectation: ->(issuable, can_use_quick_action) {
                  expect(issuable.draft?).to eq(can_use_quick_action)
                }
              ),
              # Remove draft (set ready) status
              QuickAction.new(
                action_text: "/ready",
                before_action: -> {
                  issuable.reload.update!(title: "Draft: title")
                },
                expectation: ->(noteable, can_use_quick_action) {
                  expect(noteable.draft?).not_to eq(can_use_quick_action)
                }
              )
            ]
          end

          it_behaves_like 'issuable quick actions' do
            let(:quick_actions) { issuable_quick_actions + merge_request_quick_actions }
          end
        end
      end

      context 'when note only has commands' do
        it 'adds commands applied message to note errors' do
          note_text = %(/close)
          service = double(:service)
          allow(Issues::UpdateService).to receive(:new).and_return(service)
          expect(service).to receive(:execute)

          note = described_class.new(project, user, opts.merge(note: note_text)).execute

          expect(note.errors[:commands_only]).to be_present
        end

        it 'adds commands failed message to note errors' do
          note_text = %(/reopen)
          note = described_class.new(project, user, opts.merge(note: note_text)).execute

          expect(note.errors[:commands_only]).to contain_exactly('Could not apply reopen command.')
        end

        it 'generates success and failed error messages' do
          note_text = %(/close\n/reopen)
          service = double(:service)
          allow(Issues::UpdateService).to receive(:new).and_return(service)
          expect(service).to receive(:execute)

          note = described_class.new(project, user, opts.merge(note: note_text)).execute

          expect(note.errors[:commands_only]).to contain_exactly('Closed this issue. Could not apply reopen command.')
        end

        it 'does not check for spam' do
          expect_next_instance_of(Note) do |instance|
            expect(instance).not_to receive(:check_for_spam).with(action: :create, user: user)
          end

          note_text = %(/close)
          described_class.new(project, user, opts.merge(note: note_text)).execute
        end

        it 'generates failed update error messages' do
          note_text = %(/confidential)
          service = double(:service)
          issue.errors.add(:confidential, 'an error occurred')
          allow(Issues::UpdateService).to receive(:new).and_return(service)
          allow_next_instance_of(Issues::UpdateService) do |service_instance|
            allow(service_instance).to receive(:execute).and_return(issue)
          end

          note = described_class.new(project, user, opts.merge(note: note_text)).execute
          expect(note.errors[:commands_only]).to contain_exactly('Confidential an error occurred')
        end
      end
    end

    context 'personal snippet note', feature_category: :source_code_management do
      subject { described_class.new(nil, user, params).execute }

      let(:snippet) { create(:personal_snippet) }
      let(:params) do
        { note: 'comment', noteable_type: 'Snippet', noteable_id: snippet.id }
      end

      it 'returns a valid note' do
        expect(subject).to be_valid
      end

      it 'returns a persisted note' do
        expect(subject).to be_persisted
      end

      it 'note has valid content' do
        expect(subject.note).to eq(params[:note])
      end
    end

    context 'design note', feature_category: :design_management do
      subject(:service) { described_class.new(project, user, params) }

      let_it_be(:design) { create(:design, :with_file) }
      let_it_be(:project) { design.project }
      let_it_be(:user) { project.first_owner }
      let_it_be(:params) do
        {
          type: 'DiffNote',
          noteable: design,
          note: "A message",
          position: {
            old_path: design.full_path,
            new_path: design.full_path,
            position_type: 'image',
            width: '100',
            height: '100',
            x: '50',
            y: '50',
            base_sha: design.diff_refs.base_sha,
            start_sha: design.diff_refs.base_sha,
            head_sha: design.diff_refs.head_sha
          }
        }
      end

      it 'can create diff notes for designs' do
        note = service.execute

        expect(note).to be_a(DiffNote)
        expect(note).to be_persisted
        expect(note.noteable).to eq(design)
      end

      it 'sends a notification about this note', :sidekiq_might_not_need_inline do
        notifier = double
        allow(::NotificationService).to receive(:new).and_return(notifier)

        expect(notifier)
          .to receive(:new_note)
          .with have_attributes(noteable: design)

        service.execute
      end

      it 'correctly builds the position of the note' do
        note = service.execute

        expect(note.position.new_path).to eq(design.full_path)
        expect(note.position.old_path).to eq(design.full_path)
        expect(note.position.diff_refs).to eq(design.diff_refs)
      end
    end

    context 'note with emoji only' do
      it 'creates regular note' do
        opts = {
          note: ':smile: ',
          noteable_type: 'Issue',
          noteable_id: issue.id
        }
        note = described_class.new(project, user, opts).execute

        expect(note).to be_valid
        expect(note.note).to eq(':smile:')
      end
    end

    context 'reply to individual note' do
      let(:existing_note) { create(:note_on_issue, noteable: issue, project: project) }
      let(:reply_opts) { opts.merge(in_reply_to_discussion_id: existing_note.discussion_id) }

      subject { described_class.new(project, user, reply_opts).execute }

      it 'creates a DiscussionNote in reply to existing note' do
        expect(subject).to be_a(DiscussionNote)
        expect(subject.discussion_id).to eq(existing_note.discussion_id)
      end

      it 'converts existing note to DiscussionNote' do
        expect do
          existing_note

          travel_to(Time.current + 1.minute) { subject }

          existing_note.reload
        end.to change { existing_note.type }.from(nil).to('DiscussionNote')
            .and change { existing_note.updated_at }
      end

      context 'failure in when_saved' do
        let(:service) { described_class.new(project, user, reply_opts) }

        it 'converts existing note to DiscussionNote' do
          expect do
            existing_note

            allow(service).to receive(:when_saved).and_raise(ActiveRecord::StatementInvalid)

            travel_to(Time.current + 1.minute) do
              service.execute
            rescue ActiveRecord::StatementInvalid
            end

            existing_note.reload
          end.to change { existing_note.type }.from(nil).to('DiscussionNote')
            .and change { existing_note.updated_at }
        end
      end

      it 'returns a DiscussionNote with its parent discussion refreshed correctly' do
        discussion_notes = subject.discussion.notes

        expect(discussion_notes.size).to eq(2)
        expect(discussion_notes.first).to be_a(DiscussionNote)
      end

      context 'discussion to reply cannot be found' do
        before do
          existing_note.delete
        end

        it 'returns an note with errors' do
          note = subject

          expect(note.errors).not_to be_empty
          expect(note.errors[:base]).to eq(['Discussion to reply to cannot be found'])
        end
      end
    end

    describe "usage counter" do
      let(:counter) { Gitlab::UsageDataCounters::NoteCounter }

      context 'snippet note' do
        let(:snippet) { create(:project_snippet, project: project) }
        let(:opts) { { note: 'reply', noteable_type: 'Snippet', noteable_id: snippet.id, project: project } }

        it 'increments usage counter' do
          expect do
            note = described_class.new(project, user, opts).execute

            expect(note).to be_valid
          end.to change { counter.read(:create, opts[:noteable_type]) }.by 1
        end

        it 'does not increment usage counter when creation fails' do
          expect do
            note = described_class.new(project, user, { note: '' }).execute

            expect(note).to be_invalid
          end.not_to change { counter.read(:create, opts[:noteable_type]) }
        end
      end

      context 'issue note' do
        let(:issue) { create(:issue, project: project) }
        let(:opts) { { note: 'reply', noteable_type: 'Issue', noteable_id: issue.id, project: project } }

        it 'does not increment usage counter' do
          expect do
            note = described_class.new(project, user, opts).execute

            expect(note).to be_valid
          end.not_to change { counter.read(:create, opts[:noteable_type]) }
        end
      end
    end
  end
end


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

module ProtectedTags
  class DestroyService < BaseService
    def execute(protected_tag)
      protected_tag.destroy
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ProtectedTags::DestroyService, feature_category: :compliance_management do
  let(:protected_tag) { create(:protected_tag) }
  let(:project) { protected_tag.project }
  let(:user) { project.first_owner }

  describe '#execute' do
    subject(:service) { described_class.new(project, user) }

    it 'destroy a protected tag' do
      service.execute(protected_tag)

      expect(protected_tag).to be_destroyed
    end
  end
end


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

module ProtectedTags
  class UpdateService < ::BaseService
    def execute(protected_tag)
      raise Gitlab::Access::AccessDeniedError unless can?(current_user, :admin_project, project)

      protected_tag.update(params)
      protected_tag
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ProtectedTags::UpdateService, feature_category: :compliance_management do
  let(:protected_tag) { create(:protected_tag) }
  let(:project) { protected_tag.project }
  let(:user) { project.first_owner }
  let(:params) { { name: new_name } }

  describe '#execute' do
    let(:new_name) { 'new protected tag name' }
    let(:result) { service.execute(protected_tag) }

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

    it 'updates a protected tag' do
      expect(result.reload.name).to eq(params[:name])
    end

    context 'when updating protected tag with a name that contains HTML tags' do
      let(:new_name) { 'foo<b>bar<\b>' }
      let(:result) { service.execute(protected_tag) }

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

      it 'updates a protected tag' do
        expect(result.reload.name).to eq(new_name)
      end
    end

    context 'without admin_project permissions' do
      let(:user) { create(:user) }

      it "raises error" do
        expect { service.execute(protected_tag) }.to raise_error(Gitlab::Access::AccessDeniedError)
      end
    end
  end
end


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

module ProtectedTags
  class CreateService < ::BaseService
    attr_reader :protected_tag

    def execute
      raise Gitlab::Access::AccessDeniedError unless can?(current_user, :admin_project, project)

      project.protected_tags.create(params)
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ProtectedTags::CreateService, feature_category: :compliance_management do
  let(:project) { create(:project) }
  let(:user) { project.first_owner }
  let(:params) do
    {
      name: name,
      create_access_levels_attributes: [{ access_level: Gitlab::Access::MAINTAINER }]
    }
  end

  describe '#execute' do
    let(:name) { 'tag' }

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

    it 'creates a new protected tag' do
      expect { service.execute }.to change(ProtectedTag, :count).by(1)
      expect(project.protected_tags.last.create_access_levels.map(&:access_level)).to eq([Gitlab::Access::MAINTAINER])
    end

    context 'protecting a tag with a name that contains HTML tags' do
      let(:name) { 'foo<b>bar<\b>' }

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

      it 'creates a new protected tag' do
        expect { service.execute }.to change(ProtectedTag, :count).by(1)
        expect(project.protected_tags.last.name).to eq(name)
      end
    end
  end
end


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

module Ml
  class CreateCandidateService
    def initialize(experiment, params = {})
      @experiment = experiment
      @name = params[:name]
      @user = params[:user]
      @start_time = params[:start_time]
      @model_version = params[:model_version]
    end

    def execute
      Ml::Candidate.create!(
        experiment: experiment,
        project: experiment.project,
        name: candidate_name,
        start_time: start_time || 0,
        user: user,
        model_version: model_version
      )
    end

    private

    def candidate_name
      name.presence || random_candidate_name
    end

    def random_candidate_name
      parts = Array.new(3).map { FFaker::Animal.common_name.downcase.delete(' ') } << rand(10000)
      parts.join('-').truncate(255)
    end

    attr_reader :name, :user, :experiment, :start_time, :model_version
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::CreateCandidateService, feature_category: :mlops do
  describe '#execute' do
    let_it_be(:model_version) { create(:ml_model_versions, candidate: nil) }
    let_it_be(:experiment) { create(:ml_experiments, project: model_version.project) }

    let(:params) { {} }

    subject(:candidate) { described_class.new(experiment, params).execute }

    context 'with default parameters' do
      it 'creates a candidate' do
        expect { candidate }.to change { experiment.candidates.count }.by(1)
      end

      it 'gives a fake name' do
        expect(candidate.name).to match(/[a-z]+-[a-z]+-[a-z]+-\d+/)
      end

      it 'sets the correct values', :aggregate_failures do
        expect(candidate.start_time).to eq(0)
        expect(candidate.experiment).to be(experiment)
        expect(candidate.project).to be(experiment.project)
        expect(candidate.user).to be_nil
      end
    end

    context 'when parameters are passed' do
      let(:params) do
        {
          start_time: 1234,
          name: 'candidate_name',
          model_version: model_version,
          user: experiment.user
        }
      end

      context 'with default parameters' do
        it 'creates a candidate' do
          expect { candidate }.to change { experiment.candidates.count }.by(1)
        end

        it 'sets the correct values', :aggregate_failures do
          expect(candidate.start_time).to eq(1234)
          expect(candidate.experiment).to be(experiment)
          expect(candidate.project).to be(experiment.project)
          expect(candidate.user).to be(experiment.user)
          expect(candidate.name).to eq('candidate_name')
          expect(candidate.model_version_id).to eq(model_version.id)
        end
      end
    end
  end
end


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

module Ml
  class CreateModelVersionService
    def initialize(model, params = {})
      @model = model
      @version = params[:version]
      @package = params[:package]
      @description = params[:description]
      @user = params[:user]
    end

    def execute
      ApplicationRecord.transaction do
        @version ||= Ml::IncrementVersionService.new(@model.latest_version.try(:version)).execute

        package = @package || find_or_create_package(@model.name, @version)

        model_version = Ml::ModelVersion.create!(model: @model, project: @model.project, version: @version,
          package: package, description: @description)

        model_version.candidate = ::Ml::CreateCandidateService.new(
          @model.default_experiment,
          { model_version: model_version }
        ).execute

        model_version
      end
    end

    private

    def find_or_create_package(model_name, model_version)
      package_params = {
        name: model_name,
        version: model_version
      }

      ::Packages::MlModel::FindOrCreatePackageService
        .new(@model.project, @user, package_params)
        .execute
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::CreateModelVersionService, feature_category: :mlops do
  let(:model) { create(:ml_models) }
  let(:params) { {} }

  subject(:service) { described_class.new(model, params).execute }

  context 'when no versions exist' do
    it 'creates a model version', :aggregate_failures do
      expect { service }.to change { Ml::ModelVersion.count }.by(1).and change { Ml::Candidate.count }.by(1)
      expect(model.reload.latest_version.version).to eq('1.0.0')
    end
  end

  context 'when a version exist' do
    before do
      create(:ml_model_versions, model: model, version: '3.0.0')
    end

    it 'creates another model version and increments the version number', :aggregate_failures do
      expect { service }.to change { Ml::ModelVersion.count }.by(1).and change { Ml::Candidate.count }.by(1)
      expect(model.reload.latest_version.version).to eq('4.0.0')
    end
  end

  context 'when a version is created' do
    it 'creates a package' do
      expect { service }.to change { Ml::ModelVersion.count }.by(1).and change {
                                                                          Packages::MlModel::Package.count
                                                                        }.by(1)
      expect(model.reload.latest_version.package.name).to eq(model.name)
      expect(model.latest_version.package.version).to eq(model.latest_version.version)
    end
  end

  context 'when a version is created and the package already exists' do
    it 'does not creates a package' do
      next_version = Ml::IncrementVersionService.new(model.latest_version.try(:version)).execute
      create(:ml_model_package, name: model.name, version: next_version, project: model.project)

      expect { service }.to change { Ml::ModelVersion.count }.by(1).and not_change {
                                                                          Packages::MlModel::Package.count
                                                                        }
      expect(model.reload.latest_version.package.name).to eq(model.name)
      expect(model.latest_version.package.version).to eq(model.latest_version.version)
    end
  end

  context 'when a version is created and an existing package supplied' do
    it 'does not creates a package' do
      next_version = Ml::IncrementVersionService.new(model.latest_version.try(:version)).execute
      package = create(:ml_model_package, name: model.name, version: next_version, project: model.project)
      service = described_class.new(model, { package: package })

      expect { service.execute }.to change { Ml::ModelVersion.count }.by(1).and not_change {
                                                                                Packages::MlModel::Package.count
                                                                                }
      expect(model.reload.latest_version.package.name).to eq(model.name)
      expect(model.latest_version.package.version).to eq(model.latest_version.version)
    end
  end
end


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

module Ml
  class FindOrCreateExperimentService
    def initialize(project, experiment_name, user = nil)
      @project = project
      @name = experiment_name
      @user = user
    end

    def execute
      Ml::Experiment.find_or_create(project, name, user)
    end

    private

    attr_reader :project, :name, :user
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::FindOrCreateExperimentService, feature_category: :mlops do
  let_it_be(:project) { create(:project) }
  let_it_be(:user) { project.first_owner }
  let_it_be(:existing_experiment) { create(:ml_experiments, project: project, user: user) }

  let(:name) { 'new_experiment' }

  subject(:new_experiment) { described_class.new(project, name, user).execute }

  describe '#execute' do
    it 'creates an experiment using Ml::Experiment.find_or_create', :aggregate_failures do
      expect(Ml::Experiment).to receive(:find_or_create).and_call_original

      expect(new_experiment.name).to eq('new_experiment')
      expect(new_experiment.project).to eq(project)
      expect(new_experiment.user).to eq(user)
    end

    context 'when experiment already exists' do
      let(:name) { existing_experiment.name }

      it 'fetches existing experiment', :aggregate_failures do
        expect { new_experiment }.not_to change { Ml::Experiment.count }

        expect(new_experiment).to eq(existing_experiment)
      end
    end
  end
end


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

module Ml
  class DestroyModelService
    def initialize(model, user)
      @model = model
      @user = user
    end

    def execute
      return unless @model.destroy

      ::Packages::MarkPackagesForDestructionService.new(
        packages: @model.all_packages,
        current_user: @user
      ).execute
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::DestroyModelService, feature_category: :mlops do
  let_it_be(:user) { create(:user) }
  let_it_be(:model) { create(:ml_models, :with_latest_version_and_package) }
  let(:service) { described_class.new(model, user) }

  describe '#execute' do
    context 'when model name does not exist in the project' do
      it 'returns nil' do
        allow(model).to receive(:destroy).and_return(false)
        expect(service.execute).to be nil
      end
    end

    context 'when a model exists' do
      it 'destroys the model' do
        expect(Packages::MarkPackagesForDestructionService).to receive(:new).with(packages: model.all_packages,
          current_user: user).and_return(instance_double('Packages::MarkPackagesForDestructionService').tap do |service|
                                           expect(service).to receive(:execute)
                                         end)
        expect { service.execute }.to change { Ml::Model.count }.by(-1).and change { Ml::ModelVersion.count }.by(-1)
      end
    end
  end
end


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

module Ml
  class CreateModelService
    def initialize(project, name, user = nil, description = nil, metadata = [])
      @project = project
      @name = name
      @description = description
      @metadata = metadata
      @user = user
    end

    def execute
      ApplicationRecord.transaction do
        model = Ml::Model.create!(
          project: @project,
          name: @name,
          user: (@user.is_a?(User) ? @user : nil),
          description: @description,
          default_experiment: default_experiment
        )

        add_metadata(model, @metadata)

        model
      end
    end

    private

    def default_experiment
      @default_experiment ||= Ml::FindOrCreateExperimentService.new(@project, @name).execute
    end

    def add_metadata(model, metadata_key_value)
      return unless model.present? && metadata_key_value.present?

      entities = metadata_key_value.map do |d|
        {
          model_id: model.id,
          name: d[:key],
          value: d[:value]
        }
      end

      entities.each do |entry|
        ::Ml::ModelMetadata.create!(entry)
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::CreateModelService, feature_category: :mlops do
  let_it_be(:user) { create(:user) }
  let_it_be(:existing_model) { create(:ml_models) }
  let_it_be(:another_project) { create(:project) }
  let_it_be(:description) { 'description' }
  let_it_be(:metadata) { [] }

  subject(:create_model) { described_class.new(project, name, user, description, metadata).execute }

  describe '#execute' do
    context 'when model name does not exist in the project' do
      let(:name) { 'new_model' }
      let(:project) { existing_model.project }

      it 'creates a model', :aggregate_failures do
        expect { create_model }.to change { Ml::Model.count }.by(1)

        expect(create_model.name).to eq(name)
      end
    end

    context 'when model name exists but project is different' do
      let(:name) { existing_model.name }
      let(:project) { another_project }

      it 'creates a model', :aggregate_failures do
        expect { create_model }.to change { Ml::Model.count }.by(1)

        expect(create_model.name).to eq(name)
      end
    end

    context 'when model with name exists' do
      let(:name) { existing_model.name }
      let(:project) { existing_model.project }

      it 'raises an error', :aggregate_failures do
        expect { create_model }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end

    context 'when metadata are supplied, add them as metadata' do
      let(:name) { 'new_model' }
      let(:project) { existing_model.project }
      let(:metadata) { [{ key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2' }] }

      it 'creates metadata records', :aggregate_failures do
        expect { create_model }.to change { Ml::Model.count }.by(1)

        expect(create_model.name).to eq(name)
        expect(create_model.metadata.count).to be 2
      end
    end

    # TODO: Ensure consisted error responses https://gitlab.com/gitlab-org/gitlab/-/issues/429731
    context 'for metadata with duplicate keys, it does not create duplicate records' do
      let(:name) { 'new_model' }
      let(:project) { existing_model.project }
      let(:metadata) { [{ key: 'key1', value: 'value1' }, { key: 'key1', value: 'value2' }] }

      it 'raises an error', :aggregate_failures do
        expect { create_model }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end

    # TODO: Ensure consisted error responses https://gitlab.com/gitlab-org/gitlab/-/issues/429731
    context 'for metadata with invalid keys, it does not create invalid records' do
      let(:name) { 'new_model' }
      let(:project) { existing_model.project }
      let(:metadata) { [{ key: 'key1', value: 'value1' }, { key: '', value: 'value2' }] }

      it 'raises an error', :aggregate_failures do
        expect { create_model }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end
  end
end


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

module Ml
  class UpdateModelService
    def initialize(model, description)
      @model = model
      @description = description
    end

    def execute
      @model.update!(description: @description)

      @model
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::UpdateModelService, feature_category: :mlops do
  let_it_be(:model) { create(:ml_models) }
  let_it_be(:description) { 'updated model description' }
  let(:service) { described_class.new(model, description) }

  describe '#execute' do
    context 'when supplied with a non-model object' do
      let(:model) { nil }

      it 'returns nil' do
        expect { service.execute }.to raise_error(NoMethodError)
      end
    end

    context 'with an existing model' do
      it 'updates the description' do
        updated = service.execute
        expect(updated.class).to be(Ml::Model)
        expect(updated.description).to eq(description)
      end
    end
  end
end


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

module Ml
  INITIAL_VERSION = '1.0.0'
  ALLOWED_INCREMENT_TYPES = [:patch, :minor, :major].freeze

  class IncrementVersionService
    def initialize(version, increment_type = nil)
      @version = version
      @increment_type = increment_type || :major
      @parsed_version = Packages::SemVer.parse(@version.to_s)

      raise "Version must be in a valid SemVer format" unless @parsed_version || @version.nil?

      return if ALLOWED_INCREMENT_TYPES.include?(@increment_type)

      raise "Increment type must be one of :patch, :minor, or :major"
    end

    def execute
      return INITIAL_VERSION if @version.nil?

      case @increment_type
      when :patch
        @parsed_version.patch += 1
      when :minor
        @parsed_version.minor += 1
      when :major
        @parsed_version.major += 1
      end

      @parsed_version.to_s
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::IncrementVersionService, feature_category: :mlops do
  describe '#execute' do
    let(:increment_type) { nil }
    let(:finder) { described_class.new(version, increment_type) }

    context 'when given an invalid version format' do
      let(:version) { 'foo' }

      it 'raises an error' do
        expect { finder.execute }.to raise_error(RuntimeError, "Version must be in a valid SemVer format")
      end
    end

    context 'when given a non-semver version format' do
      let(:version) { 1 }

      it 'raises an error' do
        expect { finder.execute }.to raise_error(RuntimeError, "Version must be in a valid SemVer format")
      end
    end

    context 'when given an unsupported increment type' do
      let(:version) { '1.2.3' }
      let(:increment_type) { 'foo' }

      it 'raises an error' do
        expect do
          finder.execute
        end.to raise_error(RuntimeError, "Increment type must be one of :patch, :minor, or :major")
      end
    end

    context 'when valid inputs are provided' do
      using RSpec::Parameterized::TableSyntax

      where(:version, :increment_type, :result) do
        nil | nil | '1.0.0'
        '0.0.1' | nil | '1.0.1'
        '1.0.0' | nil | '2.0.0'
        '1.0.0' | :major | '2.0.0'
        '1.0.0' | :minor | '1.1.0'
        '1.0.0' | :patch | '1.0.1'
      end

      with_them do
        subject { finder.execute }

        it { is_expected.to eq(result) }
      end
    end
  end
end


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

module Ml
  class FindOrCreateModelService
    def initialize(project, name, user = nil, description = nil, metadata = [])
      @project = project
      @name = name
      @description = description
      @metadata = metadata
      @user = user
    end

    def execute
      FindModelService.new(@project, @name).execute ||
        CreateModelService.new(@project, @name, @user, @description, @metadata).execute
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::FindOrCreateModelService, feature_category: :mlops do
  let_it_be(:user) { create(:user) }
  let_it_be(:existing_model) { create(:ml_models) }
  let_it_be(:another_project) { create(:project) }
  let_it_be(:description) { 'description' }
  let_it_be(:metadata) { [] }

  subject(:create_model) { described_class.new(project, name, user, description, metadata).execute }

  describe '#execute' do
    context 'when model name does not exist in the project' do
      let(:name) { 'new_model' }
      let(:project) { existing_model.project }

      it 'creates a model', :aggregate_failures do
        expect { create_model }.to change { Ml::Model.count }.by(1)

        expect(create_model.name).to eq(name)
      end
    end

    context 'when model name exists but project is different' do
      let(:name) { existing_model.name }
      let(:project) { another_project }

      it 'creates a model', :aggregate_failures do
        expect { create_model }.to change { Ml::Model.count }.by(1)

        expect(create_model.name).to eq(name)
      end
    end

    context 'when model with name exists' do
      let(:name) { existing_model.name }
      let(:project) { existing_model.project }

      it 'fetches existing model', :aggregate_failures do
        expect { create_model }.to change { Ml::Model.count }.by(0)

        expect(create_model).to eq(existing_model)
      end
    end
  end
end


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

module Ml
  class FindOrCreateModelVersionService
    def initialize(project, params = {})
      @project = project
      @name = params[:model_name]
      @version = params[:version]
      @package = params[:package]
      @description = params[:description]
    end

    def execute
      model = Ml::FindOrCreateModelService.new(@project, @name).execute

      model_version = Ml::ModelVersion.find_or_create!(model, @version, @package, @description)

      unless model_version.candidate
        model_version.candidate = ::Ml::CreateCandidateService.new(
          model.default_experiment,
          { model_version: model_version }
        ).execute
      end

      model_version
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::FindOrCreateModelVersionService, feature_category: :mlops do
  let_it_be(:existing_version) { create(:ml_model_versions) }
  let_it_be(:another_project) { create(:project) }
  let_it_be(:user) { create(:user) }

  let(:package) { nil }
  let(:description) { nil }

  let(:params) do
    {
      model_name: name,
      version: version,
      package: package,
      description: description,
      user: user
    }
  end

  subject(:model_version) { described_class.new(project, params).execute }

  describe '#execute' do
    context 'when model version exists' do
      let(:name) { existing_version.name }
      let(:version) { existing_version.version }
      let(:project) { existing_version.project }

      it 'returns existing model version', :aggregate_failures do
        expect { model_version }.to change { Ml::ModelVersion.count }.by(0)
        expect { model_version }.to change { Ml::Candidate.count }.by(0)
        expect(model_version).to eq(existing_version)
      end
    end

    context 'when model version does not exist' do
      let(:project) { existing_version.project }
      let(:name) { 'a_new_model' }
      let(:version) { '2.0.0' }
      let(:description) { 'A model version' }

      let(:package) { create(:ml_model_package, project: project, name: name, version: version) }

      it 'creates a new model version', :aggregate_failures do
        expect { model_version }.to change { Ml::ModelVersion.count }.by(1).and change { Ml::Candidate.count }.by(1)

        expect(model_version.name).to eq(name)
        expect(model_version.version).to eq(version)
        expect(model_version.package).to eq(package)
        expect(model_version.candidate.model_version_id).to eq(model_version.id)
        expect(model_version.description).to eq(description)
      end
    end
  end
end


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

module Ml
  class FindModelService
    def initialize(project, name)
      @project = project
      @name = name
    end

    def execute
      Ml::Model.by_project_id_and_name(@project.id, @name)
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::FindModelService, feature_category: :mlops do
  let_it_be(:user) { create(:user) }
  let_it_be(:existing_model) { create(:ml_models) }
  let(:finder) { described_class.new(project, name) }

  describe '#execute' do
    context 'when model name does not exist in the project' do
      let(:name) { 'new_model' }
      let(:project) { existing_model.project }

      it 'reutrns nil' do
        expect(finder.execute).to be nil
      end
    end

    context 'when model with name exists' do
      let(:name) { existing_model.name }
      let(:project) { existing_model.project }

      it 'returns the existing model' do
        expect(finder.execute).to eq(existing_model)
      end
    end
  end
end


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

module Ml
  module ExperimentTracking
    class CandidateRepository
      attr_accessor :project, :user, :experiment, :candidate

      def initialize(project, user = nil)
        @project = project
        @user = user
      end

      def by_eid(eid)
        ::Ml::Candidate.with_project_id_and_eid(project.id, eid)
      end

      def create!(experiment, start_time, tags = nil, name = nil)
        create_params = {
          start_time: start_time,
          user: user,
          name: candidate_name(name, tags)
        }

        candidate = Ml::CreateCandidateService.new(experiment, create_params).execute

        add_tags(candidate, tags)

        candidate
      end

      def update(candidate, status, end_time)
        candidate.status = status.downcase if status
        candidate.end_time = end_time if end_time

        candidate.save
      end

      def add_metric!(candidate, name, value, tracked_at, step)
        candidate.metrics.create!(
          name: name,
          value: value,
          tracked_at: tracked_at,
          step: step
        )
      end

      def add_param!(candidate, name, value)
        candidate.params.create!(name: name, value: value)
      end

      def add_tag!(candidate, name, value)
        handle_gitlab_tags(candidate, [{ key: name, value: value }])

        candidate.metadata.create!(name: name, value: value)
      end

      def add_metrics(candidate, metric_definitions)
        extra_keys = { tracked_at: :timestamp, step: :step }
        insert_many(candidate, metric_definitions, ::Ml::CandidateMetric, extra_keys)
      end

      def add_params(candidate, param_definitions)
        insert_many(candidate, param_definitions, ::Ml::CandidateParam)
      end

      def add_tags(candidate, tag_definitions)
        return unless tag_definitions.present?

        handle_gitlab_tags(candidate, tag_definitions)

        insert_many(candidate, tag_definitions, ::Ml::CandidateMetadata)
      end

      private

      def handle_gitlab_tags(candidate, tag_definitions)
        return unless tag_definitions.any? { |t| t[:key]&.starts_with?('gitlab.') }

        Ml::ExperimentTracking::HandleCandidateGitlabMetadataService
          .new(candidate, tag_definitions)
          .execute
      end

      def timestamps
        current_time = Time.zone.now

        { created_at: current_time, updated_at: current_time }
      end

      def insert_many(candidate, definitions, entity_class, extra_keys = {})
        return unless candidate.present? && definitions.present?

        entities = definitions.map do |d|
          {
            candidate_id: candidate.id,
            name: d[:key],
            value: d[:value],
            **extra_keys.transform_values { |old_key| d[old_key] },
            **timestamps
          }
        end

        entity_class.insert_all(entities, returning: false) unless entities.empty?
      end

      def candidate_name(name, tags)
        name.presence || candidate_name_from_tags(tags)
      end

      def candidate_name_from_tags(tags)
        tags&.detect { |t| t[:key] == 'mlflow.runName' }&.dig(:value)
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::ExperimentTracking::CandidateRepository, feature_category: :activation do
  let_it_be(:project) { create(:project) }
  let_it_be(:user) { create(:user) }
  let_it_be(:experiment) { create(:ml_experiments, user: user, project: project) }
  let_it_be(:candidate) { create(:ml_candidates, user: user, experiment: experiment, project: project) }

  let(:repository) { described_class.new(project, user) }

  describe '#by_eid' do
    let(:eid) { candidate.eid }

    subject { repository.by_eid(eid) }

    it { is_expected.to eq(candidate) }

    context 'when iid does not exist' do
      let(:eid) { non_existing_record_iid.to_s }

      it { is_expected.to be_nil }
    end

    context 'when iid belongs to a different project' do
      let(:repository) { described_class.new(create(:project), user) }

      it { is_expected.to be_nil }
    end
  end

  describe '#create!' do
    let(:tags) { [{ key: 'hello', value: 'world' }] }
    let(:name) { 'some_candidate' }

    subject { repository.create!(experiment, 1234, tags, name) }

    it 'creates the candidate' do
      expect(subject.start_time).to eq(1234)
      expect(subject.eid).not_to be_nil
      expect(subject.end_time).to be_nil
      expect(subject.name).to eq('some_candidate')
    end

    it 'creates with tag' do
      expect(subject.metadata.length).to eq(1)
    end

    context 'when name is passed as tag' do
      let(:tags) { [{ key: 'mlflow.runName', value: 'blah' }] }

      it 'ignores if name is not nil' do
        expect(subject.name).to eq('some_candidate')
      end

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

        it 'sets the mlflow.runName as candidate name' do
          expect(subject.name).to eq('blah')
        end
      end

      context 'when name is nil and no mlflow.runName is not present' do
        let(:tags) { nil }
        let(:name) { nil }

        it 'gives the candidate a random name' do
          expect(subject.name).to match(/[a-z]+-[a-z]+-[a-z]+-\d+/)
        end
      end
    end
  end

  describe '#update' do
    let(:end_time) { 123456 }
    let(:status) { 'running' }

    subject { repository.update(candidate, status, end_time) }

    it { is_expected.to be_truthy }

    context 'when end_time is missing ' do
      let(:end_time) { nil }

      it { is_expected.to be_truthy }
    end

    context 'when status is wrong' do
      let(:status) { 's' }

      it 'fails assigning the value' do
        expect { subject }.to raise_error(ArgumentError)
      end
    end

    context 'when status is missing' do
      let(:status) { nil }

      it { is_expected.to be_truthy }
    end
  end

  describe '#add_metric!' do
    let(:props) { { name: 'abc', value: 1234, tracked: 12345678, step: 0 } }
    let(:metrics_before) { candidate.metrics.size }

    before do
      metrics_before
    end

    subject { repository.add_metric!(candidate, props[:name], props[:value], props[:tracked], props[:step]) }

    it 'adds a new metric' do
      expect { subject }.to change { candidate.metrics.size }.by(1)
    end

    context 'when name missing' do
      let(:props) { { value: 1234, tracked: 12345678, step: 0 } }

      it 'does not add metric' do
        expect { subject }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end
  end

  describe '#add_param!' do
    let(:props) { { name: 'abc', value: 'def' } }

    subject { repository.add_param!(candidate, props[:name], props[:value]) }

    it 'adds a new param' do
      expect { subject }.to change { candidate.params.size }.by(1)
    end

    context 'when name missing' do
      let(:props) { { value: 1234 } }

      it 'throws RecordInvalid' do
        expect { subject }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end

    context 'when param was already added' do
      it 'throws RecordInvalid' do
        repository.add_param!(candidate, 'new', props[:value])

        expect { repository.add_param!(candidate, 'new', props[:value]) }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end
  end

  describe '#add_tag!' do
    let(:props) { { name: 'abc', value: 'def' } }

    subject { repository.add_tag!(candidate, props[:name], props[:value]) }

    it 'adds a new tag' do
      expect { subject }.to change { candidate.reload.metadata.size }.by(1)
    end

    context 'when name missing' do
      let(:props) { { value: 1234 } }

      it 'throws RecordInvalid' do
        expect { subject }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end

    context 'when tag was already added' do
      it 'throws RecordInvalid' do
        repository.add_tag!(candidate, 'new', props[:value])

        expect { repository.add_tag!(candidate, 'new', props[:value]) }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end

    context 'when tag starts with gitlab.' do
      it 'calls HandleCandidateGitlabMetadataService' do
        expect(Ml::ExperimentTracking::HandleCandidateGitlabMetadataService).to receive(:new).and_call_original

        repository.add_tag!(candidate, 'gitlab.CI_USER_ID', user.id)
      end
    end
  end

  describe "#add_params" do
    let(:params) do
      [{ key: 'model_class', value: 'LogisticRegression' }, { 'key': 'pythonEnv', value: '3.10' }]
    end

    subject { repository.add_params(candidate, params) }

    it 'adds the parameters' do
      expect { subject }.to change { candidate.reload.params.size }.by(2)
    end

    context 'if parameter misses key' do
      let(:params) do
        [{ value: 'LogisticRegression' }]
      end

      it 'does not throw and does not add' do
        expect { subject }.to raise_error(ActiveRecord::ActiveRecordError)
      end
    end

    context 'if parameter misses value' do
      let(:params) do
        [{ key: 'pythonEnv2' }]
      end

      it 'does not throw and does not add' do
        expect { subject }.to raise_error(ActiveRecord::ActiveRecordError)
      end
    end

    context 'if parameter repeated do' do
      let(:params) do
        [
          { 'key': 'pythonEnv0', value: '2.7' },
          { 'key': 'pythonEnv1', value: '3.9' },
          { 'key': 'pythonEnv1', value: '3.10' }
        ]
      end

      before do
        repository.add_param!(candidate, 'pythonEnv0', '0')
      end

      it 'does not throw and adds only the first of each kind' do
        expect { subject }.to change { candidate.reload.params.size }.by(1)
      end
    end
  end

  describe "#add_metrics" do
    let(:metrics) do
      [
        { key: 'mae', value: 2.5, timestamp: 1552550804 },
        { key: 'rmse', value: 2.7, timestamp: 1552550804 }
      ]
    end

    subject { repository.add_metrics(candidate, metrics) }

    it 'adds the metrics' do
      expect { subject }.to change { candidate.reload.metrics.size }.by(2)
    end

    context 'when metrics have repeated keys' do
      let(:metrics) do
        [
          { key: 'mae', value: 2.5, timestamp: 1552550804 },
          { key: 'rmse', value: 2.7, timestamp: 1552550804 },
          { key: 'mae', value: 2.7, timestamp: 1552550805 }
        ]
      end

      it 'adds all of them' do
        expect { subject }.to change { candidate.reload.metrics.size }.by(3)
      end
    end
  end

  describe "#add_tags" do
    let(:tags) do
      [{ key: 'gitlab.tag1', value: 'hello' }, { 'key': 'gitlab.tag2', value: 'world' }]
    end

    subject { repository.add_tags(candidate, tags) }

    it 'adds the tags' do
      expect { subject }.to change { candidate.reload.metadata.size }.by(2)
    end

    context 'if tags misses key' do
      let(:tags) { [{ value: 'hello' }] }

      it 'does throw and does not add' do
        expect { subject }.to raise_error(ActiveRecord::ActiveRecordError)
      end
    end

    context 'if tag misses value' do
      let(:tags) { [{ key: 'gitlab.tag1' }] }

      it 'does throw and does not add' do
        expect { subject }.to raise_error(ActiveRecord::ActiveRecordError)
      end
    end

    context 'if tag repeated' do
      let(:params) do
        [
          { 'key': 'gitlab.tag1', value: 'hello' },
          { 'key': 'gitlab.tag2', value: 'world' },
          { 'key': 'gitlab.tag1', value: 'gitlab' }
        ]
      end

      before do
        repository.add_tag!(candidate, 'gitlab.tag2', '0')
      end

      it 'does not throw and adds only the first of each kind' do
        expect { subject }.to change { candidate.reload.metadata.size }.by(1)
      end
    end

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

      it 'does not handle gitlab tags' do
        expect(repository).not_to receive(:handle_gitlab_tags)

        subject
      end
    end
  end
end


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

module Ml
  module ExperimentTracking
    class HandleCandidateGitlabMetadataService
      def initialize(candidate, metadata)
        @candidate = candidate
        @metadata = metadata.index_by { |m| m[:key] }
      end

      def execute
        handle_build_metadata(@metadata['gitlab.CI_JOB_ID'])

        @candidate.save
      end

      private

      def handle_build_metadata(build_metadata)
        return unless build_metadata

        build = Ci::Build.find_by_id(build_metadata[:value])

        raise ArgumentError, 'gitlab.CI_JOB_ID must refer to an existing build' unless build

        @candidate.ci_build = build
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::ExperimentTracking::HandleCandidateGitlabMetadataService, feature_category: :activation do
  let_it_be(:project) { create(:project, :repository) }
  let_it_be(:user) { project.owner }
  let_it_be(:pipeline) { create(:ci_pipeline, project: project) }
  let_it_be(:build) { create(:ci_build, :success, pipeline: pipeline) }

  let(:metadata) { [] }
  let(:candidate) { create(:ml_candidates, project: project, user: user) }

  describe 'execute' do
    subject { described_class.new(candidate, metadata).execute }

    context 'when metadata includes gitlab.CI_JOB_ID', 'and gitlab.CI_JOB_ID is valid' do
      let(:metadata) do
        [
          { key: 'gitlab.CI_JOB_ID', value: build.id.to_s }
        ]
      end

      it 'updates candidate correctly', :aggregate_failures do
        subject

        expect(candidate.ci_build).to eq(build)
      end
    end

    context 'when metadata includes gitlab.CI_JOB_ID and gitlab.CI_JOB_ID is invalid' do
      let(:metadata) { [{ key: 'gitlab.CI_JOB_ID', value: non_existing_record_id.to_s }] }

      it 'raises error' do
        expect { subject }
          .to raise_error(ArgumentError, 'gitlab.CI_JOB_ID must refer to an existing build')
      end
    end
  end
end


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

module Ml
  module ExperimentTracking
    class ExperimentRepository
      attr_accessor :project, :user

      def initialize(project, user = nil)
        @project = project
        @user = user
      end

      def by_iid_or_name(iid: nil, name: nil)
        return ::Ml::Experiment.by_project_id_and_iid(project.id, iid) if iid

        ::Ml::Experiment.by_project_id_and_name(project.id, name) if name
      end

      def all
        ::Ml::Experiment.by_project_id(project.id)
      end

      def create!(name, tags = nil)
        experiment = ::Ml::Experiment.create!(name: name,
                                              user: user,
                                              project: project)

        add_tags(experiment, tags)

        experiment
      end

      def add_tag!(experiment, key, value)
        return unless experiment.present?

        experiment.metadata.create!(name: key, value: value)
      end

      private

      def timestamps
        current_time = Time.zone.now

        { created_at: current_time, updated_at: current_time }
      end

      def add_tags(experiment, tag_definitions)
        return unless experiment.present? && tag_definitions.present?

        entities = tag_definitions.map do |d|
          {
            experiment_id: experiment.id,
            name: d[:key],
            value: d[:value],
            **timestamps
          }
        end

        ::Ml::ExperimentMetadata.insert_all(entities, returning: false) unless entities.empty?
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe ::Ml::ExperimentTracking::ExperimentRepository, feature_category: :activation do
  let_it_be(:project) { create(:project) }
  let_it_be(:user) { create(:user) }
  let_it_be(:experiment) { create(:ml_experiments, user: user, project: project) }
  let_it_be(:experiment2) { create(:ml_experiments, user: user, project: project) }
  let_it_be(:experiment3) { create(:ml_experiments, user: user, project: project) }
  let_it_be(:experiment4) { create(:ml_experiments, user: user) }

  let(:repository) { described_class.new(project, user) }

  describe '#by_iid_or_name' do
    let(:iid) { experiment.iid }
    let(:name) { nil }

    subject { repository.by_iid_or_name(iid: iid, name: name) }

    context 'when iid passed' do
      it('fetches the experiment') { is_expected.to eq(experiment) }

      context 'and name passed' do
        let(:name) { experiment2.name }

        it('ignores the name') { is_expected.to eq(experiment) }
      end

      context 'and does not exist' do
        let(:iid) { non_existing_record_iid }

        it { is_expected.to eq(nil) }
      end
    end

    context 'when iid is not passed', 'and name is passed' do
      let(:iid) { nil }

      context 'when name exists' do
        let(:name) { experiment2.name }

        it('fetches the experiment') { is_expected.to eq(experiment2) }
      end

      context 'when name does not exist' do
        let(:name) { non_existing_record_iid }

        it { is_expected.to eq(nil) }
      end
    end
  end

  describe '#all' do
    it 'fetches experiments for project' do
      expect(repository.all).to match_array([experiment, experiment2, experiment3])
    end
  end

  describe '#create!' do
    let(:name) { 'hello' }
    let(:tags) { nil }

    subject { repository.create!(name, tags) }

    it 'creates the experiment' do
      expect { subject }.to change { repository.all.size }.by(1)
    end

    context 'when name exists' do
      let(:name) { experiment.name }

      it 'throws error' do
        expect { subject }.to raise_error(ActiveRecord::ActiveRecordError)
      end
    end

    context 'when has tags' do
      let(:tags) { [{ key: 'hello', value: 'world' }] }

      it 'creates the experiment with tag' do
        expect(subject.metadata.length).to eq(1)
      end
    end

    context 'when name is missing' do
      let(:name) { nil }

      it 'throws error' do
        expect { subject }.to raise_error(ActiveRecord::ActiveRecordError)
      end
    end
  end

  describe '#add_tag!' do
    let(:props) { { name: 'abc', value: 'def' } }

    subject { repository.add_tag!(experiment, props[:name], props[:value]) }

    it 'adds a new tag' do
      expect { subject }.to change { experiment.reload.metadata.size }.by(1)
    end

    context 'when name missing' do
      let(:props) { { value: 1234 } }

      it 'throws RecordInvalid' do
        expect { subject }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end

    context 'when tag was already added' do
      it 'throws RecordInvalid' do
        repository.add_tag!(experiment, 'new', props[:value])

        expect { repository.add_tag!(experiment, 'new', props[:value]) }.to raise_error(ActiveRecord::RecordInvalid)
      end
    end
  end
end


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

module Ml
  module ModelVersions
    class UpdateModelVersionService
      def initialize(project, name, version, description)
        @project = project
        @name = name
        @version = version
        @description = description
      end

      def execute
        model_version = Ml::ModelVersion
                          .by_project_id_name_and_version(@project.id, @name, @version)

        return ServiceResponse.error(message: 'Model not found') unless model_version.present?

        result = model_version.update(description: @description)

        return ServiceResponse.error(message: 'Model update failed') unless result

        ServiceResponse.success(payload: model_version)
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Ml::ModelVersions::UpdateModelVersionService, feature_category: :mlops do
  let_it_be(:existing_version) { create(:ml_model_versions) }

  let(:project) { existing_version.project }
  let(:name) { existing_version.name }
  let(:version) { existing_version.version }
  let(:description) { 'A model version description' }

  subject(:execute_service) { described_class.new(project, name, version, description).execute }

  describe '#execute' do
    context 'when model version exists' do
      it { is_expected.to be_success }

      it 'updates the model version description' do
        execute_service

        expect(execute_service.payload.description).to eq(description)
      end
    end

    context 'when description is invalid' do
      let(:description) { 'a' * 501 }

      it { is_expected.to be_error }
    end

    context 'when model does not exist' do
      let(:name) { 'a_new_model' }

      it { is_expected.to be_error }
    end

    context 'when model version does not exist' do
      let(:name) { '2.0.0' }

      it { is_expected.to be_error }
    end
  end
end


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

module Ml
  module ModelVersions
    class GetModelVersionService
      def initialize(project, name, version)
        @project = project
        @name = name
        @version = version
      end

      def execute
        Ml::ModelVersion.by_project_id_name_and_version(
          @project.id,
          @name,
          @version
        )
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Ml::ModelVersions::GetModelVersionService, feature_category: :mlops do
  let_it_be(:existing_version) { create(:ml_model_versions) }
  let_it_be(:another_project) { create(:project) }

  subject(:model_version) { described_class.new(project, name, version).execute }

  describe '#execute' do
    context 'when model version exists' do
      let(:name) { existing_version.name }
      let(:version) { existing_version.version }
      let(:project) { existing_version.project }

      it { is_expected.to eq(existing_version) }
    end

    context 'when model version does not exist' do
      let(:project) { existing_version.project }
      let(:name) { 'a_new_model' }
      let(:version) { '2.0.0' }

      it { is_expected.to be_nil }
    end
  end
end


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

module Ml
  module ModelVersions
    class DeleteService
      def initialize(project, name, version, user)
        @project = project
        @name = name
        @version = version
        @user = user
      end

      def execute
        model_version = Ml::ModelVersion
                          .by_project_id_name_and_version(@project.id, @name, @version)
        return ServiceResponse.error(message: 'Model not found') unless model_version

        if model_version.package.present?
          result = ::Packages::MarkPackageForDestructionService
                     .new(container: model_version.package, current_user: @user)
                     .execute

          return ServiceResponse.error(message: result.message) unless result.success?
        end

        return ServiceResponse.error(message: 'Could not destroy the model version') unless model_version.destroy

        ServiceResponse.success
      end
    end
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Ml::ModelVersions::DeleteService, feature_category: :mlops do
  let_it_be(:valid_model_version) do
    create(:ml_model_versions, :with_package)
  end

  let(:project) { valid_model_version.project }
  let(:user) { valid_model_version.project.owner }
  let(:name) { valid_model_version.name }
  let(:version) { valid_model_version.version }

  subject(:execute_service) { described_class.new(project, name, version, user).execute }

  describe '#execute' do
    context 'when model version exists' do
      it 'deletes the model version', :aggregate_failures do
        expect(execute_service).to be_success
        expect(Ml::ModelVersion.find_by(id: valid_model_version.id)).to be_nil
      end
    end

    context 'when model version does not exist' do
      let(:version) { 'wrong-version' }

      it { is_expected.to be_error.and have_attributes(message: 'Model not found') }
    end

    context 'when model version has no package' do
      before do
        valid_model_version.update!(package: nil)
      end

      it 'does not trigger destroy package service', :aggregate_failures do
        expect(Packages::MarkPackageForDestructionService).not_to receive(:new)
        expect(execute_service).to be_success
      end
    end

    context 'when package cannot be marked for destruction' do
      before do
        allow_next_instance_of(Packages::MarkPackageForDestructionService) do |service|
          allow(service).to receive(:execute).and_return(ServiceResponse.error(message: 'error'))
        end
      end

      it 'does not delete the model version', :aggregate_failures do
        is_expected.to be_error.and have_attributes(message: 'error')
        expect(Ml::ModelVersion.find_by(id: valid_model_version.id)).to eq(valid_model_version)
      end
    end
  end
end


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

module DesignManagement
  class MoveDesignsService < DesignService
    # @param user [User] The current user
    # @param [Hash] params
    # @option params [DesignManagement::Design] :current_design
    # @option params [DesignManagement::Design] :previous_design (nil)
    # @option params [DesignManagement::Design] :next_design (nil)
    def initialize(user, params)
      super(nil, user, params.merge(issue: nil))
    end

    def execute
      return error(:no_focus) unless current_design.present?
      return error(:cannot_move) unless current_user.can?(:move_design, current_design)
      return error(:no_neighbors) unless neighbors.present?
      return error(:not_distinct) unless all_distinct?
      return error(:not_same_issue) unless all_same_issue?

      move_nulls_to_end
      current_design.move_between(previous_design, next_design)
      current_design.save!
      success
    end

    def error(message)
      ServiceResponse.error(message: message)
    end

    def success
      ServiceResponse.success
    end

    private

    delegate :issue, :project, to: :current_design

    def move_nulls_to_end
      moved_records = current_design.class.move_nulls_to_end(issue.designs.in_creation_order)
      return if moved_records == 0

      current_design.reset
      next_design&.reset
      previous_design&.reset
    end

    def neighbors
      [previous_design, next_design].compact
    end

    def all_distinct?
      ids.uniq.size == ids.size
    end

    def all_same_issue?
      issue.designs.id_in(ids).count == ids.size
    end

    def ids
      @ids ||= [current_design, *neighbors].map(&:id)
    end

    def current_design
      params[:current_design]
    end

    def previous_design
      params[:previous_design]
    end

    def next_design
      params[:next_design]
    end
  end
end

```

Response:
# frozen_string_literal: true
require 'spec_helper'

RSpec.describe DesignManagement::MoveDesignsService, feature_category: :design_management do
  include DesignManagementTestHelpers

  let_it_be(:issue) { create(:issue) }
  let_it_be(:developer) { create(:user, developer_projects: [issue.project]) }
  let_it_be(:designs) { create_list(:design, 3, :with_relative_position, issue: issue) }

  let(:project) { issue.project }

  let(:service) { described_class.new(current_user, params) }

  let(:params) do
    {
      current_design: current_design,
      previous_design: previous_design,
      next_design: next_design
    }
  end

  let(:current_user) { developer }
  let(:current_design) { nil }
  let(:previous_design) { nil }
  let(:next_design) { nil }

  before do
    enable_design_management
  end

  describe '#execute' do
    subject { service.execute }

    context 'the user cannot move designs' do
      let(:current_design) { designs.first }
      let(:current_user) { build_stubbed(:user) }

      it 'raises cannot_move' do
        expect(subject).to be_error.and(have_attributes(message: :cannot_move))
      end
    end

    context 'the designs are not distinct' do
      let(:current_design) { designs.first }
      let(:previous_design) { designs.first }

      it 'raises not_distinct' do
        expect(subject).to be_error.and(have_attributes(message: :not_distinct))
      end
    end

    context 'the designs are not on the same issue' do
      let(:current_design) { designs.first }
      let(:previous_design) { create(:design) }

      it 'raises not_same_issue' do
        expect(subject).to be_error.and(have_attributes(message: :not_same_issue))
      end
    end

    context 'no focus is passed' do
      let(:previous_design) { designs.second }
      let(:next_design) { designs.third }

      it 'raises no_focus' do
        expect(subject).to be_error.and(have_attributes(message: :no_focus))
      end
    end

    context 'no neighbours are passed' do
      let(:current_design) { designs.first }

      it 'raises no_neighbors' do
        expect(subject).to be_error.and(have_attributes(message: :no_neighbors))
      end
    end

    context 'moving a design with neighbours' do
      let(:current_design) { designs.first }
      let(:previous_design) { designs.second }
      let(:next_design) { designs.third }

      it 'repositions existing designs and correctly places the given design' do
        other_design1 = create(:design, issue: issue, relative_position: 10)
        other_design2 = create(:design, issue: issue, relative_position: 20)
        other_design3, other_design4 = create_list(:design, 2, issue: issue)

        expect(subject).to be_success

        expect(issue.designs.ordered).to eq(
          [
            # Existing designs which already had a relative_position set.
            # These should stay at the beginning, in the same order.
            other_design1,
            other_design2,

            # The designs we're passing into the service.
            # These should be placed between the existing designs, in the correct order.
            previous_design,
            current_design,
            next_design,

            # Existing designs which didn't have a relative_position set.
            # These should be placed at the end, in the order of their IDs.
            other_design3,
            other_design4
          ])
      end
    end
  end
end


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

module DesignManagement
  # Service class for counting and caching the number of unresolved
  # notes of a Design
  class DesignUserNotesCountService < ::BaseCountService
    # The version of the cache format. This should be bumped whenever the
    # underlying logic changes. This removes the need for explicitly flushing
    # all caches.
    VERSION = 1

    def initialize(design)
      @design = design
    end

    def relation_for_count
      design.notes.user
    end

    def raw?
      # Since we're storing simple integers we don't need all of the
      # additional Marshal data Rails includes by default.
      true
    end

    def cache_key
      ['designs', 'notes_count', VERSION, design.id]
    end

    private

    attr_reader :design
  end
end

```

Response:
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe DesignManagement::DesignUserNotesCountService, :use_clean_rails_memory_store_caching, feature_category: :design_management do
  let_it_be(:design) { create(:design, :with_file) }

  subject { described_class.new(design) }

  it_behaves_like 'a counter caching service'

  describe '#count' do
    it 'returns the count of notes' do
      create_list(:diff_note_on_design, 3, noteable: design)

      expect(subject.count).to eq(3)
    end
  end

  describe '#cache_key' do
    it 'contains the `VERSION` and `design.id`' do
      expect(subject.cache_key).to eq(['designs', 'notes_count', DesignManagement::DesignUserNotesCountService::VERSION, design.id])
    end
  end

  describe 'cache invalidation' do
    it 'changes when a new note is created' do
      new_note_attrs = attributes_for(:diff_note_on_design, noteable: design)

      expect do
        Notes::CreateService.new(design.project, create(:user), new_note_attrs).execute
      end.to change { subject.count }.by(1)
    end

    it 'changes when a note is destroyed' do
      note = create(:diff_note_on_design, noteable: design)

      expect do
        Notes::DestroyService.new(note.project, note.author).execute(note)
      end.to change { subject.count }.by(-1)
    end
  end
end