Created
December 13, 2023 05:15
-
-
Save idlehands/9ef4b2690b723be817d3c8f851a17b60 to your computer and use it in GitHub Desktop.
macro for validating ecto schema fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmacro validate_schema_fields_and_types(schema, expected_schemas_and_types) do | |
quote do | |
test "#{unquote(schema)}: it has the correct fields and types" do | |
schema = unquote(schema) | |
expected_schemas_and_types = unquote(expected_schemas_and_types) | |
actual_fields_with_types = | |
for field <- schema.__schema__(:fields) do | |
type = field_type(schema, field) | |
{field, type} | |
end | |
assert Enum.sort(actual_fields_with_types) == | |
Enum.sort(expected_schemas_and_types) | |
end | |
end | |
end | |
def field_type(module, field) do | |
case module.__schema__(:type, field) do | |
{:parameterized, Ecto.Embedded, %Ecto.Embedded{related: embedded_type}} -> | |
{:embedded_schema, embedded_type} | |
{:parameterized, Ecto.Enum, enum_data} -> | |
{Ecto.Enum, Keyword.keys(enum_data.mappings)} | |
anything_else -> | |
anything_else | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I typically paste this code into my DataCase