|
| 1 | +defmodule CodeCorps.UserRoleControllerTest do |
| 2 | + use CodeCorps.ConnCase |
| 3 | + |
| 4 | + alias CodeCorps.UserRole |
| 5 | + alias CodeCorps.Repo |
| 6 | + |
| 7 | + setup do |
| 8 | + conn = |
| 9 | + %{build_conn | host: "api."} |
| 10 | + |> put_req_header("accept", "application/vnd.api+json") |
| 11 | + |> put_req_header("content-type", "application/vnd.api+json") |
| 12 | + |
| 13 | + {:ok, conn: conn} |
| 14 | + end |
| 15 | + |
| 16 | + defp attributes do |
| 17 | + %{} |
| 18 | + end |
| 19 | + |
| 20 | + defp relationships(user, role) do |
| 21 | + %{ |
| 22 | + user: %{data: %{id: user.id}}, |
| 23 | + role: %{data: %{id: role.id}} |
| 24 | + } |
| 25 | + end |
| 26 | + |
| 27 | + test "creates and renders resource when data is valid", %{conn: conn} do |
| 28 | + user = insert_user(%{email: "test-user@mail.com"}) |
| 29 | + role = insert_role(%{title: "test-role"}) |
| 30 | + |
| 31 | + conn = post conn, user_role_path(conn, :create), %{ |
| 32 | + "meta" => %{}, |
| 33 | + "data" => %{ |
| 34 | + "type" => "user-role", |
| 35 | + "attributes" => attributes, |
| 36 | + "relationships" => relationships(user, role) |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + json = json_response(conn, 201) |
| 41 | + |
| 42 | + id = json["data"]["id"] |> String.to_integer |
| 43 | + user_role = UserRole |> Repo.get!(id) |
| 44 | + |
| 45 | + assert json["data"]["id"] == "#{user_role.id}" |
| 46 | + assert json["data"]["type"] == "user-role" |
| 47 | + assert json["data"]["relationships"]["user"]["data"]["id"] == "#{user.id}" |
| 48 | + assert json["data"]["relationships"]["role"]["data"]["id"] == "#{role.id}" |
| 49 | + end |
| 50 | + |
| 51 | + test "does not create resource and renders errors when data is invalid", %{conn: conn} do |
| 52 | + conn = post conn, user_role_path(conn, :create), %{ |
| 53 | + "meta" => %{}, |
| 54 | + "data" => %{ |
| 55 | + "type" => "user-role", |
| 56 | + "attributes" => attributes, |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + assert json_response(conn, 422)["errors"] != %{} |
| 61 | + end |
| 62 | + |
| 63 | + test "deletes resource", %{conn: conn} do |
| 64 | + role = insert_role(%{title: "test-role"}) |
| 65 | + user = insert_user(%{email: "test-user@mail.com"}) |
| 66 | + user_role = insert_user_role(%{user_id: user.id, role_id: role.id}) |
| 67 | + response = delete conn, user_role_path(conn, :delete, user_role) |
| 68 | + |
| 69 | + assert response.status == 204 |
| 70 | + end |
| 71 | +end |
0 commit comments