RSpec describe and it blocks in Ruby - Time & Space Complexity
When running tests with RSpec, it's helpful to know how the time to run tests grows as you add more tests.
We want to see how the number of tests affects the total time spent running them.
Analyze the time complexity of this RSpec test structure.
RSpec.describe "Calculator" do
it "adds numbers" do
expect(1 + 1).to eq(2)
end
it "subtracts numbers" do
expect(5 - 3).to eq(2)
end
end
This code defines two simple tests inside a describe block.
Look at what repeats when running tests.
- Primary operation: Each
itblock runs one test. - How many times: Once per
itblock, so as many times as there are tests.
As you add more it blocks, the total test run time grows.
| Number of Tests (n) | Approx. Test Runs |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The total time grows directly with the number of tests.
Time Complexity: O(n)
This means the total time to run tests grows in a straight line as you add more tests.
[X] Wrong: "Adding more describe blocks makes tests run faster because they are separate."
[OK] Correct: All it blocks run independently, so total time depends on how many tests run, not how they are grouped.
Understanding how test time grows helps you write efficient tests and manage test suites well in real projects.
"What if each it block ran multiple assertions? How would the time complexity change?"