Where developers come to connect, share, build and be inspired.

2

PHP continuous testing with GruntJS and PHPUnit

2652 views


Grunt (http://gruntjs.com/) is our preferred tool here at mention (https://mention.com) when it comes to task automation. It’s a Javascript task runner, offering both a lot of bundled plugins for common tasks, while still being very extensible, giving you the option to write all kinds of tasks to suit your need. The best comes when you can combine tasks together to create even more powerful ones!

Grunt’s scope goes beyond simply automating front-end related tasks. We use it, for example, to continuously test in PHP while we develop:

 var log, terminal;

terminal = require('color-terminal');

log = function(error, stdout, stderr, cb) {
  if (error) {
    terminal.color('red').write(stdout);
  } else {
    terminal.color('green').write(stdout);
  }
  return cb();
};

module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-shell');
  grunt.initConfig({
    testFilepath: null,
    watch: {
      php: {
        options: {
          event: 'changed',
          spawn: false
        },
        files: ['foo/bar/**/*.php', 'foo/bar/**/*Test.php'],
        tasks: 'shell:phpunit'
      }
    },
    shell: {
      phpunit: {
        options: {
          callback: log
        },
        command: 'echo <%= testFilepath %> && phpunit -c app <%= testFilepath %>'
      }
    }
  });
  return grunt.event.on('watch', function(action, filepath, ext) {
    var regex, testFilepath;
    regex = new RegExp("foo/bar/([a-z0-9]+)/([a-z0-9/]+)", "i");
    if (filepath.match(regex)) {
      if (filepath.indexOf('Test') === -1) {
        testFilepath = filepath.replace(regex, "foo/bar/$1/Tests/$2Test");
      } else {
        testFilepath = filepath;
      }
      return grunt.config('testFilepath', testFilepath);
    }
  });
};

This simple Grunt task watch *.php and *Test.php files, and run PHPUnit with the correct test class each time it is modified. Simple but really efficient while in an intense coding session.

Want to learn more ? Here's the list of our favorite front-end tools: http://blog.mention.com/the-5-best-front-end-developer-tools/

Add a comment