TDD workflow with Vim

Recently I picked up a neat trick from Jeffrey Way (host of Laracasts) for making testing easier with Vim. Rather than using automated test runners and setting up file system listeners he prefers to manually setup simple mappings in Vim to run his tests. I have automated this processes and integrated it into my workflow.

Assuming you are working on a php project and using phpunit for testing, the idea is to make mappings on the fly as follows.

:nmap ,t phpunit %<cr>

This will map ,t to run the tests in the current file. However, you can only run the test while you are editing the test file. The alternative is to manually hard code the file name into the mapping so you can run it from anywhere.

:nmap ,t phpunit tests/ExampleTest.php<cr>

This allows you to execute your tests from any file. However I found the process of changing the file name cumbersome. To make things faster I currently have the following command mode abbreviation in my .vimrc

cabbrev mpu nmap ,t :!phpunit <C-r>=shellescape(expand(‘%’), 1)<cr>^V^V^M

To enter the key sequence ^V^V^M at the end, type <ctrl-V><ctrl-V><ctrl-V><ctrl-V><ctrl-V><enter> and make sure they are all on the same line.

This allows me to simply type ‘:mpu’ (think of it as Map phpunit) which will expand to the correct nmap command.

The abbreviation works by utilizing the expression register to expand the % to the current file name. The weird ^V^V^M is an escaped sequence. You can read more about it here (search for *using_CTRL-V*). It basically results in an escaped carriage return.

Happy coding!