0
0
Rubyprogramming~30 mins

Mocking and stubbing in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Mocking and Stubbing in Ruby
📖 Scenario: You are writing tests for a simple Ruby program that fetches weather data from an external service. Since the real service is slow and unreliable for testing, you will use mocking and stubbing to simulate its behavior.
🎯 Goal: Build a test that uses mocking and stubbing to simulate the weather service response and verify your program handles it correctly.
📋 What You'll Learn
Create a class WeatherService with a method fetch_temperature(city) that normally returns a temperature.
Create a test class WeatherServiceTest using minitest.
Stub the fetch_temperature method to return a fixed value for testing.
Mock the fetch_temperature method call and verify it was called with the correct argument.
💡 Why This Matters
🌍 Real World
Mocking and stubbing help you test your code without relying on slow or unreliable external services, making tests faster and more reliable.
💼 Career
Many software development jobs require writing automated tests. Knowing how to mock and stub is essential for testing code that interacts with external systems.
Progress0 / 4 steps
1
Create the WeatherService class
Create a class called WeatherService with a method fetch_temperature(city) that returns the string "Real temperature for #{city}".
Ruby
Need a hint?

Define a class and a method that returns a string including the city name.

2
Set up the test class with minitest
Create a test class called WeatherServiceTest that inherits from Minitest::Test. Inside it, create a method setup that initializes an instance variable @service as a new WeatherService.
Ruby
Need a hint?

Use require 'minitest/autorun' and define a test class inheriting from Minitest::Test.

3
Stub the fetch_temperature method
Inside WeatherServiceTest, add a test method called test_stub_fetch_temperature. In it, stub the fetch_temperature method on @service to always return "Stubbed temperature 25C" when called with any city. Then call @service.fetch_temperature('London') and assign the result to temp.
Ruby
Need a hint?

Use object.stub :method, return_value do ... end to stub a method temporarily.

4
Mock the fetch_temperature method call
Add a test method called test_mock_fetch_temperature_called_with_city inside WeatherServiceTest. Use Minitest::Mock to create a mock object. Expect the fetch_temperature method to be called once with argument 'Paris' and return "Mocked temperature 20C". Replace @service with the mock, call @service.fetch_temperature('Paris'), and verify the mock.
Ruby
Need a hint?

Create a Minitest::Mock object, set an expectation with expect, and call verify to check it.