The lasttwo episodes have concentrated on refactoring and testing. By the end of the last episode we’d refactored our model, but the tests for it were in a bit of a mess. Let’s see what we can do to tidy them up.

We have three tests and there is a lot of duplication across them. For each test we create a new User and compare it to a string value. To remove the duplication we’ll create a method that creates a new User and returns its full_name.

Now that our tests are straightforward they can be moved in to a single test with three assertions. The only problem with doing that is that if one of the assertions in a test fails it is difficult to know which one it was. We can add a message to each assertion so that it identifies itself if it fails. Our final test class looks like this:

Over the last three episodes we’ve created unit tests and refactored them along with the code they test to leave both in a much more readable and managable state. While this is a relatively simple example it should persuade you of the benefits of testing and refactoring your Ruby and Rails code.