{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/testing-with-elixir-and-phoenix-controllers","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Testing with Elixir and Phoenix: Controllers\",\n  \"order\": 38,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\", \"elixir\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Testing with Elixir and Phoenix: Controllers\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"UserController tests\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Metaprogramming\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"AuthController tests\")), mdx(\"p\", null, \"We've already gone over the basics of testing in a previous lesson with React, so in this lesson we'll jump right into testing your Phoenix app. We're going to start by testing our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserController\"), \".\"), mdx(\"p\", null, \"To do this we're going to simulate requests by calling \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"get/3\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put/3\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"delete/3\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"post/3\"), \", etc. Those functions simulate a dispatch to an endpoint in your app without the need to go through HTTP using \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.ConnTest.html.\",\n    \"parentName\": \"p\"\n  }, \"Phoenix.ConnTest\"), \".\"), mdx(\"h2\", null, \"UserController tests\"), mdx(\"p\", null, \"The first thing you'll notice is the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"use PhoenixChat.ConnCase\"), \". This module comes by default in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test/support/conn_case.ex\"), \" and it's worth looking it over to get a sense of what it's providing to you on every test.\"), mdx(\"p\", null, \"Now in order to save us some keystrokes, we're going to create two variables at the top of the file. One is for valid user attributes and one for invalid. Generally speaking, when we pass valid attributes, we expect things to pass, while invalid values should give us an error.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserControllerTest do\\n  use PhoenixChat.ConnCase\\n\\n  alias PhoenixChat.User\\n  @valid_attrs %{email: \\\"me@test.com\\\", password: \\\"some content\\\", username: \\\"some content\\\"}\\n  @invalid_attrs %{}\\n\\n  ...\\n\\nend\\n\")), mdx(\"p\", null, mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat.ConnCase\"), \" provides us with a default \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"setup\"), \" block that passes a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"conn\"), \" struct, just like we would have in our actual Controller. From there, we can add things to it, such as headers. As it happens, this is already set up for us from our generator, but it should look like the code below.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  setup %{conn: conn} do\\n    {:ok, conn: put_req_header(conn, \\\"accept\\\", \\\"application/json\\\")}\\n  end\\n\")), mdx(\"p\", null, \"The next block is our first test. Note that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"%{conn: conn}\"), \" is the second argument to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test/3\"), \" \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/docs/stable/ex_unit/ExUnit.Case.html#test/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \", which is a pattern-match on the map passed by the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"setup\"), \" block (the first argument is the string that describes the test and the third argument is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"do\"), \" block). A more detailed explanation below the code.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"lists all entries on index\\\", %{conn: conn} do\\n  conn = get conn, user_path(conn, :index)\\n  assert json_response(conn, 200)[\\\"data\\\"] == []\\nend\\n\")), mdx(\"p\", null, \"In the first line of our test, we simulate the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"get\"), \" request \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.ConnTest.html#get/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"users.index\"), \" and update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"conn\"), \" with that information.\"), mdx(\"p\", null, \"Then we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assert\"), \" that the json response \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.ConnTest.html#json_response/2\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" returned by \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"users.index\"), \" was successful (status code 200) and is an empty list, which is the result we should expect since the database has no user records.\"), mdx(\"h2\", null, \"Metaprogramming\"), mdx(\"p\", null, \"In the next test, we create a user, then check to make sure that the user was added. So in order to make our lives easier, we're going to create a utility function to create a user. This will allow us to call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create_user\"), \" instead of a full \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.insert/1\"), \" command each time. And since we're going to use this function across multiple controllers, we're going to dig a little deeper into Phoenix to make this function reusable.\"), mdx(\"p\", null, \"We're going to add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create_user/1\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create_user/2\"), \" to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test/support/conn_case.ex\"), \" file. If you open that file up, you'll see a block called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"using\"), \". This \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"using\"), \" block is what gets added every time you add the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"use\"), \" keyword to a module. So in the example of our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserControllerTest\"), \" above, by adding \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"use PhoenixChat.ConnCase\"), \", we have effectively imported everything within this block. This is what is known as metaprogramming in Elixir. It's abstraction layer upon abstraction layer.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n  using do\\n    quote do\\n      # Import conveniences for testing with connections\\n      use Phoenix.ConnTest\\n\\n      alias PhoenixChat.Repo\\n      import Ecto\\n      import Ecto.Changeset\\n      import Ecto.Query, only: [from: 1, from: 2]\\n\\n      import PhoenixChat.Router.Helpers\\n\\n      # The default endpoint for testing\\n      @endpoint PhoenixChat.Endpoint\\n    end\\n  end\\n  ...\\n\")), mdx(\"p\", null, \"So now let's add the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create_user\"), \" functions and the necessary aliases to the file, and import \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat.ConnCase\"), \" into our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"using\"), \" block. You might be thinking that we've created an infinite loop by importing a module into itself, which imports itself into itself... but when you use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"import\"), \", it ignores the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"using\"), \" block, so by importing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat.ConnCase\"), \" into this block, we've just added the two \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"create_user\"), \" functions into any module that uses \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"use PhoenixChat.ConnCase\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.ConnCase do\\n  use ExUnit.CaseTemplate\\n\\n  alias PhoenixChat.{Repo, User}\\n\\n  using do\\n    quote do\\n\\n      ...\\n\\n      import PhoenixChat.ConnCase\\n\\n      # The default endpoint for testing\\n      @endpoint PhoenixChat.Endpoint\\n    end\\n  end\\n\\n  ...\\n\\n  def create_user!() do\\n    Repo.insert! %User{username: \\\"foo\\\", email: \\\"foo@bar.com\\\"}\\n  end\\n\\n  def create_user!(attrs) do\\n    map = Map.merge(%{username: \\\"foo\\\", email: \\\"foo@bar.com\\\"}, attrs)\\n    struct = struct(User, map)\\n    Repo.insert! struct\\n  end\\nend\\n\")), mdx(\"p\", null, \"In our test, we're going to simulate a post request with valid parameters to create a new user, then assert that we get the appropriate \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"201\"), \" response for account creation and that we can find the user in the database. For our query to work, we're going to drop \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/docs/stable/elixir/Map.html#drop/2\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" the password field since we do not store plain text passwords in our database.\"), mdx(\"p\", null, \"To clarify, we're running two assertions to test this functionality. First we're making sure that our post request worked, then we're making sure that the database was properly updated with the value.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"creates and renders resource when data is valid\\\", %{conn: conn} do\\n  conn = post conn, user_path(conn, :create), user: @valid_attrs\\n  assert json_response(conn, 201)[\\\"data\\\"][\\\"id\\\"]\\n  assert Repo.get_by(User, Map.drop(@valid_attrs, [:password]))\\nend\\n\")), mdx(\"p\", null, \"The second line runs a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"post/2\"), \" \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/docs/stable/elixir/Process.html#get/2\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" request with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"conn\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_path\"), \", which is an automatically generated helper for calling our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" route \", mdx(\"a\", {\n    \"href\": \"https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/router/helpers.ex\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \". We're asking that route to render \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":create\"), \", which you can see in your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserView\"), \".\"), mdx(\"p\", null, \"If you want to see all your helpers, run the following and you will see all routes, with their helpers on the left.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.routes\\n\\npage_path  GET   /           PhoenixChat.PageController :index\\nuser_path  GET   /api/users  PhoenixChat.UserController :index\\n...\\n\")), mdx(\"p\", null, \"Then we need to test to make sure that invalid attributes fails the way we want. This should already be in place from our generator.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"does not create resource and renders errors when data is invalid\\\", %{conn: conn} do\\n  conn = post conn, user_path(conn, :create), user: @invalid_attrs\\n  assert json_response(conn, 422)[\\\"errors\\\"] != %{}\\nend\\n\")), mdx(\"p\", null, \"We're also asserting that we get the proper error when an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" is not present. Asserting errors is simple. We use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assert_error_sent/2\"), \", along with the \", mdx(\"a\", {\n    \"href\": \"https://github.com/elixir-lang/plug/blob/master/lib/plug/conn/status.ex\",\n    \"parentName\": \"p\"\n  }, \"error code\"), \" we expect and a function that should generate the error. In the case below, since there is no \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"-1\"), \", it should give us an error. Your generator should have created this for you as well.\"), mdx(\"p\", null, \"Now we're going to test our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":update\"), \" function. Everything here is the same the previous test in which we tested \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":create\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"updates and renders chosen resource when data is valid\\\", %{conn: conn} do\\n  user = create_user!\\n  conn = put conn, user_path(conn, :update, user), user: @valid_attrs\\n  assert json_response(conn, 200)[\\\"data\\\"][\\\"id\\\"]\\n  assert Repo.get_by(User, Map.drop(@valid_attrs, [:password]))\\nend\\n\")), mdx(\"p\", null, \"Now we need to test the opposite and make sure it doesn't work with invalid parameters.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"does not update chosen resource and renders errors when data is invalid\\\", %{conn: conn} do\\n  user = create_user!\\n  conn = put conn, user_path(conn, :update, user), user: %{email: \\\"foo\\\"}\\n  assert json_response(conn, 422)[\\\"errors\\\"] != %{}\\nend\\n\")), mdx(\"p\", null, \"And for our last test, we're going to make sure that we can delete a user bu calling \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":delete\"), \" and making sure that we get a negative result from a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.get\"), \" query by using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"refute\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"deletes chosen resource\\\", %{conn: conn} do\\n  user = create_user!\\n  conn = delete conn, user_path(conn, :delete, user)\\n  assert response(conn, 204)\\n  refute Repo.get(User, user.id)\\nend\\n\")), mdx(\"h2\", null, \"AuthController tests\"), mdx(\"p\", null, \"We have a lot to test in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AuthController\"), \". We aren't going to test the internals of things like \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Comeonin\"), \" or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Guardian\"), \" because it's safe to assume those will work.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch test/controllers/auth_controller_test.exs\\n\")), mdx(\"p\", null, \"Just like we did with our previous tests, we need to set up our valid attributes and a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"setup\"), \" block. This is almost identical to our other controller.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AuthControllerTest do\\n  use PhoenixChat.ConnCase\\n\\n  alias PhoenixChat.User\\n  @valid_attrs %{email: \\\"me@test.com\\\", password: \\\"password\\\", username: \\\"test\\\"}\\n  @invalid_attrs %{}\\n\\n  setup do\\n    {:ok, conn: put_req_header(build_conn, \\\"accept\\\", \\\"application/json\\\")}\\n  end\\n\\nend\\n\")), mdx(\"p\", null, \"Now it's time to test our authentication routes. We're going to nest some of these tests within a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"describe\"), \" block so we can group similar tests.\"), mdx(\"p\", null, \"For our first tests, we want to make sure that a successful authentication returns a JSON web token, since that's the whole point of our authorization route.\"), mdx(\"p\", null, \"In the first line, we create a user with valid attributes, then make a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"post\"), \" request to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/auth/identity/callback\"), \" with the valid parameters to successfully create an account.\"), mdx(\"p\", null, \"Then we assert that the response is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"201\"), \", which means it was created successfully.\"), mdx(\"p\", null, \"Then we're asserting that the response contained the parameters we want (username and email), and at the same time we are assigning the web token to the value \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"token\"), \" so we can use it later.\"), mdx(\"p\", null, \"In our next assertion, we take that token we received in our last assertion and use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Guardian.decode_and_verify/1\"), \" to decode the token, which should work, and at the same time we are storing the response in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"claims\"), \".\"), mdx(\"p\", null, \"Then we take that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"claims\"), \" value and find the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user.id\"), \" that it's associated with. Check \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat.GuardianSerializer.for_token/1\"), \" to see what's stored in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"sub\"), \".\"), mdx(\"p\", null, \"Then we just make sure that if we give bad values an account does not validate.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  describe \\\"post '/auth/identity/callback'\\\" do\\n    test \\\"successful authentication returns JWT token\\\", %{conn: conn} do\\n      user = User.registration_changeset(%User{}, @valid_attrs) |> Repo.insert!\\n      params = %{email: user.email, password: \\\"password\\\"}\\n      conn = post conn, \\\"/auth/identity/callback\\\", params\\n\\n      response = json_response(conn, 201)[\\\"data\\\"]\\n      assert response\\n\\n      assert %{\\\"username\\\" => \\\"test\\\", \\\"token\\\" => token, \\\"email\\\" => \\\"me@test.com\\\"} = response\\n      assert {:ok, claims} = Guardian.decode_and_verify(token)\\n      assert claims[\\\"sub\\\"] == \\\"User:#{user.id}\\\"\\n    end\\n\\n    test \\\"unsuccessful authentication\\\", %{conn: conn} do\\n      params = %{email: \\\"non@existent.com\\\", password: \\\"password\\\"}\\n      conn = post conn, \\\"/auth/identity/callback\\\", params\\n\\n      assert json_response(conn, 400) == \\\"Internal server error\\\"\\n    end\\n  end\\n...\\n\")), mdx(\"p\", null, \"Our next \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"describe\"), \" block will handle our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/auth/me\"), \" route. This route takes in a JWT via \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorization\"), \" header and checks to see if the token is valid.\"), mdx(\"p\", null, \"First we need to create a user with valid parameters. Then we create a token by passing the connection through \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Guardian\"), \".\"), mdx(\"p\", null, \"Now that we have a valid token, we can simulate passing it to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/auth/me\"), \" route in the auth header. We then assert that the response we should receive is 200, which means it worked.\"), mdx(\"p\", null, \"We're also going to assert that the response body returns the email, id, and the username of the user because our frontend expects those values. If you forgot what the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"^\"), \" does, it references a value above rather than use the value for assignment.\"), mdx(\"p\", null, \"In the second test, we simply pass an invalid token and assert that the response is 401 unauthorized.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  describe \\\"get '/auth/me'\\\" do\\n    test \\\"authorized user gets json response\\\", %{conn: conn} do\\n      user = User.registration_changeset(%User{}, @valid_attrs) |> Repo.insert!\\n      token = conn\\n              |> Guardian.Plug.api_sign_in(user)\\n              |> Guardian.Plug.current_token\\n\\n      conn = conn\\n             |> put_req_header(\\\"authorization\\\", \\\"Bearer #{token}\\\")\\n             |> get(\\\"/auth/me\\\")\\n\\n      response = json_response(conn, 200)[\\\"data\\\"]\\n      assert response\\n\\n      %{email: email, id: id, username: username} = user\\n      assert %{\\\"email\\\" => ^email, \\\"id\\\" => ^id, \\\"username\\\" => ^username} = response\\n    end\\n\\n    test \\\"unauthorized user\\\", %{conn: conn} do\\n      conn = conn\\n             |> put_req_header(\\\"authorization\\\", \\\"Bearer fake_token\\\")\\n             |> get(\\\"/auth/me\\\")\\n\\n      assert json_response(conn, 401) == \\\"Internal server error\\\"\\n    end\\n  end\\n...\\n\")), mdx(\"p\", null, \"And for the sake of optimization, we're going to give our test environment really bad keys so they generate faster. This will overwrite our normal configuration when in the test environment.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"config :comeonin, :bcrypt_log_rounds, 4\\nconfig :comeonin, :pbkdf2_rounds, 1\\n\")), mdx(\"h2\", null, \"Debugging\"), mdx(\"p\", null, \"If this is not your first time through the course, you might run into an error when you run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix test\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"** (Postgrex.Error) ERROR (duplicate_table): relation \\\"users\\\" already exists\\n...\\n\")), mdx(\"p\", null, \"If you run into this error, run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"MIX_ENV=test mix ecto.reset\"), \" to reset your test database. Ecto creates a separate database for your test environment, so just like on your actual app, when you start a new project and your migrations change, you need to drop and create a fresh database.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Testing with Elixir and Phoenix: Controllers UserController tests Metaprogramming AuthController tests We've already gone over the basics of…","frontmatter":{"title":"Testing with Elixir and Phoenix: Controllers","order":38,"active":true,"free":false,"tech":["phoenix","elixir"]}}},"pageContext":{"slug":"testing-with-elixir-and-phoenix-controllers","prevNode":{"frontmatter":{"title":"Transactional Email with Mailgun and Bamboo","active":true,"free":false,"order":37,"tech":["phoenix","elixir","mailgun"]},"fields":{"slug":"transactional-email-with-mailgun-and-bamboo"}},"nextNode":{"frontmatter":{"title":"Testing with Elixir and Phoenix: Channels","active":true,"free":false,"order":39,"tech":["phoenix","elixir"]},"fields":{"slug":"testing-with-elixir-and-phoenix-channels"}}}},"staticQueryHashes":["1723017916"]}