# frozen_string_literal: true

require 'spec_helper'

describe ReleaseTools::Branch do
  subject(:branch) do
    described_class.new(name: branch_name, project: project)
  end

  let(:branch_name) { 'release-tools-create-branch' }
  let(:client) { stub_const('ReleaseTools::GitlabClient', spy) }
  let(:project) { ReleaseTools::Project::GitlabCe }

  describe '#create', vcr: { cassette_name: 'branches/create' } do
    it 'creates a new branch in the given project' do
      without_dry_run do
        expect(branch.create(ref: '9-4-stable')).to be_truthy
      end
    end

    it 'points the branch to the correct ref' do
      without_dry_run do
        response = branch.create(ref: '9-4-stable')

        expect(response.commit.short_id).to eq 'b125d211'
      end
    end
  end

  describe '#exist?' do
    it 'returns the status of the branch' do
      allow(client)
        .to receive(:find_branch)
        .and_return(create(:branch))

      expect(branch).to exist
    end

    context 'when the branch does not exist' do
      it 'returns the status of the branch' do
        allow(client)
          .to receive(:find_branch)
          .and_return(nil)

        expect(branch).not_to exist
      end
    end
  end

  describe '#last_commit' do
    it 'return the lastest commit of a branch' do
      # Set values for branch name and project
      allow(client)
        .to receive(:commit)
        .with(project, ref: branch_name)
        .and_return(create(:commit, short_id: 'b125d211'))

      expect(branch.last_commit.short_id).to eq 'b125d211'
    end
  end

  describe '#version' do
    context 'with a regular branch' do
      it 'returns nil' do
        expect(branch.version).to be_nil
      end
    end

    context 'with a stable branch' do
      let(:branch_name) { '16-10-stable-ee' }

      it 'returns a version object' do
        expect(branch.version).to eq('16.10.0')
        expect(branch.version).to be_an_instance_of(ReleaseTools::Version)
      end
    end
  end
end
