From 57b3c48e6dc411dfd7f7ab93e2a63857e074288e Mon Sep 17 00:00:00 2001 From: Claire Date: Mon, 19 Jun 2023 11:00:56 +0200 Subject: [PATCH] Fix user settings not getting validated --- app/models/user_settings.rb | 5 ++++- spec/models/user_settings_spec.rb | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/app/models/user_settings.rb b/app/models/user_settings.rb index 2c025d6c56426..0f77f45f78743 100644 --- a/app/models/user_settings.rb +++ b/app/models/user_settings.rb @@ -72,7 +72,10 @@ def []=(key, value) raise KeyError, "Undefined setting: #{key}" unless self.class.definition_for?(key) - typecast_value = self.class.definition_for(key).type_cast(value) + setting_definition = self.class.definition_for(key) + typecast_value = setting_definition.type_cast(value) + + raise ArgumentError, "Invalid value for setting #{key}: #{typecast_value}" if setting_definition.in.present? && setting_definition.in.exclude?(typecast_value) if typecast_value.nil? @original_hash.delete(key) diff --git a/spec/models/user_settings_spec.rb b/spec/models/user_settings_spec.rb index f0e4272fd9943..653597c90de59 100644 --- a/spec/models/user_settings_spec.rb +++ b/spec/models/user_settings_spec.rb @@ -49,6 +49,16 @@ expect(subject[:always_send_emails]).to be true end end + + context 'when the setting has a closed set of values' do + it 'updates the attribute when given a valid value' do + expect { subject[:'web.display_media'] = :show_all }.to change { subject[:'web.display_media'] }.from('default').to('show_all') + end + + it 'raises an error when given an invalid value' do + expect { subject[:'web.display_media'] = 'invalid value' }.to raise_error ArgumentError + end + end end describe '#update' do