Mocks in Elixir/Phoenix using Behaviors and Environment variables.

Mocks are the squirt gun vs. the real gun. They can mimic behavior but aren’t nearly as dangerous.

The Goal

The goal is to use a Twilio Sms Mock to verify and send. Rather than use the Twilio API directly, we don’t want to rely on external APIs in our non-production environments for a variety of reasons:

  • Introduces flakiness and a reliance on network connectivity
  • Slows down tests that need to wait for the response
  • Avoid coupling code directly to the library in case we change libraries.
  • Working directly with a library that can send real SMS text messages is risky.

The Design

We can set an environment variable in phoenix to point to the module we want to use depending on the environment.

Access and Set Environment Variables.

You can set environment variables in phoenix by adding them to your environment’s config file.

To Set An Environment Variable.

Add the following to an environment config file.

  • :app_name should be your applications name
  • sms_service is the env variable name. It can be any valid name you want.
  • App.Sms.MockSms is the SMS module you want to use for that environment. In dev.exs and test.exs, it should be MockSms, and in prod.exs it should be ProdSms

To Retrieve an Environment Variable.

You can access environment variables with Application.get_env

Create The Prod and Mock Modules.

Both modules should have the same interface. This means they must define the same common public methods.

Delegate to the Prod and Mock Modules.

Now that you have production and mock modules defined, your parent module can delegate to them.

Test the Prod Module.

To make sure your prod module continues to work, you can implement tests that specifically use the module.

Final Thoughts.

Now that you have the parent module set up, you can use that in your normal tests.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brooklin Myers

Brooklin Myers

Software Engineer. I create educational content focused on technology for mobile and web applications.