Advertisement
Guest User

Untitled

a guest
Oct 17th, 2016
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. defmodule Storybook.UserRepoTest do
  2. use Storybook.ModelCase
  3. alias Storybook.User
  4.  
  5. @valid_attrs %{email: "email@test.com", username: "user", password: "password"}
  6. @test_attrs %{email: "different_email@test.com", username: "different_user", password: "different_password"}
  7.  
  8. test "converts unique_constraint on username to error" do
  9. %User{}
  10. |> User.registration_changeset(@valid_attrs)
  11. |> Repo.insert!()
  12.  
  13. attrs = Map.put(@test_attrs, :username, "user")
  14. changeset = User.registration_changeset(%User{}, attrs)
  15.  
  16. assert {:error, changeset} = Repo.insert(changeset)
  17. assert {:username, {"has already been taken", []}} in changeset.errors
  18. end
  19. end
  20.  
  21.  
  22. defmodule Storybook.User do
  23. use Storybook.Web, :model
  24.  
  25. schema "users" do
  26. field :email, :string
  27. field :name, :string
  28. field :username, :string
  29. field :password, :string, virtual: true
  30. field :password_hash, :string
  31.  
  32. timestamps()
  33. end
  34.  
  35. @doc """
  36. Builds a changeset based on the `struct` and `params`.
  37. """
  38. def changeset(struct, params \\ %{}) do
  39. struct
  40. |> cast(params, [:email, :username])
  41. |> validate_required([:email, :username])
  42. |> validate_length(:username, max: 40)
  43. |> unique_constraint(:username)
  44. |> unique_constraint(:email)
  45. end
  46.  
  47. def registration_changeset(struct, params \\ %{}) do
  48. struct
  49. |> changeset(params)
  50. |> cast(params, [:password])
  51. |> validate_required([:password])
  52. |> validate_length(:password, min: 6)
  53. |> put_password_hash()
  54. end
  55.  
  56. defp put_password_hash(changeset) do
  57. case changeset do
  58. %Ecto.Changeset{valid?: true, changes: %{password: password}} ->
  59. put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(password))
  60. _ ->
  61. changeset
  62. end
  63. end
  64. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement