elixircowboyex-unit

How to spawn a cowboy server in a test?


Background

I have a specific test where I need to spawn a cowboy server listening on port 8082 that returns some static responses.

Objective

Normally I would spin up a cowboy process in my application.ex file like this:

   def start(_type, args) do
     children = children([{Cowboy, scheme: :http, plug: MyServer, options: [port: 8082]}])

     opts = [strategy: :one_for_one, name: MyApp.Supervisor]
     Supervisor.start_link(children, opts)
   end

But the code I am working on is not an application, so I can't do that.

My objective is to use the setup_all callback of ExUnit to do this, however I don't know how to do it or if it is possible.

Questions

  1. How can I start a cowboy server in ExUnit?

Solution

  • After some digging around, I found that there is a library called bypass that already covers this use case.

    This solution was also confirmed by Elixir's community, which seems to suggest it as well: https://elixirforum.com/t/how-to-spawn-a-cowboy-server-in-a-test/36686