Welcome to day 45 of the 49 Days of Ruby! ๐
For the past 44 days, we have discussed writing code. Today, we will discuss testing your code!
Over the next several days we will look at different ways to test your code in Ruby.
However, before we start discussing how, it's important to discuss why. Why should you test your code?
This question gets asked a lot because especially when you first start writing tests, the writing of the tests can often take longer than the writing of the code! It can seem like a big use of your time and for not a lot of immediate benefit.
Why Test Your Code
The most fundamental reason why you should test your code is no one is perfect.
You are not perfect.
The writers of gems your code relies upon are not perfect.
The API engineers of the external APIs your code relies upon are not perfect.
No one is perfect.
That means that while you may think you got everything down right, you may have missed one letter in a variable, or forgot to put a semicolon. Perhaps, an API engineer released a new version of an API endpoint and unintentionally broke your code.
How do you know when a mistake happens? Well, you could know when you run the code and something breaks.
However, depending on running the code means that you will often put things out there that don't work, and you want to avoid that. Hence, building tests.
Tests give you confidence that your code, at least at the time of writing the test, works.
What kind of tests?
Typically, when you are going to write tests you want to test a couple of different things:
- Success Routes
- Failure Routes
A success route is what you expect to happen when things go well. If method A does something with input X and returns an output of Y, I want to test that those are the case.
A failure route is what you expect to happen when things go wrong. A user puts in the wrong input. The API returned an error code, etc.
It is important to test both routes because you want your code to be able to handle both circumstances.
Now that we have a sense of why you should test, tomorrow we'll start looking at Ruby testing frameworks!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.