Covering icky code with automated tests

Every codebase has "icky" code.

Code that works but is difficult to read and understand, that most people will avoid working on.

It could be fragile and occasionally return different results or error.

It could be a suboptimal implementation.

I mention in my test-driven drupal talk when I wrote some code that worked locally but didn't work because of the hosting setup and I had to rewrite the code in a different and less optimal way.

How do you build confidence around this code?

Write more automated tests around it.

This will make it easier to understand what the code does as the tests will act like examples and, as you find situations where the code can break, you can write tests to ensure it works as expected once fixed and will continue to work.

Once there are tests, the code will be easier to add to, change, refactor, read and understand.