Testing the Edges
Explore how unit testing enhances Ruby on Rails applications by isolating code failures, speeding up debugging, and validating object behavior in detail. Learn to write precise unit tests that ensure data integrity and simulate various scenarios, improving code quality while balancing test coverage with development cost.
We'll cover the following...
Why unit testing
Integration tests ensure that all our code works as expected from start to finish. Those tests are great because we want to know if all the pieces of the puzzle work together to give us the result we want.
While testing things in integration could be sufficient on its own, we might find ourselves wanting to describe the behavior of our objects in more detail. Unit tests are a great tool for this.
Unit tests provide a number of advantages:
-
Unit tests help isolate a failure down to the smallest unit of code.
-
Unit tests might be our most effective tool for debugging. They allow us to simulate different kinds of scenarios for each of our objects.
-
Unit tests are much faster in terms of feedback loops, so they provide a much nicer experience when we’re driving our code with tests. This is because we don’t have to wait a few seconds for every small change we make to our implementation code.
Unit tests in action
There are a few good use cases for unit tests in our example application.
-
Ensure that a
Userobject isn’t valid if thenamefield is longer than 100 characters. -
The
namefield shouldn’t have fewer than two characters. -
Names should only contain letters and spaces. So, something like emojis shouldn’t be allowed.
The list could go on indefinitely, and it’s up to us (and the stakeholder) to decide which things are important.
Note: There’s always a balance between exhaustiveness and cost that we need to consider when building software. We must constantly evaluate the cost of each task and determine if it’s worth the investment.