0
0
Rubyprogramming~3 mins

Why Mocking and stubbing in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could test your code without waiting for slow or unreliable outside services?

The Scenario

Imagine you are testing a program that talks to a bank to check your balance. Every time you run the test, you have to wait for the bank to respond, and sometimes the bank is slow or down.

The Problem

Waiting for the real bank every time makes tests slow and unreliable. If the bank changes or is offline, your tests break even if your code is fine. Manually creating fake responses each time is tiring and messy.

The Solution

Mocking and stubbing let you create pretend versions of the bank that respond instantly and exactly how you want. This way, tests run fast and always behave the same, so you can focus on your code.

Before vs After
Before
response = BankAPI.get_balance(user_id)
if response == expected
  puts 'Test passed'
end
After
bank_mock = Minitest::Mock.new
bank_mock.expect(:get_balance, 100, [user_id])
result = bank_mock.get_balance(user_id)
assert_equal 100, result
What It Enables

It enables fast, reliable tests that don't depend on outside systems and let you safely try different scenarios.

Real Life Example

When building an app that sends emails, you don't want to send real emails every test. Mocking the email service lets you check if your app tries to send emails without actually sending them.

Key Takeaways

Manual testing with real systems is slow and fragile.

Mocking and stubbing create fake parts that behave predictably.

This makes tests faster, stable, and easier to write.