Let and before hooks in Ruby - Time & Space Complexity
We want to understand how the time it takes to run code with let and before hooks changes as the input grows.
How does the setup and repeated use of these hooks affect the total work done?
Analyze the time complexity of the following Ruby test setup using let and before hooks.
let(:numbers) { (1..n).to_a }
before do
@sum = 0
numbers.each do |num|
@sum += num
end
end
it 'calculates sum' do
expect(@sum).to eq(n * (n + 1) / 2)
end
This code creates an array of numbers from 1 to n, sums them before each test, and checks the sum.
Look at what repeats when the test runs.
- Primary operation: Looping through the array to sum numbers.
- How many times: Once before each test example runs.
As n grows, the number of numbers to add grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the before hook grows in a straight line as the input size grows.
[X] Wrong: "The let block runs only once, so it doesn't affect time much."
[OK] Correct: The let block runs lazily once per test example (memoized after first use within the example), so the cost repeats for each test.
Understanding how setup code like before hooks scales helps you write tests that run efficiently as your project grows.
"What if we moved the summing code inside the let block instead of the before hook? How would the time complexity change?"