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.
Practice
stubbing in Ruby testing?Solution
Step 1: Understand stubbing concept
Stubbing means replacing a method's output with a fake value to control test behavior.Step 2: Differentiate from mocking
Mocking checks method calls, but stubbing focuses on return values.Final Answer:
To replace a method's return value with a fake one -> Option DQuick Check:
Stubbing = fake return value [OK]
- Confusing stubs with mocks
- Thinking stubs run real code
- Believing stubs slow tests
foo on an object obj to return 42 using RSpec?Solution
Step 1: Recall RSpec stubbing syntax
In RSpec, stubbing usesallow(object).to receive(:method).and_return(value).Step 2: Check each option
allow(obj).to receive(:foo).and_return(42) matches correct syntax; others use outdated or incorrect methods.Final Answer:
allow(obj).to receive(:foo).and_return(42) -> Option AQuick Check:
RSpec stub = allow + receive + and_return [OK]
- Using deprecated stub syntax
- Confusing expect with allow for stubs
- Using mock instead of allow for stubs
class Calculator
def add(a, b)
a + b
end
end
calc = Calculator.new
allow(calc).to receive(:add).with(2, 3).and_return(10)
puts calc.add(2, 3)
puts calc.add(4, 5)Solution
Step 1: Analyze stubbed method call
The methodaddis stubbed to return 10 only when called with arguments 2 and 3.Step 2: Check calls and outputs
First callcalc.add(2, 3)returns 10 due to stub. Second callcalc.add(4, 5)is not stubbed, so runs original method returning 9.Final Answer:
10 9 -> Option BQuick Check:
Stubbed args return 10; others run real method [OK]
- Assuming all calls return stub value
- Ignoring method arguments in stub
- Expecting syntax error
user = double('User')
expect(user).to receive(:login).with('admin')
user.login('guest')Solution
Step 1: Understand the expectation
The test expectsloginto be called with argument 'admin'.Step 2: Check actual method call
The method is called with 'guest', which does not match the expectation.Final Answer:
The method login is called with wrong argument -> Option CQuick Check:
Expect argument mismatch causes failure [OK]
- Calling method with different arguments
- Confusing stub and expect syntax
- Ignoring error raised by RSpec
fetch_data on a Service object. How can you use mocking and stubbing together to test your method without calling the real API?Solution
Step 1: Stub the API call to avoid real network
Stubfetch_datato return controlled fake data, so tests run fast and reliably.Step 2: Mock to verify the method call
Use mock to checkfetch_datawas called exactly once, ensuring your method triggers it.Final Answer:
Stub fetch_data to return fake data and mock to check it was called once -> Option AQuick Check:
Stub return + mock call count = test isolation [OK]
- Calling real API in tests
- Mocking without stubbing return value
- Ignoring call verification
Ready to prove it?
Pass the test and this pattern moves unknown
