The more interviews and take home challenges I get, the more I realize how important it is to know how to write and read tests for my code. Every single recruiter for all of the backend positions that I have asked me to demonstrate my test writing skills, in one way or another. After diving into Ruby docs and scanning Youtube for how-to videos, I feel like I have the fundamentals I need to be proficient with Ruby's testing suite Minitest.
Assert/Refute style testing is the most basic way to write tests for your code. You simply write a method that will either assert that a parameter is true or refute that a parameter is true. The outcome of the function will be either true or false.
This example test will fail, as it is an assert test that returns false. The first parameter in this method is the test, while the second parameter is the failure message. The failure message can be a string or a proc. If the message is a string, it will be used as the failure message. Otherwise, the result of calling message will be used as the message if the assertion fails. If no message is given, a default message will be used. This particular test would have passed if it was written as a refute, instead of assert.
There are a number of different ways to write assert/refute tests with Minitest. Below are some basic testing methods:
assert_block( failure_message = nil )
This method tests the result of the given code block. If the block does not return true, the assertion will fail.
assert_equal( expected, actual, failure_message = nil )
This method tests if expected is equal to actual.
assert_not_equal( expected, actual, failure_message = nil )
This method tests if expected is not equal to actual.
assert_not_nil( expression, failure_message = nil )
This method tests if expression is not nil.
In the same way that there are endless ways to write and structure your code, there are copious ways in which you can write these assert/refute tests to verify your code. I would highly recommend picking up a testing suite written for your most familiar language and really digging in. The ability to write and read tests for code is extremely important.
REFERENCES
https://docs.ruby-lang.org/en/2.1.0/Test/Unit/Assertions.html
https://blog.codeship.com/getting-started-with-minitest/
Top comments (0)