Add test support for default role assignment

This commit is contained in:
Moritz 2026-01-24 19:13:15 +01:00
parent 9557d8ae6b
commit 3b5b5044fb
Signed by: moritz
GPG key ID: 1020A035E5DD0824
2 changed files with 84 additions and 0 deletions

View file

@ -182,6 +182,56 @@ defmodule Mv.Fixtures do
user_with_role
end
@doc """
Creates a user with password authentication and a specific role.
This is useful for tests that need to use password-based registration
but also require the user to have a role for authorization.
## Parameters
- `email` - User email (defaults to unique generated email)
- `password` - User password (defaults to "testpassword123")
- `permission_set_name` - The permission set name (defaults to "own_data")
## Returns
- User struct with role preloaded
## Examples
iex> user = password_user_with_role_fixture()
iex> user.role.permission_set_name
"own_data"
"""
def password_user_with_role_fixture(opts \\ %{}) do
email = Map.get(opts, :email, "user#{System.unique_integer([:positive])}@example.com")
password = Map.get(opts, :password, "testpassword123")
permission_set_name = Map.get(opts, :permission_set_name, "own_data")
# Create role with permission set
role = role_fixture(permission_set_name)
# Create user with password (without password_confirmation as it's optional)
{:ok, user} =
Mv.Accounts.User
|> Ash.Changeset.for_create(:register_with_password, %{
email: email,
password: password
})
|> Ash.create()
# Assign role to user
{:ok, user} =
user
|> Ash.Changeset.for_update(:update, %{})
|> Ash.Changeset.manage_relationship(:role, role, type: :append_and_remove)
|> Ash.update()
# Reload user with role preloaded
{:ok, user_with_role} = Ash.load(user, :role, domain: Mv.Accounts)
user_with_role
end
@doc """
Creates a member with an actor (for use in tests with policies).