Minitest is a lightweight and easy-to-use testing framework for Ruby. It is a part of the Ruby standard library, which means you don’t need to install any additional gems to use it. In this blog post, we will guide you through the process of writing your first Minitest for your Ruby code.
Step 1: Create a Ruby file and a test file
First, create a Ruby file with the code you want to test. For this example, let’s create a simple class that calculates the sum of two numbers called calculator.rb.
Inside calculator.rb, add the following code:
class Calculator
def sum(a, b)
a + b
end
end
Now, create a test file for this class. By convention, test file names should end with _test.rb. We can name our test file calculator_test.rb and place it in the same directory as calculator.rb.
Step 2: Write your Minitest
Inside calculator_test.rb, add the following code:
require 'minitest/autorun'
require_relative 'calculator'
class CalculatorTest < Minitest::Test
def setup
@calculator = Calculator.new
end
def test_sum
assert_equal 5, @calculator.sum(2, 3)
end
end
Let’s break down the code above:
- require ‘minitest/autorun’: This line loads the Minitest framework.
- require_relative ‘calculator’: This line loads the calculator.rb file so that we can use the Calculator class in our tests.
- class CalculatorTest < Minitest::Test: We define a new class called CalculatorTest that inherits from Minitest::Test. This allows us to use the testing methods provided by Minitest.
- def setup: The setup method is called before each test. In this case, we create a new instance of the Calculator class and assign it to the instance variable @calculator.
- def test_sum: We define a test method called test_sum. Minitest will automatically execute all methods whose names start with test_.
- assert_equal 5, @calculator.sum(2, 3): This line checks if the result of calling @calculator.sum(2, 3) is equal to 5. If it is, the test passes. Otherwise, the test fails.
Step 3: Run your Minitest
To run your Minitest, open a terminal and navigate to the directory containing both calculator.rb and calculator_test.rb. Then, run the following command:
ruby calculator_test.rb
If your test passes, you should see an output similar to this:
Run options: --seed 12345
# Running:
.
Finished in 0.001083s, 922.9021 runs/s, 922.9021 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
This output indicates that one test was run (1 runs), one assertion was made (1 assertions), and there were no failures or errors.
Conclusion
Congratulations! You have now written and run your first Minitest for your Ruby code. Minitest is a powerful tool for writing tests that can help you ensure your code is working as expected and catch bugs early in the development process. Keep practicing and experimenting with Minitest to improve your Ruby testing skills!