From 917effb7379f8e871dbc113d7c7dab89473d4bc8 Mon Sep 17 00:00:00 2001 From: Grzegorz Bizon Date: Fri, 11 Dec 2015 13:37:54 +0000 Subject: [PATCH] Make sure that token `ensure_*` method always returns a token --- app/models/concerns/token_authenticatable.rb | 8 ++++++-- spec/models/concerns/token_authenticatable_spec.rb | 9 ++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/models/concerns/token_authenticatable.rb b/app/models/concerns/token_authenticatable.rb index fe764e8da41..56d38fe8250 100644 --- a/app/models/concerns/token_authenticatable.rb +++ b/app/models/concerns/token_authenticatable.rb @@ -17,8 +17,12 @@ module TokenAuthenticatable end define_method("ensure_#{token_field}") do - write_attribute(token_field, generate_token_for(token_field)) if - read_attribute(token_field).blank? + current_token = read_attribute(token_field) + if current_token.blank? + write_attribute(token_field, generate_token_for(token_field)) + else + current_token + end end define_method("reset_#{token_field}!") do diff --git a/spec/models/concerns/token_authenticatable_spec.rb b/spec/models/concerns/token_authenticatable_spec.rb index 1b553173415..a9b0b64e5de 100644 --- a/spec/models/concerns/token_authenticatable_spec.rb +++ b/spec/models/concerns/token_authenticatable_spec.rb @@ -13,7 +13,7 @@ describe User, 'TokenAuthenticatable' do let(:token_field) { :authentication_token } it_behaves_like 'TokenAuthenticatable' - describe 'ensured authentication token' do + describe 'ensures authentication token' do subject { create(:user).send(token_field) } it { is_expected.to be_a String } end @@ -29,6 +29,13 @@ describe ApplicationSetting, 'TokenAuthenticatable' do context 'token is not generated yet' do it { expect(token).to be nil } + + describe 'ensured token' do + subject { described_class.new.send("ensure_#{token_field}") } + + it { is_expected.to be_a String } + it { is_expected.to_not be_blank } + end end context 'token is generated' do