Blithe Rocher

Not your average engineering manager.

  1. About
  2. Blog
  3. Résumé

Test-driven Development (TDD)

I've had some difficulty practicing Test-driven Development (TDD) while working on my current project. I think it comes from the combination of 1) not knowing exactly what I want my web app to do, 2) not knowing the specific code I need to write to create that look/functionality, and 3) not knowing the correct way to write a test to check it. 

I realize that I should be making a plan, then writing a test, then writing code but I usually start with a vague idea of something I want to do then I try to figure out if I can code it. By the time that I figure out what I can code (usually through trial and error), that determines how that feature is represented on the sites. At that point, I have coded the feature and I haven't added any tests! Oops. I really want to be better at writing the test first so I am spending some time this weekend learning more about how to write tests. Instead of adding more features to my project, I want to make sure everything I've added so far already has test coverage. 

I knew in general that there were gems that would test for code coverage. Andy Lindeman recommended the simplecov gem to me. I should mention that just because a line of code is technically covered by a test, you don't have 100% code coverage unless you test all of the possible use cases. At this point, I am just using simplecov to show the major areas where I need to focus my attention. 

After installing the gem, I used RSpec to run my tests, I discovered that I already had pretty good overall coverage but my more recently added features needed serious attention, particularly the controllers. 

image

As I had added new features that required models and controllers to my project new tests were required. I was already pretty comfortable writing tests for models (hence their good coverage) but I hadn't really written any tests for my controllers. Writing all of the tests from scratch for the controllers seemed like a pretty big challenge. Luckily I found a helpful post at Everyday Rails about testing controllers. I appreciate the way that Aaron Sumner lays out the organization of the tests and builds from there. I'm familiar with most of the concepts in the post but writing everything from scratch was difficult.

I also appreciated how he included the type of request method in the text of the describe block (as shown in the "organization" figure below). I wouldn't have thought to include that bit of information on my own. 

image

This post has helped me to feel more comfortable with writing tests for my controllers. Now I can make sure the features I have already added are covered. I'll also use this information to write new tests for features before adding them in the code.