Converting Rails tests to 2.2 format

Converting Rails tests to 2.2 format

This is a short one, but we’ve had to do it a couple of times so I thought I’d put it up.

As you may be aware, Rails 2.2 introduced a new format for test names. Where you once might have had:

def test_should_do_stuff

You can now have:

test 'should do stuff' do

We’ve found this much easier to read and type – especially when your test names start to get big, or would be more readable if they contained characters that aren’t valid in Ruby method names.

However, if you’ve got lots of existing tests and want to shift them across to this format, it can be a pain to do it manually. Unless you’ve got a Ruby script, of course:

directory = 'unit'
Dir.mkdir("#{directory}.new") do |entry|
  original_filename = "#{directory}/#{entry}""#{directory}.new/#{entry}", 'w+') do |new_file| do |line|
      new_file.puts(line.gsub(/def test_*(.*)/) do |match|
          "test '#{$1.gsub('_', ' ')}' do"
  end unless

..which you’ll also find in this gist.

If you go into your ‘test’ folder and run this script, it’ll create a new directory called ‘’, that contains copies of all of your original unit tests, converted to the new format. Change ‘unit’ to ‘functional’, and it’ll do the same for your functional tests. Note that this will not do tests in subdirectories. YMMV. Feel free to steal and modify as you see fit.

I'm a Senior Consultant at Shine Solutions.

1 Comment
  • Mark
    Posted at 09:28h, 13 October Reply

    Sweet! Thanks Ben.

Leave a Reply

%d bloggers like this: