simplifiable_spec.rb 2.43 KB
Newer Older
1 2
require 'spec_helper'

3
describe Gitlab::Config::Entry::Simplifiable do
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 67 68 69 70 71 72 73 74
  describe '.strategy' do
    let(:entry) do
      Class.new(described_class) do
        strategy :Something, if: -> { 'condition' }
        strategy :DifferentOne, if: -> { 'condition' }
      end
    end

    it 'defines entry strategies' do
      expect(entry.strategies.size).to eq 2
      expect(entry.strategies.map(&:name))
        .to eq %i[Something DifferentOne]
    end
  end

  describe 'setting strategy by a condition' do
    let(:first) { double('first strategy') }
    let(:second) { double('second strategy') }
    let(:unknown) { double('unknown strategy') }

    before do
      stub_const("#{described_class.name}::Something", first)
      stub_const("#{described_class.name}::DifferentOne", second)
      stub_const("#{described_class.name}::UnknownStrategy", unknown)
    end

    context 'when first strategy should be used' do
      let(:entry) do
        Class.new(described_class) do
          strategy :Something, if: -> (arg) { arg == 'something' }
          strategy :DifferentOne, if: -> (*) { false }
        end
      end

      it 'attemps to load a first strategy' do
        expect(first).to receive(:new).with('something', anything)

        entry.new('something')
      end
    end

    context 'when second strategy should be used' do
      let(:entry) do
        Class.new(described_class) do
          strategy :Something, if: -> (arg) { arg == 'something' }
          strategy :DifferentOne, if: -> (arg) { arg == 'test' }
        end
      end

      it 'attemps to load a second strategy' do
        expect(second).to receive(:new).with('test', anything)

        entry.new('test')
      end
    end

    context 'when neither one is a valid strategy' do
      let(:entry) do
        Class.new(described_class) do
          strategy :Something, if: -> (*) { false }
          strategy :DifferentOne, if: -> (*) { false }
        end
      end

      it 'instantiates an unknown strategy' do
        expect(unknown).to receive(:new).with('test', anything)

        entry.new('test')
      end
    end
  end
75 76 77 78 79 80 81 82 83 84 85 86 87

  context 'when a unknown strategy class is not defined' do
    let(:entry) do
      Class.new(described_class) do
        strategy :String, if: -> (*) { true }
      end
    end

    it 'raises an error when being initialized' do
      expect { entry.new('something') }
        .to raise_error ArgumentError, /UndefinedStrategy not available!/
    end
  end
88
end