After running mix phx.gen.live Catalog Product products name:string \ description:string unit_price:float sku:integer:unique
to create the Catalog and updating router.ex
, running mix test
results in hundreds of failed tests (113) due to usernames being too long (+20 chars).
Example error:
** (MatchError) no match of right hand side value: {:error, #Ecto.Changeset<action: :insert, changes: %{username: "user-576460752303421560", password: "**redacted**", email: "user-576460752303421592@example.com"}, errors: [username: {"should be at most %{count} character(s)", [count: 20, validation: :length, kind: :max, type: :string]}], data: #Pento.Accounts.User<>, valid?: false, ...>}
stacktrace:
(pento 0.1.0) test/support/fixtures/accounts_fixtures.ex:20: Pento.AccountsFixtures.user_fixture/1
test/pento/accounts_test.exs:336: Pento.AccountsTest.__ex_unit_setup_12_0/1
Pento.AccountsTest.__ex_unit_describe_12/1
This is because the unique_username()
function in accounts_fixtures.ex
generates usernames like "user#{System.unique_integer()}"
, but System.unique_integer()
can return very large numbers (ex: 576460752303421560
). This creates usernames longer than 20 characters, but the User
schema has a validation that limits usernames to a maximum of 20 characters:
|> validate_length(:username, min: 3, max: 20)
My fix involves truncating usernames & emails via rem
like so:
def unique_user_email, do: "user#{System.unique_integer() |> rem(1_000_000)}@example.com"
def unique_username, do: "user#{System.unique_integer() |> rem(1_000_000)}"
I’m using the following versions:
elixir = "1.18.4-otp-27"
erlang = "27.3.4.1"