What if you could test your code without waiting for slow or unreliable outside services?
Why Mocking and stubbing in Ruby? - Purpose & Use Cases
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.
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.
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.
response = BankAPI.get_balance(user_id) if response == expected puts 'Test passed' end
bank_mock = Minitest::Mock.new bank_mock.expect(:get_balance, 100, [user_id]) result = bank_mock.get_balance(user_id) assert_equal 100, result
It enables fast, reliable tests that don't depend on outside systems and let you safely try different scenarios.
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.
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.