From e33af9c86fbfd806214a0e55fab2fbe1d0ea864a Mon Sep 17 00:00:00 2001 From: Joel Drapper Date: Thu, 19 Dec 2024 13:08:13 +0000 Subject: [PATCH] Coerce should raise if it fails --- lib/literal/enum.rb | 10 ++++++++-- test/enum.test.rb | 12 ++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/literal/enum.rb b/lib/literal/enum.rb index f530c91..1c91349 100644 --- a/lib/literal/enum.rb +++ b/lib/literal/enum.rb @@ -153,10 +153,16 @@ def coerce(value) self[value] || begin const_get(value) rescue NameError - nil + raise ArgumentError.new( + "Can't coerce #{value.inspect} into a #{inspect}." + ) end else - self[value] + self[value] || raise( + ArgumentError.new( + "Can't coerce #{value.inspect} into a #{inspect}." + ) + ) end end diff --git a/test/enum.test.rb b/test/enum.test.rb index 97a9747..ba1e08d 100644 --- a/test/enum.test.rb +++ b/test/enum.test.rb @@ -47,8 +47,16 @@ class SymbolTypedEnum < Literal::Enum(Symbol) assert_equal Color.coerce(:Red), Color::Red end -test ".coerce with invalid symbol returns nil" do - assert_equal Color.coerce(:Invalid), nil +test ".coerce with invalid symbol raises an ArgumentError" do + assert_raises ArgumentError do + Color.coerce(:Invalid) + end +end + +test ".coerce with invalid value raises an ArgumenError" do + assert_raises ArgumentError do + Color.coerce("invalid value") + end end test ".[] looks up the key by value" do