summaryrefslogtreecommitdiff
path: root/spec/models/concerns/manual_inverse_association_spec.rb
blob: ee32e3b165babf4a3e487562caed253ed36e27e6 (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
# frozen_string_literal: true

require 'spec_helper'

describe ManualInverseAssociation do
  let(:model) do
    Class.new(MergeRequest) do
      belongs_to :manual_association, class_name: 'MergeRequestDiff', foreign_key: :latest_merge_request_diff_id
      manual_inverse_association :manual_association, :merge_request
    end
  end

  before do
    stub_const("#{described_class}::Model", model)
  end

  let(:instance) { create(:merge_request).becomes(model) }

  describe '.manual_inverse_association' do
    context 'when the relation exists' do
      before do
        instance.create_merge_request_diff
        instance.reload
      end

      it 'loads the relation' do
        expect(instance.manual_association).to be_an_instance_of(MergeRequestDiff)
      end

      it 'does not perform extra queries after loading' do
        instance.manual_association

        expect { instance.manual_association.merge_request }
          .not_to exceed_query_limit(0)
      end

      it 'allows reloading the relation' do
        query_count = ActiveRecord::QueryRecorder.new do
          instance.manual_association
          instance.reload_manual_association
        end.count

        expect(query_count).to eq(2)
      end
    end

    context 'when the relation does not return a value' do
      it 'does not try to set an inverse' do
        expect(instance.manual_association).to be_nil
      end
    end
  end
end