If you are not sure about Ruby on Rails testing and writing tests for any application, consider reading this article.

You may write tests just without any plan but if you want to build a Ruby on Rails testing routine that will make your code better please meet testing cycles: red, green, refactor.

Red

Red like a failure. First, create the test, put there all expectations and let it fail. For some people, it may be weird that we first create test instead of contents in a testing class. The goal here is to focus on expectations not on writing tests that are green for code we already have. In simple words: if you buying a box for your books you check first how many books do you have or you just buy a box counting on a luck that there would be enough space for all boxes? You can go for both versions but only one of them would always save some time for you - it's always better to set expectations first and search for a box that can fit n books inside, not buy a box and then test how many books we can put there.

Green

Green like a success. You have tests and expectations so now your goal is to write code that would satisfy them. Simple as that. Don’t spend much time on writing the best code you can, focus on satisfying expectations.

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

Refactor

It’s time to make things clean and beautiful. Now you can update your code by getting rid of unneeded variables, methods or doubled calls. You shouldn’t spend much time on this step. If you did then it may mean that code is too complicated and you didn’t implement single responsibility principle.

What’s next?

Now repeat. Repeat with each next class you will be creating. I will write more about Test Driven Development soon so stay in touch.

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!