Mocking and stubbing in Ruby - Time & Space Complexity
When using mocking and stubbing in tests, it's important to understand how the time to run tests changes as the number of mocks grows.
We want to see how the test execution time scales with more mocks or stubs.
Analyze the time complexity of the following Ruby test code using mocks and stubs.
1. require 'minitest/autorun'
2. class User
3. def greet
4. "Hello!"
5. end
6. end
7.
8. class UserTest < Minitest::Test
9. def test_greet
10. user = Minitest::Mock.new
11. user.expect(:greet, "Hi!")
12. assert_equal "Hi!", user.greet
13. user.verify
14. end
15. end
This code tests a User class method by replacing it temporarily with a mocked response.
Look for repeated actions that affect time.
- Primary operation: Running each test method with its stub setup and teardown.
- How many times: Once per test case, but if many tests or many stubs are used, this repeats for each.
Imagine adding more tests or stubs.
| Number of Tests (n) | Approx. Operations |
|---|---|
| 10 | About 10 stub setups and test runs |
| 100 | About 100 stub setups and test runs |
| 1000 | About 1000 stub setups and test runs |
Pattern observation: The total time grows roughly in direct proportion to the number of tests using mocks or stubs.
Time Complexity: O(n)
This means the test time grows linearly as you add more mocked or stubbed tests.
[X] Wrong: "Mocking or stubbing makes tests run instantly, so time doesn't grow with more tests."
[OK] Correct: Each mock or stub still takes setup and teardown time, so more tests mean more total time.
Understanding how mocks and stubs affect test time helps you write efficient tests and explain trade-offs clearly in interviews.
What if we replaced stubs with real method calls? How would the time complexity change?