BigW Consortium Gitlab

token_authenticatable_spec.rb 2.32 KB
Newer Older
1 2 3 4
require 'spec_helper'

shared_examples 'TokenAuthenticatable' do
  describe 'dynamically defined methods' do
5 6
    it { expect(described_class).to be_private_method_defined(:generate_token) }
    it { expect(described_class).to be_private_method_defined(:write_new_token) }
7 8
    it { expect(described_class).to respond_to("find_by_#{token_field}") }
    it { is_expected.to respond_to("ensure_#{token_field}") }
9
    it { is_expected.to respond_to("set_#{token_field}") }
10 11 12 13 14 15 16 17
    it { is_expected.to respond_to("reset_#{token_field}!") }
  end
end

describe User, 'TokenAuthenticatable' do
  let(:token_field) { :authentication_token }
  it_behaves_like 'TokenAuthenticatable'

18
  describe 'ensures authentication token' do
19 20 21 22 23 24 25 26 27 28 29
    subject { create(:user).send(token_field) }
    it { is_expected.to be_a String }
  end
end

describe ApplicationSetting, 'TokenAuthenticatable' do
  let(:token_field) { :runners_registration_token }
  it_behaves_like 'TokenAuthenticatable'

  describe 'generating new token' do
    context 'token is not generated yet' do
30 31
      describe 'token field accessor' do
        subject { described_class.new.send(token_field) }
32
        it { is_expected.not_to be_blank }
33
      end
34 35 36 37 38

      describe 'ensured token' do
        subject { described_class.new.send("ensure_#{token_field}") }

        it { is_expected.to be_a String }
39
        it { is_expected.not_to be_blank }
40 41 42 43
      end

      describe 'ensured! token' do
        subject { described_class.new.send("ensure_#{token_field}!") }
44

45
        it 'persists new token' do
46 47
          expect(subject).to eq described_class.current[token_field]
        end
48
      end
49 50 51
    end

    context 'token is generated' do
52 53 54 55
      before do
        subject.send("reset_#{token_field}!")
      end

56
      it 'persists a new token' do
57 58
        expect(subject.send(:read_attribute, token_field)).to be_a String
      end
59 60 61
    end
  end

62 63 64 65 66 67
  describe 'setting new token' do
    subject { described_class.new.send("set_#{token_field}", '0123456789') }

    it { is_expected.to eq '0123456789' }
  end

68 69 70 71 72 73 74 75 76 77 78
  describe 'multiple token fields' do
    before do
      described_class.send(:add_authentication_token_field, :yet_another_token)
    end

    describe '.token_fields' do
      subject { described_class.authentication_token_fields }
      it { is_expected.to include(:runners_registration_token, :yet_another_token) }
    end
  end
end