Convert to the new Rspec syntax with Vim macros

ruby vim
Posted on: 2012-11-28

Rspec 2.11 introduces a new syntax: expect(foo).to eq('bar') instead of foo.should eq('bar'). Myron Marston has explained why in detail; essentially it boils down to "passing arbitrary objects to expect is easier than reliably defining a should method on every possible object."

You probably should start using the new syntax, and you might expect it to be a chore. Unix masters could surely use something like awk to do it in bulk, but I haven't taken the time to learn it yet.

For the small chore of converting Authority's tests, a couple of git greps and Vim macros were enough. Here's how I did it:

  • git grep \\.should\ (that's a literal period at the beginning and a space at the end)
  • Open a matching file in Vim
  • Search using /\.should\s
  • n to land on the first match
  • Record a macro
    • qa to start recording a macro in register a
    • I to insert at the beginning of the line. Type "expect(".
    • Esc, then n to land on the match again (the '.' at the start of '.should')
    • ct (change to space) and type ").to"
    • Esc
    • q to stop recording the macro
  • n to get to the next match
  • @a to use the macro
  • For all subsequent matches, n to get to them and @@ to reuse the macro
  • Open the other files one by one, keep hopping to matches with n and using the macro
  • Repeat the process for usages of should_not