I have a controller with a create function that looks like this:
def create(conn, %{"data" => refinement_params}) do
case Repo.insert %Refinement{ refinement_code: refinement_params["refinement_code"], team_name: refinement_params["team_name"], organization_id: conn.assigns[:organization_id]} do
{:ok, model} -> json conn, %{refinement_code: model.refinement_code}
{:error, changeset} -> conn |> send_resp(500, "")
end
end
I have a validate_length(:refinement_code, min: 5) clause in the changeset of the model. If I post using a web REST tool to the controller with an empty refinement_code, I get a 500 response back as expected.
In the tests for the controller, I have the following:
@invalid_attrs %{refinement_code: "", team_name: ""}
test "/api call to create a voting session with creds but invalid data gets an error code", %{conn: conn} do
organization = Repo.insert! %Organization{domain: "test.com", email: "[email protected]"}
conn = recycle(conn)
|> put_req_header("unique_code", organization.unique_code)
|> put_req_header("domain", organization.domain)
conn = post conn, "/api/refinements", data: @invalid_attrs
assert conn.status == 500
end
In this case, the conn.status is a 200 for some reason. Why is the test incorrectly failing?
You're not using the changeset in the controller action, so validations won't be run. I would check the logs for some other reason your web requests are failing.
To make your controller action use the changeset and its validations, you want to use something like this:
changeset = Refinement.changeset(%Refinement{}, refinement_params)
case Repo.insert(changeset) do
....