Phoenix.NotAcceptableError on JSON API test

Hi,

I’m having trouble testing a JSON based API controller. It works fine in the browser, but all tests are throwing the same error.

I’ve created it using

mix phoenix.gen.json Api.Account accounts --no-model

The account model is working and it’s all tested.

Here’s my router.ex (only the relevant parts)

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

...

scope "/api/v1", MyApp do
    pipe_through :api
    resources "/accounts", Api.AccountController, except: [:new, :edit]
end

Using my browser, I can go /api/v1/accounts and se the json being rendered correctly.

However, when I try to run my tests (generated by phoenix.gen.json), I get the following error in every single test:

mix test test/controllers/api/account_controller_test.exs

Output:

** (Phoenix.NotAcceptableError) no supported media type in accept header, expected one of ["html"]

And here’s a portion of my test script:

setup %{conn: conn} do
    conn = conn |> put_req_header("accept", "application/json")
    {:ok, conn: conn}    
end

...

test "lists all entries on index", %{conn: conn} do
    conn = get conn, account_path(conn, :index)
    assert json_response(conn, 200)["data"] == []
end

What am I missing here?

Thanks in advance :slight_smile:

Following this documentation i figured out the problem.

In my router.ex file, I was defining

resources "/accounts", AccountController

And also

scope "/api/v1", MyApp.Api do
   pipe_through :api
   resources "/accounts", AccountController, except: [:new, :edit]
end

Both were generating the acount_path path helper. So, I just had to add a prefix to all API routes, using as: :api in my API scope:

scope "/api/v1", MyApp.Api, as: :api do
    pipe_through :api
    resources "/accounts", AccountController, except: [:new, :edit]
end

This will make all my path helpers of routes under /api/v1 start with api, like api_account_path.

In the controller test I just changed from account_path (that was pointing to the HTML version of the controller) to api_account_path and everything worked :slight_smile:

2 Likes

This is the key. :+1: