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 UserController.
To do this we're going to simulate requests by calling get/3, put/3, delete/3, post/3, etc. Those functions simulate a dispatch to an endpoint in your app without the need to go through HTTP using Phoenix.ConnTest.
The first thing you'll notice is the use PhoenixChat.ConnCase. This module comes by default in 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.
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.
defmodule PhoenixChat.UserControllerTest do use PhoenixChat.ConnCase alias PhoenixChat.User @valid_attrs %{email: "me@test.com", password: "some content", username: "some content"} @invalid_attrs %{} ...endPhoenixChat.ConnCase provides us with a default setup block that passes a 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.
setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} endThe next block is our first test. Note that %{conn: conn} is the second argument to test/3 (docs), which is a pattern-match on the map passed by the setup block (the first argument is the string that describes the test and the third argument is do block). A more detailed explanation below the code.
test "lists all entries on index", %{conn: conn} do conn = get conn, user_path(conn, :index) assert json_response(conn, 200)["data"] == []endIn the first line of our test, we simulate the get request (docs) for users.index and update our conn with that information.
Then we assert that the json response (docs) returned by 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.
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 create_user instead of a full 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.
We're going to add create_user/1 and create_user/2 to our test/support/conn_case.ex file. If you open that file up, you'll see a block called using. This using block is what gets added every time you add the use keyword to a module. So in the example of our UserControllerTest above, by adding 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.
... using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias PhoenixChat.Repo import Ecto import Ecto.Changeset import Ecto.Query, only: [from: 1, from: 2] import PhoenixChat.Router.Helpers # The default endpoint for testing @endpoint PhoenixChat.Endpoint end end ...So now let's add the create_user functions and the necessary aliases to the file, and import PhoenixChat.ConnCase into our 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 import, it ignores the using block, so by importing PhoenixChat.ConnCase into this block, we've just added the two create_user functions into any module that uses use PhoenixChat.ConnCase.
defmodule PhoenixChat.ConnCase do use ExUnit.CaseTemplate alias PhoenixChat.{Repo, User} using do quote do ... import PhoenixChat.ConnCase # The default endpoint for testing @endpoint PhoenixChat.Endpoint end end ... def create_user!() do Repo.insert! %User{username: "foo", email: "foo@bar.com"} end def create_user!(attrs) do map = Map.merge(%{username: "foo", email: "foo@bar.com"}, attrs) struct = struct(User, map) Repo.insert! struct endendIn 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 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 (docs) the password field since we do not store plain text passwords in our database.
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.
test "creates and renders resource when data is valid", %{conn: conn} do conn = post conn, user_path(conn, :create), user: @valid_attrs assert json_response(conn, 201)["data"]["id"] assert Repo.get_by(User, Map.drop(@valid_attrs, [:password]))endThe second line runs a post/2 (docs) request with the conn and user_path, which is an automatically generated helper for calling our user route (docs). We're asking that route to render :create, which you can see in your UserView.
If you want to see all your helpers, run the following and you will see all routes, with their helpers on the left.
$ mix phoenix.routespage_path GET / PhoenixChat.PageController :indexuser_path GET /api/users PhoenixChat.UserController :index...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.
test "does not create resource and renders errors when data is invalid", %{conn: conn} do conn = post conn, user_path(conn, :create), user: @invalid_attrs assert json_response(conn, 422)["errors"] != %{}endWe're also asserting that we get the proper error when an id is not present. Asserting errors is simple. We use assert_error_sent/2, along with the error code we expect and a function that should generate the error. In the case below, since there is no id of -1, it should give us an error. Your generator should have created this for you as well.
Now we're going to test our :update function. Everything here is the same the previous test in which we tested :create.
test "updates and renders chosen resource when data is valid", %{conn: conn} do user = create_user! conn = put conn, user_path(conn, :update, user), user: @valid_attrs assert json_response(conn, 200)["data"]["id"] assert Repo.get_by(User, Map.drop(@valid_attrs, [:password]))endNow we need to test the opposite and make sure it doesn't work with invalid parameters.
test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do user = create_user! conn = put conn, user_path(conn, :update, user), user: %{email: "foo"} assert json_response(conn, 422)["errors"] != %{}endAnd for our last test, we're going to make sure that we can delete a user bu calling :delete and making sure that we get a negative result from a Repo.get query by using refute.
test "deletes chosen resource", %{conn: conn} do user = create_user! conn = delete conn, user_path(conn, :delete, user) assert response(conn, 204) refute Repo.get(User, user.id)endWe have a lot to test in our AuthController. We aren't going to test the internals of things like Comeonin or Guardian because it's safe to assume those will work.
$ touch test/controllers/auth_controller_test.exsJust like we did with our previous tests, we need to set up our valid attributes and a setup block. This is almost identical to our other controller.
defmodule PhoenixChat.AuthControllerTest do use PhoenixChat.ConnCase alias PhoenixChat.User @valid_attrs %{email: "me@test.com", password: "password", username: "test"} @invalid_attrs %{} setup do {:ok, conn: put_req_header(build_conn, "accept", "application/json")} endendNow it's time to test our authentication routes. We're going to nest some of these tests within a describe block so we can group similar tests.
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.
In the first line, we create a user with valid attributes, then make a post request to /auth/identity/callback with the valid parameters to successfully create an account.
Then we assert that the response is 201, which means it was created successfully.
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 token so we can use it later.
In our next assertion, we take that token we received in our last assertion and use Guardian.decode_and_verify/1 to decode the token, which should work, and at the same time we are storing the response in claims.
Then we take that claims value and find the user.id that it's associated with. Check PhoenixChat.GuardianSerializer.for_token/1 to see what's stored in sub.
Then we just make sure that if we give bad values an account does not validate.
... describe "post '/auth/identity/callback'" do test "successful authentication returns JWT token", %{conn: conn} do user = User.registration_changeset(%User{}, @valid_attrs) |> Repo.insert! params = %{email: user.email, password: "password"} conn = post conn, "/auth/identity/callback", params response = json_response(conn, 201)["data"] assert response assert %{"username" => "test", "token" => token, "email" => "me@test.com"} = response assert {:ok, claims} = Guardian.decode_and_verify(token) assert claims["sub"] == "User:#{user.id}" end test "unsuccessful authentication", %{conn: conn} do params = %{email: "non@existent.com", password: "password"} conn = post conn, "/auth/identity/callback", params assert json_response(conn, 400) == "Internal server error" end end...Our next describe block will handle our /auth/me route. This route takes in a JWT via authorization header and checks to see if the token is valid.
First we need to create a user with valid parameters. Then we create a token by passing the connection through Guardian.
Now that we have a valid token, we can simulate passing it to our /auth/me route in the auth header. We then assert that the response we should receive is 200, which means it worked.
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 ^ does, it references a value above rather than use the value for assignment.
In the second test, we simply pass an invalid token and assert that the response is 401 unauthorized.
... describe "get '/auth/me'" do test "authorized user gets json response", %{conn: conn} do user = User.registration_changeset(%User{}, @valid_attrs) |> Repo.insert! token = conn |> Guardian.Plug.api_sign_in(user) |> Guardian.Plug.current_token conn = conn |> put_req_header("authorization", "Bearer #{token}") |> get("/auth/me") response = json_response(conn, 200)["data"] assert response %{email: email, id: id, username: username} = user assert %{"email" => ^email, "id" => ^id, "username" => ^username} = response end test "unauthorized user", %{conn: conn} do conn = conn |> put_req_header("authorization", "Bearer fake_token") |> get("/auth/me") assert json_response(conn, 401) == "Internal server error" end end...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.
config :comeonin, :bcrypt_log_rounds, 4config :comeonin, :pbkdf2_rounds, 1If this is not your first time through the course, you might run into an error when you run mix test.
** (Postgrex.Error) ERROR (duplicate_table): relation "users" already exists...If you run into this error, run 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.