summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/class_attributes_spec.rb
blob: ac2a18a18605b7fa0349a5c03b889e2e33fdcc21 (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
67
# frozen_string_literal: true
require 'fast_spec_helper'

RSpec.describe Gitlab::ClassAttributes do
  let(:klass) do
    Class.new do
      include Gitlab::ClassAttributes

      class << self
        attr_reader :counter_1, :counter_2

        # get_class_attribute and set_class_attribute are protected,
        # hence those methods are for testing purpose
        def get_attribute(name)
          get_class_attribute(name)
        end

        def set_attribute(name, value)
          set_class_attribute(name, value)
        end
      end

      after_set_class_attribute do
        @counter_1 ||= 0
        @counter_1 += 1
      end

      after_set_class_attribute do
        @counter_2 ||= 0
        @counter_2 += 2
      end
    end
  end

  let(:subclass) { Class.new(klass) }

  it "returns values set on the class" do
    klass.set_attribute(:foo, :bar)

    expect(klass.get_attribute(:foo)).to eq(:bar)
  end

  it "returns values set on a superclass" do
    klass.set_attribute(:foo, :bar)

    expect(subclass.get_attribute(:foo)).to eq(:bar)
  end

  it "returns values from the subclass over attributes from a superclass" do
    klass.set_attribute(:foo, :baz)
    subclass.set_attribute(:foo, :bar)

    expect(klass.get_attribute(:foo)).to eq(:baz)
    expect(subclass.get_attribute(:foo)).to eq(:bar)
  end

  it "triggers after hooks after set class values" do
    expect(klass.counter_1).to be(nil)
    expect(klass.counter_2).to be(nil)

    klass.set_attribute(:foo, :bar)
    klass.set_attribute(:foo, :bar)

    expect(klass.counter_1).to eq(2)
    expect(klass.counter_2).to eq(4)
  end
end