Running ExUnit tests when file changes June 16, 2015 posted in elixir, exunit.

I’m working on the exercises from Elixir Etudes and I was looking for a way how to run my tests automatically when my source or test file changes — something like guard-rspec in ruby.

Guard

Surprisingly, there is an integration of ExUnit into guard. So if you have your ruby environment ready you can use this gem. The version on ruby gems doesn’t support guard 2.0 so you need to be specific with the github repository.

Firstly, add the following lines into Gemfile . If you don’t have bundler installed run gem install bundler .

group :development do gem 'guard-elixir', :git => 'git://github.com/os6sense/guard-elixir.git' end

After that, run bundle install .

If you are using rbenv you can install and run guard with the following commands. If you have only plain ruby remove the bundle exec.

bundle exec guard init elixir bundle exec guard

Entr

Entr project is a general purpose tool in your UNIX tool belt. It can monitor any directory you specify and run any command. Very useful tool, when there isn’t anything targeted to the goal you are trying to achieve.

Download and unpack the latest version from the project website. The one in the Ubuntu package is a little bit old. After that, install with the following commands.

./configure cp ./Makefile.linux Makefile make test sudo make install

Now, in your Elixir project run the following command to monitor your lib and test directories.

while sleep 1; do ls -d lib/**/*.ex test/**/*.exs | entr -d mix test; done

The command is running in a while loop as the -d option exits the program when a new file appears so it is automatically restarted and can pick up newly created files.

Picking up new files and running the tests from it is also the biggest advantage of Entr in comparison to the other alternatives.

Mix Test.Watch

Last and probably a go to solution for Elixir developers is an extension for mix command called mix test.watch.

The usage is pretty straightforward. Add a dependency to your mix.exs file.

def deps do [{:mix_test_watch, "~> 0.1.1"}] end

Run mix deps.get and mix test.watch . ExUnit directories are now watched and the test will run after every file change.

Now you know at least three ways to run your tests automatically so there is nothing stopping you from testing your Elixir code — no more excuses.

Would you like to get top 5 links on Elixir every Monday?

Sign up to Elixir Digest and stay up to date!