0
0
Rubyprogramming~5 mins

Mocking and stubbing in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Mocking and stubbing
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Imagine adding more tests or stubs.

Number of Tests (n)Approx. Operations
10About 10 stub setups and test runs
100About 100 stub setups and test runs
1000About 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.

Final Time Complexity

Time Complexity: O(n)

This means the test time grows linearly as you add more mocked or stubbed tests.

Common Mistake

[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.

Interview Connect

Understanding how mocks and stubs affect test time helps you write efficient tests and explain trade-offs clearly in interviews.

Self-Check

What if we replaced stubs with real method calls? How would the time complexity change?