user_info_spec.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. RSpec.describe UserInfo do
  4. describe '#current_user_id' do
  5. it 'is nil by default' do
  6. expect(described_class.current_user_id).to be_nil
  7. end
  8. it 'takes a User ID as paramter and returns it' do
  9. test_id = 99
  10. described_class.current_user_id = test_id
  11. expect(described_class.current_user_id).to eq(test_id)
  12. end
  13. end
  14. describe '#ensure_current_user_id' do
  15. let(:return_value) { 'Hello World' }
  16. it 'uses and keeps set User IDs' do
  17. test_id = 99
  18. described_class.current_user_id = test_id
  19. described_class.ensure_current_user_id do
  20. expect(described_class.current_user_id).to eq(test_id)
  21. end
  22. expect(described_class.current_user_id).to eq(test_id)
  23. end
  24. it 'sets and resets temporary User ID 1' do
  25. described_class.current_user_id = nil
  26. described_class.ensure_current_user_id do
  27. expect(described_class.current_user_id).to eq(1)
  28. end
  29. expect(described_class.current_user_id).to be_nil
  30. end
  31. it 'resets current_user_id in case of an exception' do
  32. begin
  33. described_class.ensure_current_user_id do
  34. raise 'error'
  35. end
  36. rescue # rubocop:disable Lint/SuppressedException
  37. end
  38. expect(described_class.current_user_id).to be_nil
  39. end
  40. it 'passes return value of given block' do
  41. received = described_class.ensure_current_user_id do
  42. return_value
  43. end
  44. expect(received).to eq(return_value)
  45. end
  46. end
  47. describe 'with_user_id' do
  48. let(:return_value) { 'Hello World' }
  49. let(:test_id) { 666 }
  50. let(:another_test_id) { 123 }
  51. it 'uses given user ID in the given block' do
  52. described_class.with_user_id(test_id) do
  53. expect(described_class.current_user_id).to eq(test_id)
  54. end
  55. end
  56. it 'resets to surrounding user ID' do
  57. described_class.current_user_id = test_id
  58. described_class.with_user_id(another_test_id) do
  59. expect(described_class.current_user_id).not_to eq(test_id)
  60. end
  61. expect(described_class.current_user_id).to eq(test_id)
  62. end
  63. it 'resets current_user_id in case of an exception' do
  64. begin
  65. described_class.with_user_id(test_id) do
  66. raise 'error'
  67. end
  68. rescue # rubocop:disable Lint/SuppressedException
  69. end
  70. expect(described_class.current_user_id).to be_nil
  71. end
  72. it 'passes return value of given block' do
  73. received = described_class.with_user_id(test_id) do
  74. return_value
  75. end
  76. expect(received).to eq(return_value)
  77. end
  78. end
  79. end