Controllers Test's conn is being redirect, but why?

Hello! I’m writing some tests to my controllers but I’m having some trouble with they.
All controllers’s tests are being redirect to somewhere else, resulting into a 307 HTTP error, that’s fails all the tests.

this is one of my controller test:

defmodule SysbovApiWeb.User.UserControllerTest do
  use SysbovApiWeb.ConnCase, async: true

  describe "create/2" do
    test "return 201 when all params are valid", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "email" => "matheus_pessanha2001@outlook.com",
          "first_name" => "Matheus",
          "last_name" => "de Souza Pessanha",
          "password" => "mdsp9070",
          "password_confirmation" => "mdsp9070"
        })

      assert %{
               "user" => %{
                 "id" => _,
                 "role" => _,
                 "email" => _,
                 "first_name" => _,
                 "last_name" => _,
                 "payment" => _,
                 "farm" => _
               }
             } = json_response(conn, 201)
    end

    test "returns 400 when email is blank", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "first_name" => "Matheus",
          "last_name" => "de Souza Pessanha",
          "password" => "mdsp9070",
          "password_confirmation" => "mdsp9070"
        })

      assert %{"errors" => _} = json_response(conn, 400)
    end

    test "returns 400 when email is invalid", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "first_name" => "Matheus",
          "last_name" => "de Souza Pessanha",
          "password" => "mdsp9070",
          "password_confirmation" => "mdsp9070"
        })

      assert %{"errors" => _} = json_response(conn, 400)
    end

    test "returns 400 when first_name is blank", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "email" => "matheus_pessanha2001@outlook.com",
          "last_name" => "de Souza Pessanha",
          "password" => "mdsp9070",
          "password_confirmation" => "mdsp9070"
        })

      assert %{"errors" => _} = json_response(conn, 400)
    end

    test "returns 400 when last_name is blank", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "email" => "matheus_pessanha2001@outlook.com",
          "first_name" => "Matheus",
          "password" => "mdsp9070",
          "password_confirmation" => "mdsp9070"
        })

      assert %{"errors" => _} = json_response(conn, 400)
    end

    test "returns 400 when password is blank", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "email" => "matheus_pessanha2001@outlook.com",
          "first_name" => "Matheus",
          "last_name" => "de Souza Pessanha",
          "password_confirmation" => "mdsp9070"
        })

      assert %{"errors" => _} = json_response(conn, 400)
    end

    test "returns 400 when password_confirmation is blank", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "email" => "matheus_pessanha2001@outlook.com",
          "first_name" => "Matheus",
          "last_name" => "de Souza Pessanha",
          "password" => "mdsp9070"
        })

      assert %{"errors" => _} = json_response(conn, 400)
    end

    test "returns 400 when passwords not match", %{conn: conn} do
      conn =
        post(conn, "/api/v1/users", %{
          "email" => "matheus_pessanha2001@outlook.com",
          "first_name" => "Matheus",
          "last_name" => "de Souza Pessanha",
          "password" => "mdsp9070"
        })

      assert %{"errors" => _} = json_response(conn, 400)
    end
  end
end

this is my router:

defmodule SysbovApiWeb.Router do
  use SysbovApiWeb, :router

  pipeline :api do
    plug :accepts, ["json"]
  end

  pipeline :api_as_user do
    plug :accepts, ["json"]
    plug SysbovApiWeb.AuthAccessPipeline
  end

  scope "/api/v1", SysbovApiWeb do
    pipe_through :api

    post "/users/sessions", User.SessionController, :create
    post "/users", User.UserController, :create
  end

  scope "/api/v1", SysbovApiWeb do
    pipe_through :api_as_user

    post "/farms", Farm.FarmController, :create
    get "/farms/:farm_id", Farm.FarmController, :show
    delete "/farms/:farm_id", Farm.FarmController, :delete
    post "/farms/animals", Animals.AnimalsController, :create
    get "/farms/animals", Animals.AnimalsController, :index
    get "/farm/animals/:animal_id", Animals.AnimalsController, :show
    delete "/farms/animals/:animal_id", Animals.AnimalsController, :delete
  end

  # Enables LiveDashboard only for development
  #
  # If you want to use the LiveDashboard in production, you should put
  # it behind authentication and allow only admins to access it.
  # If your application does not have an admins-only section yet,
  # you can use Plug.BasicAuth to set up some basic authentication
  # as long as you are also using SSL (which you should anyway).
  if Mix.env() in [:dev, :test] do
    import Phoenix.LiveDashboard.Router

    scope "/" do
      pipe_through [:fetch_session, :protect_from_forgery]
      live_dashboard "/dashboard", metrics: SysbovApiWeb.Telemetry
    end
  end
end

and this is my conn_case:

defmodule SysbovApiWeb.ConnCase do
  @moduledoc """
  This module defines the test case to be used by
  tests that require setting up a connection.

  Such tests rely on `Phoenix.ConnTest` and also
  import other functionality to make it easier
  to build common data structures and query the data layer.

  Finally, if the test case interacts with the database,
  we enable the SQL sandbox, so changes done to the database
  are reverted at the end of every test. If you are using
  PostgreSQL, you can even run database tests asynchronously
  by setting `use SysbovApiWeb.ConnCase, async: true`, although
  this option is not recommended for other databases.
  """

  alias Ecto.Adapters.SQL.Sandbox

  use ExUnit.CaseTemplate

  using do
    quote do
      # Import conveniences for testing with connections
      import Plug.Conn
      import Phoenix.ConnTest
      import SysbovApiWeb.ConnCase

      alias SysbovApiWeb.Router.Helpers, as: Routes

      # The default endpoint for testing
      @endpoint SysbovApiWeb.Endpoint
    end
  end

  setup tags do
    :ok = Sandbox.checkout(SysbovApi.Repo)

    unless tags[:async] do
      Sandbox.mode(SysbovApi.Repo, {:shared, self()})
    end

    {:ok, conn: Phoenix.ConnTest.build_conn()}
  end
end

What I’m doing wrong?

The only place I see in the standard Phoenix plumbing that would generate a 307 is Plug.SSL, but I wouldn’t think that would be running in this situation…

Is there any code in User.UserController that sends that status code?

1 Like

No, any code that returns 307! Always 200, 201, 400 or 500

Try looking at conn.resp_body and conn.resp_headers to see if there are any clues about why it is being redirected. You can also try running the tests with logging enabled (set the level to :debug in config/test.exs) as they usually include who is redirecting.

3 Likes

:debug level gave the answer!

09:38:51.960 [info] Plug.SSL is redirecting POST /api/v1/users to https://www.example.com with status 307

There’s any config that I’m supposed to do?

What does the response look like? In particular, what is the Location header that’s being sent?

1 Like
resp_headers: [
    {"cache-control", "max-age=0, private, must-revalidate"},
    {"location", "https://www.example.com/api/v1/users"}
  ],

I added force_ssl config on my config.exs, moving it to prod.exs the tests runnned successfully. Thank you all.

1 Like