ecto icon indicating copy to clipboard operation
ecto copied to clipboard

Add error reason to `Ecto.Enum.cast/2`

Open satom99 opened this issue 11 months ago • 0 comments

The current behaviour of Ecto.Enum.cast/2 is that only an :error atom is returned in case of error:

params = Ecto.Enum.init(values: [foo: 1, bar: 2, baz: 5])

assert :error = Ecto.Enum.cast("qux", params)

This PR changes the assertion above to be:

assert {:error, validation: :inclusion, enum: [:foo, "foo", 1, :bar, "bar", 2, :baz, "baz", 5]} =
               Ecto.Enum.cast("qux", params)

Where I chose to mimic the same :validation and :enum fields that Ecto emits for the Changeset.validate_inclusion/2 function.

Also, for this purpose I also defined a new Ecto.Enum.cast_values/1 function that returns all the possible values that the cast/2 function accepts — so [:foo, 1, :bar, 2, :baz, 5] for this example.

satom99 avatar Mar 07 '24 15:03 satom99