Elixir Warnings as Errors…Sometimes

Michael Stalker
Code for RentPath
Published in
2 min readApr 23, 2019

--

You can treat warnings in Elixir as errors, so that your code won’t compile if the compiler emits warnings. This will help catch issues like unused functions. You can do it by adding a new key/value pair to project/0 in mix.exs.

defmodule MyProject.MixProject do
use Mix.Project
def project do
[
elixirc_options: [warnings_as_errors: true]
# ...
]
end
# ...
end

However, this sometimes gets in the way when I’m refactoring.

I like running my tests after each small change I make. When I begin applying Extract Function, I’d run my tests before finishing my refactoring. If warnings_as_errors is enabled, Elixir will fail to compile my code. Why? I wrote a new function and ran my tests before any code used it. What’s a developer to do?

To get around this, we can use warnings_as_errors in a development and production environment, but disable it in a test environment.

defmodule MyProject.MixProject do
use Mix.Project
def project do
[
elixirc_options: [
warnings_as_errors: halt_on_warnings?(Mix.env())
]
# ...
]
end
defp halt_on_warnings?(:test), do: false
defp halt_on_warnings?(_), do: true
# ...
end

Acknowledgements

Louis Pilfold’s mix test.watch library makes it incredibly easy to run your tests frequently. It runs your test suite every time you save a file.

You have read Refactoring, haven’t you? It’s amazing. Steve Yegge said it made him “a better programmer overnight.” You can buy a JavaScript version (by Martin Fowler, with contributions from Kent Beck), a Java version (by Martin Fowler, with contributions from Kent Beck, John Brant, William Opdyke, and Don Roberts), or a Ruby version (by Jay Fields, Shane Harvie, and Martin Fowler, with Kent Beck).

Thanks also goes to Craig Cottingham, who reviewed this article.

--

--