zoedsoupe

zoedsoupe

How do you implement integration tests for a Phoenix API?

That question maybe look as too generic but I really want to have an initial idea about how do you make integration/acceptance tests on a Phoenix API.

Some point are:

  • do you use any libraries or builtins function in ConnCase/ChannelCase are enough?
  • any suggestions with extra content and material about this topic and phoenix/elixir?
  • could you provide a simple example test that can’t be covered with Phoenix’s builtin functions

Marked As Solved

stefanchrobot

stefanchrobot

I write the integration tests in ExUnit which has the benefit of the tests being ran as part of the normal test suite. I abstract away any Phoenix helpers since they are taking some shortcuts. I follow the approach of Hex: we should be testing behaviours, not the implementation, but the unit of behaviour here is an API endpoint - it’s the public contract. I try to avoid shared setups as much as possible - this way the tests are self-contained. I invest into building helpers to combat code duplication. UserUI is a module with helpers that mimic user actions in the web app (creating account, sending a message, etc.). MobileApi is a module with helpers that basically do HTTP requests but are tailored to this specific API (API-key based auth with JSON). Example test with test helpers:

defmodule MobileApiTest do
  use MyApp.Case, async: true

  alias MyApp.TestHelpers.UserUI
  alias MyApp.TestHelpers.MobileApi

  describe "GET /api/mobile/messages" do
    test "lists messages sent to the person" do
      # Setup...
      account = UserUI.create_account!()
      message1 = UserUI.create_message!(account)
      # More setup...

      assert MobileApi.get("/api/mobile/messages", api_key) == %{
               status: 200,
               body: %{
                 "messages" => [
                   %{
                     "id" => message2.id,
                     "subject" => message2.subject,
                     "sent_at" => DateTime.to_iso8601(message2.inserted_at)
                   },
                   %{
                     "id" => message1.id,
                     "subject" => message1.subject,
                     "sent_at" => DateTime.to_iso8601(message1.inserted_at)
                   }
                 ]
               }
             }
    end

    test "returns 401 on expired API key" do
      # Setup...

      assert %{
               status: 401,
               body: %{"error" => "expired_api_key"}
             } = MobileApi.get("/api/mobile/messages", api_key)
    end
  end
end

defmodule MyApp.TestHelpers.MobileApi do
  @moduledoc """
  Test helpers for interacting with the mobile app API.
  """

  alias Plug.Conn
  alias Phoenix.ConnTest
  require Phoenix.ConnTest

  # The default endpoint for testing.
  @endpoint MyApp.Endpoint

  def get(url, api_key \\ nil) do
    %{status: status, resp_body: body} =
      api_key
      |> build_conn()
      |> ConnTest.get(url)

    %{status: status, body: if(body != "", do: Jason.decode!(body), else: "")}
  end

  defp build_conn(api_key) do
    conn =
      ConnTest.build_conn()
      |> Conn.put_req_header("accept", "application/json")

    if api_key do
      conn |> Conn.put_req_header("authorization", "Bearer #{api_key}")
    else
      conn
    end
  end
end

Last Post!

karlosmid

karlosmid

Hi!

Using code coverage: mix test --cover be sure to have:

  1. source code statement coverage
  2. combinations for branch (if then else) coverage
  3. do not forget test data

Where Next?

Popular in Discussions Top

PragTob
Hey everyone, this has been on my mind for some time and I’d love your input on it! TLDR: I feel like maps are superioer for storing and...
New
CharlesO
Erlang :list.nth simple, but 1 - based nth(1, [H|_]) -> H; nth(N, [_|T]) when N > 1 -> nth(N - 1, T). Elixir Enum.at … coo...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 55125 245
New
restack_oslo
Hello, Please pardon me for any faux paux. I am 46 and this is my first time on a forum of any kind. I wanted to to get answers from tho...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

Other popular topics Top

ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement