Bird
0
0

You want to test a method that calls an external API method fetch_data on a Service object. How can you use mocking and stubbing together to test your method without calling the real API?

hard📝 Application Q15 of 15
Ruby - Testing with RSpec and Minitest
You want to test a method that calls an external API method fetch_data on a Service object. How can you use mocking and stubbing together to test your method without calling the real API?
AStub <code>fetch_data</code> to return fake data and mock to check it was called once
BCall the real <code>fetch_data</code> method and ignore mocking
CMock <code>fetch_data</code> without stubbing its return value
DDo not use mocking or stubbing; test with real API
Step-by-Step Solution
Solution:
  1. Step 1: Stub the API call to avoid real network

    Stub fetch_data to return controlled fake data, so tests run fast and reliably.
  2. Step 2: Mock to verify the method call

    Use mock to check fetch_data was called exactly once, ensuring your method triggers it.
  3. Final Answer:

    Stub fetch_data to return fake data and mock to check it was called once -> Option A
  4. Quick Check:

    Stub return + mock call count = test isolation [OK]
Quick Trick: Stub return and mock call count together [OK]
Common Mistakes:
  • Calling real API in tests
  • Mocking without stubbing return value
  • Ignoring call verification

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes