Read about our upcoming Code of Conduct on this issue

internal_id_spec.rb 2.21 KB
Newer Older
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
require 'spec_helper'

describe InternalId do
  let(:project) { create(:project) }
  let(:usage) { :issues }

  context 'validations' do
    it { is_expected.to validate_presence_of(:usage) }
    it { is_expected.to validate_presence_of(:project_id) }
  end

  describe '.generate_next' do
    context 'in the absence of a record' do
      subject { described_class.generate_next(project, usage) }

      it 'creates a record if not yet present' do
        expect { subject }.to change { described_class.count }.from(0).to(1)
      end

      it 'stores record attributes' do
        subject

        described_class.first.tap do |record|
          expect(record.project).to eq(project)
          expect(record.usage).to eq(usage.to_s) # TODO
        end
      end

      context 'with existing issues' do
        before do
          rand(10).times { create(:issue, project: project) }
        end

        it 'calculates last_value values automatically' do
          expect(subject).to eq(project.issues.size + 1)
        end
      end
    end

    it 'generates a strictly monotone, gapless sequence' do
      seq = (0..rand(1000)).map do
        described_class.generate_next(project, usage)
      end
      normalized = seq.map { |i| i - seq.min }
      expect(normalized).to eq((0..seq.size - 1).to_a)
    end
  end

  describe '#increment_and_save!' do
    let(:id) { create(:internal_id) }
    subject { id.increment_and_save! }

    it 'returns incremented iid' do
      value = id.last_value
      expect(subject).to eq(value + 1)
    end

    it 'saves the record' do
      subject
      expect(id.changed?).to be_falsey
    end

    context 'with last_value=nil' do
      let(:id) { build(:internal_id, last_value: nil) }

      it 'returns 1' do
        expect(subject).to eq(1)
      end
    end
  end

  describe '#calculate_last_value! (for issues)' do
    subject do
      build(:internal_id, project: project, usage: :issues)
    end

    context 'with existing issues' do
      before do
        rand(10).times { create(:issue, project: project) }
      end

      it 'counts related issues and saves' do
        expect { subject.calculate_last_value! }.to change { subject.last_value }.from(nil).to(project.issues.size)
      end
    end
  end
end