How To Run Rspec Specs From Vim

August 27, 2009

Test Driven Development is all about having a quick feedback loop. You know something’s broken immediately because your tests fail.

As projects grow you write more tests, and it takes more time to run your tests. It becomes increasingly important to be able to only run one test or the few tests you care about so you can keep moving with the code.

TextMate has some commands to do this (Cmd-R, and Cmd-Shift-R).

Here’s how to do it with vim.

Usually when I’m coding I have Vim open in split screen mode (with rails.vim installed, of course.) I’ll have a spec file on one side, and the application code on the other.

I have this incredibly handy function and key mapping in my .vimrc. Credit for this clever implementation goes to Art and Technology Consultant extraordinaire Ian Smith-Heisters.

" Execute open rspec buffer
" Thanks to Ian Smith-Heisters
function! RunSpec(args)
 if exists("b:rails_root") && filereadable(b:rails_root . "/script/spec")
   let spec = b:rails_root . "/script/spec"
 else
   let spec = "spec"
 end
 let cmd = ":! " . spec . " % -cfn " . a:args
 execute cmd
endfunction
 
" Mappings
" run one rspec example or describe block based on cursor position
map !s :call RunSpec("-l " . <C-r>=line('.')<CR>)
" run full rspec file
map !S :call RunSpec("")
 
view raw This Gist brought to you by GitHub.

When I’m in the spec file I can hit !s return to execute the example or describe block that the cursor is in.

Hitting !S return executes all the examples in that file.

The fancy descriptive output is just one of the nested formatter which comes included with Rspec. They can be specified with the -f flag. spec --help has more details on this.