setting_spec.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. RSpec.describe Setting do
  4. describe '#to_param' do
  5. let(:setting) { Fabricate(:setting, var: var) }
  6. let(:var) { 'var' }
  7. it 'returns setting.var' do
  8. expect(setting.to_param).to eq var
  9. end
  10. end
  11. describe '.[]' do
  12. let(:key) { 'key' }
  13. let(:cache_key) { 'cache-key' }
  14. let(:cache_value) { 'cache-value' }
  15. before do
  16. allow(described_class).to receive(:cache_key).with(key).and_return(cache_key)
  17. end
  18. context 'when Rails.cache does not exists' do
  19. before do
  20. allow(described_class).to receive(:default_settings).and_return(default_settings)
  21. Fabricate(:setting, var: key, value: 42) if save_setting
  22. Rails.cache.delete(cache_key)
  23. end
  24. let(:default_value) { 'default_value' }
  25. let(:default_settings) { { key => default_value } }
  26. let(:save_setting) { true }
  27. context 'when the setting has been saved to database' do
  28. it 'returns the value from database' do
  29. callback = double
  30. allow(callback).to receive(:call)
  31. ActiveSupport::Notifications.subscribed callback, 'sql.active_record' do
  32. expect(described_class[key]).to eq 42
  33. end
  34. expect(callback).to have_received(:call)
  35. end
  36. end
  37. context 'when the setting has not been saved to database' do
  38. let(:save_setting) { false }
  39. it 'returns default_settings[key]' do
  40. expect(described_class[key]).to be default_settings[key]
  41. end
  42. end
  43. end
  44. context 'when Rails.cache exists' do
  45. before do
  46. Rails.cache.write(cache_key, cache_value)
  47. end
  48. it 'does not query the database' do
  49. callback = double
  50. allow(callback).to receive(:call)
  51. ActiveSupport::Notifications.subscribed callback, 'sql.active_record' do
  52. described_class[key]
  53. end
  54. expect(callback).to_not have_received(:call)
  55. end
  56. it 'returns the cached value' do
  57. expect(described_class[key]).to eq cache_value
  58. end
  59. end
  60. end
  61. end