Skip to content

Instantly share code, notes, and snippets.

@idlehands
Created December 13, 2023 05:15
Show Gist options
  • Save idlehands/9ef4b2690b723be817d3c8f851a17b60 to your computer and use it in GitHub Desktop.
Save idlehands/9ef4b2690b723be817d3c8f851a17b60 to your computer and use it in GitHub Desktop.
macro for validating ecto schema fields
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
@idlehands
Copy link
Author

I typically paste this code into my DataCase

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment