When testing controllers it can be useful to have some data in the test database. And sometimes you might want to test the data creation. What is the correct way to set this up? A test for controllers should test if the create function of the controller is working, not the model.
As an example I want to test a Session controller and I have two tests. One is testing that a created user can login. The other that he cannot if the password is wrong. Both rely on a user being in the database. How I deal with it now is to create the user first:
defmodule MyApp.SessionControllerTest do
use MyApp.ConnCase
alias MyApp.Admin
@valid_attrs %{email: "[email protected]", name: "John Doe", password: "goodpassword", password_confirmation: "goodpassword", password_hash: "somecontent", username: "username"}
@invalid_attrs %{}
setup do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
test "admin can login after creation" do
conn = post conn, admin_path(conn, :create), admin: @valid_attrs
body = json_response(conn, 201)
assert Repo.get_by(Admin, email: @valid_attrs[:email])
conn = post conn, session_path(conn, :create), %{data: %{attributes: %{email: @valid_attrs[:email], password: @valid_attrs[:password]}}}
body = json_response(conn, 201)
assert body["data"]["token"]
end
test "login with wrong password returns an error" do
conn = post conn, session_path(conn, :create), %{data: %{attributes: %{email: @valid_attrs[:email], password: "wrongpassword"}}}
body = json_response(conn, 403)
assert body["error"]
end
end
If I now add a uniqueness restrain on my Admin model this could potentially get messy since whenever I need a user in the database I have to make sure that the test isn't failing because of this constraint but because something in the tested controller is wrong. Also it isn't clear in which order the tests are run and staying consistent with the data creation over several tests seems like a nightmare.
I either want one place where I define in the beginning which Data is created. Or use mocks for Controller testing.
How is this possible?