From 8ef2970234dab65a00b4189cc230dcff9195de34 Mon Sep 17 00:00:00 2001 From: Thorsten Eckel Date: Thu, 27 Apr 2017 10:17:10 +0200 Subject: [PATCH] Added method to perform a yielded action with an ensured UserInfo.current_user_id and added new and missing tests. --- lib/user_info.rb | 12 +++++++++++ spec/lib/user_info_spec.rb | 41 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 spec/lib/user_info_spec.rb diff --git a/lib/user_info.rb b/lib/user_info.rb index ed6a12761..604e9e964 100644 --- a/lib/user_info.rb +++ b/lib/user_info.rb @@ -6,4 +6,16 @@ module UserInfo def self.current_user_id=(user_id) Thread.current[:user_id] = user_id end + + def self.ensure_current_user_id + if UserInfo.current_user_id.nil? + UserInfo.current_user_id = 1 + reset_current_user_id = true + end + + yield + + return if !reset_current_user_id + UserInfo.current_user_id = nil + end end diff --git a/spec/lib/user_info_spec.rb b/spec/lib/user_info_spec.rb new file mode 100644 index 000000000..d183e9a6a --- /dev/null +++ b/spec/lib/user_info_spec.rb @@ -0,0 +1,41 @@ +require 'rails_helper' + +RSpec.describe UserInfo do + + describe '#current_user_id' do + + it 'is nil by default' do + expect(described_class.current_user_id).to be nil + end + + it 'takes a User ID as paramter and returns it' do + test_id = 99 + described_class.current_user_id = test_id + expect(described_class.current_user_id).to eq(test_id) + end + end + + describe '#ensure_current_user_id' do + + it 'uses and keeps set User IDs' do + test_id = 99 + described_class.current_user_id = test_id + + described_class.ensure_current_user_id do + expect(described_class.current_user_id).to eq(test_id) + end + + expect(described_class.current_user_id).to eq(test_id) + end + + it 'sets and resets temporary User ID 1' do + described_class.current_user_id = nil + + described_class.ensure_current_user_id do + expect(described_class.current_user_id).to eq(1) + end + + expect(described_class.current_user_id).to be nil + end + end +end