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.
Alguém aí ainda não escreve testes?
Um bom motivador:

Fonte:
http://onestepback.org/index.cgi/Tech/Programming/DarthTest.red
Autor: http://www.flickr.com/photos/sebastian_bergmann/
Expressividade no código ou “Porque testes, código bem escrito e refactoring são melhores que qualquer documentação”
Interessantíssimo o artigo do Phillip Calçado, “Expressividade no código“. Nele, Phillip fala o que todo programador já está cansado de saber mas que a maioria finge não saber ou, simplesmente, acha “trabalhoso” demais. Afinal, desenvolvimento “Quick and Dirty” dá muito menos trabalho, não é?
Pior ainda é conseguir convencer gerentes disso. Gerentes são burocratas por natureza, possuem uma paixão inexplicável por papelada e documentação (que nem eles mesmo utilizam), adoram andar com livros grossos pregando a última “revolução” no mundo dos processos, caçando certificações como Cobit e PMI e, principalmente, não enxergando um palmo à frente do nariz. Não é por acaso que, hoje, a inovação vêm das startups e pequenos grupos de desenvolvedores pragmáticos que focam no que realmente importa: software simples, elegante e que resolve problemas.
Voltando ao artigo, a leitura é altamente recomendada. Com um exemplo simples e direto, Phillip constrói seu argumento com rara habilidade. Habilidade que só a experiência com desenvolvimento real é capaz de trazer.
Aprendendo a “amar” os testes e um pouco de BDD
Uma das práticas mais fortes das metodologias ágeis é o desenvolvimento guiado por testes, Test-Driven Development. Leia sobre o assunto aqui.
Uma corrente mais nova desenvolveu o Behavior-Driven Development (desenvolvimento guiado por comportamento), uma evolução do TDD, buscando tornar a prática mais natural através de técnicas como a Ubiquitous Language.
Gregg Pollack do site RailsEnvy recentemente publicou um vídeo de sua apresentação sobre testes e BDD em Rails no grupo de usuários de Orlando, veja aqui: How I learned to love testing.
Aprendizado orientado a testes
Você provavelmente já ouviu falar de Test-Driven Development (desenvolvimento orientado a testes) e provavelmente até utiliza esse método. Se não utiliza, deveria começar a pensar seriamente nisso.
Recentemente, passeando por alguns blogs, encontei um post falando sobre aprendizando orientado a testes. Neste caso, aprendizado de Ruby utilizando o framework para testes unitários incluso na linguagem (leia sobre o framework aqui e aqui). Veja o post e sua sequência.
Essa abordagem é bastante interessante pois estimula o aprendizado através da experimentação e da descoberta. Os testes unitários são uma excelente forma de descobrir como algo funciona em uma linguagem. É claro que a documentação é importante (e a documentação do Ruby é muito boa: simples, direta e completa), mas todos sabemos que a melhor documentação é o código-fonte, aquele que gira as engrenagens e faz com que tudo funcione (ou não…).