Red-green-refactor cycle

Ruby on Rails / Testing

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.

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