3-1/ What to Test and How to Test it
3-2/ Why Write Tests
3-3/ The Arrange, Act, Assert Pattern
In Part 1 of this tutorial, we demonstrated the MInitest paradigm without even writing any actually Ruby code at all. Normally, you don’t assert 1+1=2, that wouldn’t be much use. Instead, your real tests will test real code. Before going further, it’s time to introduce you to a foundational part of all testing: The Arrange, Act, and Assert pattern, or AAA.
Arrange, Act, and Assert means we think about our tests in 3 steps: 1) Setting up some prerequisites (or arrange), doing something (act), and asserting that something is true.
In Minitest, it’s sometimes easy to conflate these steps, which is OK but as a good exercise try to think in these terms. Although you will not formally write the words “Arrange, Act, Assert” in your test code, you often
# ARRANGE thing = StringTransformer.new("an input") # ACT thing.reverse_string! # ASSERT assert_equal("tupni na", thing.result)
In the example above, I’ve included comments at the top of each section, but this is only for learning purposes. In your real production code you should not include these comments, but it is often a good pattern to leave a blank space between the lines of code that are Arrange & Act, and then another blank space between Act & Assert. For example, let’s assume our ACT line was actually two lines:
# ACT thing.reverse_string! thing.transpose_string!
In this example, we have two lines as part of our act. When writing this code without the ARRANGE ACT ASSERT comments, we’d leave a blank line between the Arrange-Act-Assert sections:
thing = StringTransformer.new("an input") thing.reverse_string! thing.transpose_string! assert_equal("utnp ian", thing.result)
Here, we’re creating a StringTransformer giving it a string. Then we reverse the string and transpose the letters. Notice that there is a blank line between the Arrange, Act, and Assert sections but not between the two lines of the Act section.
This is just a template for structuring your tests. Although it is a good idea to learn up front and often makes your tests easier to understand, there are still many cases when you might not strictly follow this pattern.