High Five: five tips on testing with Rails
Testing is a very important aspect of Rails programming. The framework makes testing really easy, eliminating some excuses you could have for not testing your applications. Here’s my five tips for testing with Rails:
- Embrace the TDD cycle: this one isn’t Rails related, but is very important. You can write your code first and test it after and you’ll get some benefits, but Test-Driven Development really leverages the power of this automated testing. By writing your tests first you get low coupling and high cohesion through a better interface (API) design. Moreover, by following the red-green-refactor cycle you’ll always know when you’re done and will avoid scope creep.
- Test your helpers: plain and simple. Rais Recipes has a recipe about it and, with Edge Rails, testing helpers got easier.
- Overmocking results in brittle tests:and brittle tests are a bad thing. Many people just mock and stub everything. By doing this you’re coupling your tests to the inner details of the tested code instead of the result of its execution. You can see an example here (and subscribe to that blog’s feed, it’s very good).
- Watch out on your way to BDD: Behavior-Driven Development is in vogue within the Rails community. Be careful. Just like you can write Fortran in any language, you can use something like RSpec and still not do BDD. BDD is about a shift in the way you think about tests, not about tools by themselves. You can use Test::Unit and do BDD. Tools like RSpec and Shoulda (my personal choice) are facilitators, they don’t guarantee anything.
- One assertion per test: this is one of that tips that seems inoffensive but once you’re doing helps a lot. Why? Jay Fields can explain better than me.
And that’s it. Five quick and simple tips that I hope will help you. Feel free to share your own tips in the comments. This article is my entry to the Railscasts’ 100th episode contest. Take some time to visit the site, it’s really good.
Contributing: reserved_attributes Rails plugin
Here’s my first contribution to the Rails community: the reserved_attributes plugin.
The plugin is very simple, just adding a rake task to your project. The task scans all your models checking its attributes (columns) and warning you if any of them have a name that are a Ruby/Rails reserved word.
Some time ago I spent about 8 hours of work because my unit tests was breaking with a very strange error (and a gigantic trace). It turns out that I was using an attribute called “notify” and there’s already an internal method with that name, so I was overriding it and breaking everything. I’ve seen many people with the same problem, so here’s a little help. Take a look at the repository main page to see the README file with instructions.
The plugin is hosted at github and you’re free to fork and improve it.