0
0
Rubyprogramming~5 mins

Test doubles concept in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Test doubles concept
O(n)
Understanding Time Complexity

When using test doubles, we want to see how the time to run tests changes as the number of doubles grows.

We ask: How does adding more test doubles affect test execution time?

Scenario Under Consideration

Analyze the time complexity of the following Ruby code using test doubles.


    class OrderProcessor
      def initialize(payment_gateway)
        @payment_gateway = payment_gateway
      end

      def process(order)
        @payment_gateway.charge(order.amount)
      end
    end

    payment_double = double('PaymentGateway')
    allow(payment_double).to receive(:charge).and_return(true)

    processor = OrderProcessor.new(payment_double)
    processor.process(order)
    

This code uses a test double to replace a real payment gateway in order processing.

Identify Repeating Operations

Look for repeated calls or loops involving test doubles.

  • Primary operation: Calling the double's method charge.
  • How many times: Once per order processed, or once per test run.
How Execution Grows With Input

As the number of test doubles or calls grows, the total calls to doubles grow linearly.

Input Size (number of calls)Approx. Operations
1010 calls to doubles
100100 calls to doubles
10001000 calls to doubles

Pattern observation: The number of operations grows directly with the number of calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to run tests grows in a straight line as you add more calls to test doubles.

Common Mistake

[X] Wrong: "Test doubles make tests run instantly, no matter how many calls there are."

[OK] Correct: Each call to a double still takes time, so more calls mean more time, even if faster than real objects.

Interview Connect

Understanding how test doubles affect test speed helps you write efficient tests and explain your choices clearly.

Self-Check

What if we replaced test doubles with real objects that perform network calls? How would the time complexity change?