Browse Source

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.

Thorsten Eckel 5 years ago
parent
commit
b361c422f8
2 changed files with 25 additions and 4 deletions
  1. 2 4
      lib/user_info.rb
  2. 23 0
      spec/lib/user_info_spec.rb

+ 2 - 4
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

+ 23 - 0
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