Ruby Mocking and Stubbing
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →Mocking and stubbing are essential techniques in Ruby for creating effective unit tests. These methods allow developers to isolate code, simulate behavior, and improve test reliability.
What are Mocking and Stubbing?
Mocking creates objects that mimic the behavior of real objects in controlled ways. Stubbing, on the other hand, replaces specific method behaviors with predefined responses.
Why Use Mocking and Stubbing?
- Isolate code under test
- Simulate complex scenarios
- Speed up test execution
- Test error handling
Mocking in Ruby
Ruby provides several libraries for mocking, with RSpec being one of the most popular. Here's a simple example using RSpec:
require 'rspec'
class WeatherService
def get_temperature(city)
# Imagine this method makes an API call
end
end
describe WeatherService do
it "returns the temperature for a city" do
weather_service = instance_double(WeatherService)
allow(weather_service).to receive(:get_temperature).with("London").and_return(20)
expect(weather_service.get_temperature("London")).to eq(20)
end
end
In this example, we create a mock object using instance_double and define its behavior using allow.
Stubbing in Ruby
Stubbing is often used to replace method calls with predefined return values. Here's an example:
require 'rspec'
class User
def full_name
"John Doe"
end
end
describe User do
it "returns a stubbed full name" do
user = User.new
allow(user).to receive(:full_name).and_return("Jane Smith")
expect(user.full_name).to eq("Jane Smith")
end
end
This code demonstrates how to stub the full_name method to return a different value during testing.
Best Practices
- Only mock or stub what's necessary
- Use mocks for behavior verification
- Use stubs for state verification
- Keep mocks and stubs simple
- Avoid mocking third-party code
Related Concepts
To further enhance your Ruby testing skills, explore these related topics:
By mastering mocking and stubbing, you'll be able to write more robust and reliable tests for your Ruby applications. Remember to use these techniques judiciously and always aim for clear, maintainable test code.