Search⌘ K
AI Features

Testing Periodic Actions

Explore how to test periodic actions in Elixir GenServers using ExUnit. Understand how to manage API polling, state to avoid redundant alerts, and integration with external services like Twilio. This lesson covers practical testing techniques to assert asynchronous behavior reliably.

A common use for GenServers is to have a process in your system that acts periodically. For example, you could have a GenServer that resets a cache every five minutes or a GenServer that looks for changes to system environment variables every few seconds and updates other parts of your system when that happens.

SoggyWaffle

For our Soggy Waffle application, we need something like what we just described. Soggy Waffle’s purpose is to alert us if there will be rain in the next few hours. To do that, the application needs to periodically call out to the weather API to check if there’s rain in the forecast for a given location.

Remember the weather API we worked within Unit Tests, and Integration and End-to-End Tests. We’ll finally be able to put that to real use.

However, just performing weather API calls periodically and alerting if there’s rain in the next few hours isn’t enough to make this work properly. The application also needs to avoid alerting us every time the forecast says it will rain in two hours. If we are checking the API every 30 minutes, we can’t also be sending an alert every thirty minutes. We need to store some data somewhere that’ll help us avoid useless alerts.

So our use case is clear:

  • Perform some periodic action.
  • Store some state.

It seems like our best tool to solve this is a GenServer. What a plot twist. ...