From cc08f2570a07b667d2aa207ddde2838fb488714b Mon Sep 17 00:00:00 2001 From: Lewis Buckley Date: Wed, 2 Aug 2023 13:06:29 +0100 Subject: [PATCH] Setting an invalid enum default is a bug --- lib/kredis/types/enum.rb | 8 +++++++- test/types/enum_test.rb | 12 ++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/kredis/types/enum.rb b/lib/kredis/types/enum.rb index 70bd885..b5047d4 100644 --- a/lib/kredis/types/enum.rb +++ b/lib/kredis/types/enum.rb @@ -5,6 +5,8 @@ class Kredis::Types::Enum < Kredis::Types::Proxying prepend Kredis::DefaultValues + InvalidDefault = Class.new(StandardError) + proxying :set, :get, :del, :exists?, :multi attr_accessor :values @@ -40,6 +42,10 @@ def define_predicates_for_values end def set_default - set default + if default.in?(values) || default.nil? + set default + else + raise InvalidDefault, "Default value #{default.inspect} for #{key} is not a valid option (Valid values: #{values.join(", ")})" + end end end diff --git a/test/types/enum_test.rb b/test/types/enum_test.rb index 6cac20e..d89f882 100644 --- a/test/types/enum_test.rb +++ b/test/types/enum_test.rb @@ -14,11 +14,15 @@ class EnumTest < ActiveSupport::TestCase assert_equal "two", @enum.value end - test "does not set default for invalid option" do - enum = Kredis.enum "myenum3", values: [ 1, 2, 3 ], default: ->() { nil } + test "default can be nil" do + enum = Kredis.enum "myenum3", values: [ 1, 2, 3 ], default: nil assert_nil enum.value - enum = Kredis.enum "myenum4", values: [ 1, 2, 3 ], default: ->() { 4 } - assert_equal "4", enum.value + end + + test "default value has to be valid if not nil" do + assert_raises Kredis::Types::Enum::InvalidDefault do + Kredis.enum "myenum4", values: [ 1, 2, 3 ], default: 4 + end end test "predicates" do