Elixir TDD'ing

I like TDD. I also like automated stuff. Adding these two, I like my tests to run when I save code files in my project. I have this need to see “N tests, 0 failures” in my console and I love the real-time feedback.

So here is my setup to have tests running all the time via grunt on my Phoenix project! Add/create the following in your packages.json file on your root dir:

{
  “name”: “my_app”,
  “version”: “0.0.1”,
  “devDependencies”: {
    “grunt”: “~0.4.1”,
    “grunt-exec”: “~0.4.6”,
    “grunt-contrib-watch”: “~0.5.3”
  }
}

Add/create the following to your Gruntfile.js also at the root of your project:

module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON(‘package.json’),
    watch: {
      files: [“web/**/*.ex”,”lib/**/*.ex”,”test/**/*.exs”],
      tasks: [“exec”],
      options: {
        dateFormat: function(time) { return “”; }
      }
    },
    exec: {
      run_update_script: {
        stdout: true,
        cmd: ‘mix test’
      }
    }
  });

  grunt.loadNpmTasks(‘grunt-exec’);
  grunt.loadNpmTasks(‘grunt-contrib-watch’);

  grunt.registerTask(‘default’, [‘watch’]);
};

Now jump to your console and:

$ cd $PROJECT_PATH
$ npm install
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄░░░░░░░░░
░░░░░░░░▄▀░░░░░░░░░░░░▄░░░░░░░▀▄░░░░░░░
░░░░░░░░█░░▄░░░░▄░░░░░░░░░░░░░░█░░░░░░░
░░░░░░░░█░░░░░░░░░░░░▄█▄▄░░▄░░░█░▄▄▄░░░
░▄▄▄▄▄░░█░░░░░░▀░░░░▀█░░▀▄░░░░░█▀▀░██░░
░██▄▀██▄█░░░▄░░░░░░░██░░░░▀▀▀▀▀░░░░██░░
░░▀██▄▀██░░░░░░░░▀░██▀░░░░░░░░░░░░░▀██░
░░░░▀████░▀░░░░▄░░░██░░░▄█░░░░▄░▄█░░██░
░░░░░░░▀█░░░░▄░░░░░██░░░░▄░░░▄░░▄░░░██░
░░░░░░░▄█▄░░░░░░░░░░░▀▄░░▀▀▀▀▀▀▀▀░░▄▀░░
░░░░░░█▀▀█████████▀▀▀▀████████████▀░░░░
░░░░░░████▀░░███▀░░░░░░▀███░░▀██▀░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
$ grunt
Running “watch” task  
Waiting…OK  

You’re all set. Next time when you save a file on your favorite editor:

Running “watch” task  
Waiting…OK  
>> File “test/unit/foo_test.exs” changed.

Running “exec:run_update_script” (exec) task  
…….
Finished in 0.2 seconds (0.1s on load, 0.09s on tests)  
7 tests, 0 failures

Randomized with seed 434932  

w00t! Not the fastest but good enough for now.

P.S.: You might notice that after the “Randomized with seed” text a “Done, without errors” appears. I didn’t find a way to remove this programatically, so just kill that line under $PROJECT_PATH/node_modules/grunt/lib/grunt/fail.js.

Check my other Elixir posts here.