Configuring a cron-style task in Elixir on start

I’m making an app that makes an HTTP request to an external site every 5 minutes. It makes its first request on start-up, then sleeps for 5 minutes and recurses. My problem is that when I run tests, this thing immediately starts making external HTTP requests. Since it happens on start-up, its tough to stub out in my tests.

The code looks like this:

defmodule Pinger
  def start_link do
    Task.start_link __MODULE__, :forever_ping, []
  end

  def forever_ping do
    Task.start __MODULE__, :ping, []
    :timer.sleep(@interval)
    forever_ping
  end

  def ping do
    @url
    |> HTTPoison.get
    |> handle_response
  end
end

Then I start the module as a child worker process like this:

children = [ worker(Pinger, []) ]
Supervisor.start_link(children, opts)

Any ideas on how to stub/not-run this in the tests are very welcome. Also, if other people have found solutions to cron-style tasks in elixir, I’d love to compare notes!

1 Like

Have you tried the --no-start flag when running your tests? This will prevent your applications from starting.

4 Likes

I didn’t know about --no-start. Thanks!

1 Like

No problem. If you wanted to always run tests with that flag you could also setup an mix alias see here