summaryrefslogtreecommitdiff
path: root/spec/models/concerns/has_environment_scope_spec.rb
blob: a6e1ba59263503c4d30e9be97010fe0c834eac84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# frozen_string_literal: true

require 'spec_helper'

describe HasEnvironmentScope do
  subject { build(:ci_variable) }

  it { is_expected.to allow_value('*').for(:environment_scope) }
  it { is_expected.to allow_value('review/*').for(:environment_scope) }
  it { is_expected.not_to allow_value('').for(:environment_scope) }
  it { is_expected.not_to allow_value('!!()()').for(:environment_scope) }

  it do
    is_expected.to validate_uniqueness_of(:key)
      .scoped_to(:project_id, :environment_scope)
      .with_message(/\(\w+\) has already been taken/)
  end

  describe '.on_environment' do
    let(:project) { create(:project) }

    it 'returns scoped objects' do
      variable1 = create(:ci_variable, project: project, environment_scope: '*')
      variable2 = create(:ci_variable, project: project, environment_scope: 'product/*')
      create(:ci_variable, project: project, environment_scope: 'staging/*')

      expect(project.variables.on_environment('product/canary-1')).to eq([variable1, variable2])
    end

    it 'returns only the most relevant object if relevant_only is true' do
      create(:ci_variable, project: project, environment_scope: '*')
      variable2 = create(:ci_variable, project: project, environment_scope: 'product/*')
      create(:ci_variable, project: project, environment_scope: 'staging/*')

      expect(project.variables.on_environment('product/canary-1', relevant_only: true)).to eq([variable2])
    end

    it 'returns scopes ordered by lowest precedence first' do
      create(:ci_variable, project: project, environment_scope: '*')
      create(:ci_variable, project: project, environment_scope: 'production*')
      create(:ci_variable, project: project, environment_scope: 'production')

      result = project.variables.on_environment('production').map(&:environment_scope)

      expect(result).to eq(['*', 'production*', 'production'])
    end
  end

  describe '#environment_scope=' do
    context 'when the new environment_scope is nil' do
      it 'strips leading and trailing whitespaces' do
        subject.environment_scope = nil

        expect(subject.environment_scope).to eq('')
      end
    end

    context 'when the new environment_scope has leadind and trailing whitespaces' do
      it 'strips leading and trailing whitespaces' do
        subject.environment_scope = ' * '

        expect(subject.environment_scope).to eq('*')
      end
    end
  end
end