DEV Community

Marcio Lopes de Faria
Marcio Lopes de Faria

Posted on • Updated on

Execute and Watch Elixir tests from iex.

EDIT: I came up with a even better way to debug Elixir code than using iex, check it here.

Interactive Driven Development, or REPL Driven Development is a really good way to approach programming, specially for developers that get distracted easily with time being expend out the main development loop or flow.

A way to do it in Elixir is just to use the fswatch as presented in Elixir Mix Test documentation, or using the excellent mix.test-watch library, but them don't work well with iex, the Elixir REPL, so why not do something else.

So I created some modules that can be imported on your iex through the ~/.iex.exs file and get the same benefits.

Just insert it on your ~/.iex.exs file:

And create a ~/.iex directory, placing this file on it:

There is an explanition about how to use it on the @moduledoc, but briefly you just need to call iex prepending the ~/.iex directory on the Elixir path:

  ELIXIR_ERL_OPTIONS="-pa $HOME/.iex" MIX_ENV=test iex -S mix
Enter fullscreen mode Exit fullscreen mode

The IExWatchTests.Helpers that is imported on ~/.iex.exs allows to call f and s and a to run failed, stale and all tests respectively.

You can call w to watch tests and uw to unwatch.

There is a really simple throttle mechanism that disallow run the suite concurrently.

That is all. Enjoy!

Discussion (4)

Collapse
alexandremcosta profile image
Alexandre Marangoni Costa

Nice tip! Any idea on how to make Mix.Tasks.Test.run([]) to work on umbrella projects? Mine always output There are no tests to run

Collapse
marciol profile image
Marcio Lopes de Faria Author

I need to figure out, but I think that must be simple.

Collapse
alexandremcosta profile image
Alexandre Marangoni Costa • Edited

For some reason, I also can't import IExWatchTests.Helpers from .iex.exs

$ ELIXIR_ERL_OPTIONS="-pa $HOME/.iex" MIX_ENV=test iex -S mix
Erlang/OTP 24 [erts-12.0.2] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit]
Interactive Elixir (1.12.1) - press Ctrl+C to exit (type h() ENTER for help)
Error while evaluating: /Users/xxx/.iex.exs
** (CompileError) /Users/xxx/.iex.exs:11: module IExWatchTests.Helpers is not loaded and could not be found
Enter fullscreen mode Exit fullscreen mode

But if I comment this line and run it from iex, it works!

Thread Thread
marciol profile image
Marcio Lopes de Faria Author

Yes, I wrote another post explaining why I concluded that this approach is less than ideal, because there is a lot of limitation on what you can do in .iex.exs. For example, there is a IEx.Helpers.import_if_available/2 to deal with it.