Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- defmodule Storybook.UserRepoTest do
- use Storybook.ModelCase
- alias Storybook.User
- @valid_attrs %{email: "email@test.com", username: "user", password: "password"}
- @test_attrs %{email: "different_email@test.com", username: "different_user", password: "different_password"}
- test "converts unique_constraint on username to error" do
- %User{}
- |> User.registration_changeset(@valid_attrs)
- |> Repo.insert!()
- attrs = Map.put(@test_attrs, :username, "user")
- changeset = User.registration_changeset(%User{}, attrs)
- assert {:error, changeset} = Repo.insert(changeset)
- assert {:username, {"has already been taken", []}} in changeset.errors
- end
- end
- defmodule Storybook.User do
- use Storybook.Web, :model
- schema "users" do
- field :email, :string
- field :name, :string
- field :username, :string
- field :password, :string, virtual: true
- field :password_hash, :string
- timestamps()
- end
- @doc """
- Builds a changeset based on the `struct` and `params`.
- """
- def changeset(struct, params \\ %{}) do
- struct
- |> cast(params, [:email, :username])
- |> validate_required([:email, :username])
- |> validate_length(:username, max: 40)
- |> unique_constraint(:username)
- |> unique_constraint(:email)
- end
- def registration_changeset(struct, params \\ %{}) do
- struct
- |> changeset(params)
- |> cast(params, [:password])
- |> validate_required([:password])
- |> validate_length(:password, min: 6)
- |> put_password_hash()
- end
- defp put_password_hash(changeset) do
- case changeset do
- %Ecto.Changeset{valid?: true, changes: %{password: password}} ->
- put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(password))
- _ ->
- changeset
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement