Testing the Error Case for Create

Learn how to write an error case test for the create endpoint.

An error test for create

We can complete our coverage of this endpoint and controller action by testing a failure case. Inside the same describe block POST /users, and under our previous test, add this:

Press + to interact
#file path -> test/not_skull_web/controllers/user_controller_test.exs
#add this code at the indicated place mentioned in comments of test/not_skull_web/
#controllers/user_controller_test.exs in the playground widget
test "error: does not insert, redirects to 'new' page w/invalid attributes",
%{
conn: conn
} do
flunk_if_email_is_sent()
expected_user_count = Repo.all(User) |> Enum.count()
conn = post(conn, Routes.user_path(conn, :create), user: %{})
assert html = html_response(conn, 200)
parsed_html = Floki.parse_document!(html)
for field <- ["name", "email", "password"] do
# using <> so that the first #(indicating an id) is easy to read
field_as_id = "#" <> "#{field}-error"
span = Floki.find(parsed_html, field_as_id)
assert Floki.text(span) == "can't be blank"
end
assert Repo.all(User) |> Enum.count() == expected_user_count,
"There should have been no records inserted during this test."
end

Let’s see the details of the test:

  • The test leverages a new custom helper function called flunk_if_email_is_sent/0, on line 8, that’s defined in NotSkull.ConnCase, right next to our other helper function.

Note: Because our test is a failure case, it needs to make sure that no new users were created as a side effect.

  • On line 10, the test is getting the pre-exercise count of users in the database. This allows us to assert at the end of the test (line ...