Writing tests/specs for existing code

By Nathan Donaldson

Tags:

On several occasions we’ve looked at Rails projects with no tests, or very low test coverage. Trying to write tests when you didn’t write the original methods is difficult. Here are some tips that we’ve found helpful.

Use your favourite framework.

If there is a large body of existing tests using a particular framework, write your new tests in that framework. If there are few or no tests then strip out anything already there and replace it with your preferred framework. At Boost we’ve decided to use RSpec for all our projects. Your objective here is to write tests, not to learn a new way of writing tests.

Don’t fix bugs!

If you discover what you believe to be a bug while writing tests, consider that you don’t know why the bug is there. You should write your test to pass the code as is. Describe the bug in your bug tracker and move on. I’ve fixed bugs while writing tests only to find that the side effect breaks something else – but I had no tests so there was no way to know.

Start with the basics

The easiest way to get started is to write a test for every method, action and view that just runs without asserting anything. This will get your test coverage up. Running over the whole code base allows you to catch exceptions caused by typos. Doing this will also give you a good starting overview of the code base. Using a tool like ZenTest, or a recently posted rake task unspec’d, will help find everything to test.

Mocks and Stubs

Obviously you’ll be using mocks and stubs, but be careful not to stub out too much. Get a test in for every public method, and don’t stub out private methods.

Test your own code

Make sure that you write comprehensive tests for any code you add to the project. Never use the lack of existing tests as an excuse for not writing your own.

Any finally, don’t give up hope! For any reasonably complex project it is nearly always faster to implement the tests/specs than to rewrite the whole thing from scratch. Writing tests is actually a really good way to learn a foreign code base.

Learn more

Debugging using ctags to index and search your code base

Make a bigger impact tomorrow

Talk to us today