From b361c422f80f9e17d83e2e58772193b436f9118d Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Fri, 12 Jul 2019 15:59:18 +0200 Subject: [PATCH] Refactoring UserInfo: - Pass return value of given block back to caller. - Ensure that exceptions don't cause the temporary UserInfo.current_user_id to leak. --- lib/user_info.rb | 6 ++---- spec/lib/user_info_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/lib/user_info.rb b/lib/user_info.rb index 1361996dd..b79aa4f69 100644 --- a/lib/user_info.rb +++ b/lib/user_info.rb @@ -14,9 +14,7 @@ module UserInfo end yield - - return if !reset_current_user_id - - UserInfo.current_user_id = nil + ensure + UserInfo.current_user_id = nil if reset_current_user_id end end diff --git a/spec/lib/user_info_spec.rb b/spec/lib/user_info_spec.rb index d183e9a6a..46bfff7a2 100644 --- a/spec/lib/user_info_spec.rb +++ b/spec/lib/user_info_spec.rb @@ -17,6 +17,8 @@ RSpec.describe UserInfo do describe '#ensure_current_user_id' do + let(:return_value) { 'Hello World' } + it 'uses and keeps set User IDs' do test_id = 99 described_class.current_user_id = test_id @@ -37,5 +39,26 @@ RSpec.describe UserInfo do expect(described_class.current_user_id).to be nil end + + it 'resets current_user_id in case of an exception' do + begin + described_class.ensure_current_user_id do + raise 'error' + end + rescue # rubocop:disable Lint/HandleExceptions + end + + expect(described_class.current_user_id).to be nil + end + + it 'passes return value of given block' do + + received = described_class.ensure_current_user_id do + return_value + end + + expect(received).to eq(return_value) + end + end end