Skip to content

Commit

Permalink
Setting an invalid enum default is a bug
Browse files Browse the repository at this point in the history
  • Loading branch information
lewispb committed Aug 2, 2023
1 parent 5c5ee24 commit cc08f25
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
8 changes: 7 additions & 1 deletion lib/kredis/types/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
12 changes: 8 additions & 4 deletions test/types/enum_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cc08f25

Please sign in to comment.