Minitest basics (assert style) in Ruby - Time & Space Complexity
When we write tests using Minitest's assert style, it's important to know how long these tests take as the code grows.
We want to understand how the time to run tests changes when we add more checks or bigger inputs.
Analyze the time complexity of the following Minitest assert style test.
require 'minitest/autorun'
class TestSum < Minitest::Test
def test_sum
n = 1000
numbers = (1..n).to_a
sum = numbers.reduce(0, :+)
assert_equal n * (n + 1) / 2, sum
end
end
This test checks if the sum of numbers from 1 to n is correct using the reduce method and an assertion.
Look at what repeats when the test runs.
- Primary operation: Summing numbers from 1 to n using reduce.
- How many times: The sum operation goes through all n numbers once.
As n grows, the sum operation takes longer because it adds more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the test takes longer in a straight line as the input size n grows.
[X] Wrong: "The assertion itself takes a lot of time as n grows."
[OK] Correct: The assertion just compares two numbers, which is very fast and does not depend on n.
Understanding how test time grows helps you write efficient tests and shows you care about quality and speed in real projects.
"What if we replaced the reduce method with a direct formula calculation? How would the time complexity change?"