Mocking and stubbing help you test your code by pretending parts of it work in a certain way. This makes testing easier and faster.
0
0
Mocking and stubbing in Ruby
Introduction
When you want to test a method without running its real code.
When a method depends on external services like a database or web API.
When you want to check if a method was called with the right inputs.
When you want to control what a method returns during a test.
When you want to avoid slow or unreliable parts during testing.
Syntax
Ruby
require 'minitest/autorun' require 'mocha/minitest' class MyTest < Minitest::Test def test_example obj = mock() obj.stubs(:method_name).returns('value') assert_equal 'value', obj.method_name end end
mock() creates a fake object.
stubs(:method_name) tells the fake object to pretend the method returns a value.
Examples
This makes
obj.greet always return 'Hello!'.Ruby
obj = mock() obj.stubs(:greet).returns('Hello!') puts obj.greet
This checks that
add is called with 2 and 3, then returns 5.Ruby
obj = mock() obj.expects(:add).with(2, 3).returns(5) puts obj.add(2, 3)
This makes
obj.time return a fixed date and time.Ruby
obj = mock() obj.stubs(:time).returns(Time.new(2024, 1, 1)) puts obj.time
Sample Program
This program shows how to use stubs and mocks in Ruby tests. The add method is stubbed to return 10 instead of 5. The multiply method is mocked to expect specific inputs and return 20.
Ruby
require 'minitest/autorun' require 'mocha/minitest' class Calculator def add(a, b) a + b end def multiply(a, b) a * b end end class CalculatorTest < Minitest::Test def test_add_with_stub calc = Calculator.new calc.stubs(:add).with(2, 3).returns(10) result = calc.add(2, 3) puts "Stubbed add result: #{result}" end def test_multiply_with_mock calc = mock() calc.expects(:multiply).with(4, 5).returns(20) result = calc.multiply(4, 5) puts "Mocked multiply result: #{result}" end end CalculatorTest.new('test_add_with_stub').test_add_with_stub CalculatorTest.new('test_multiply_with_mock').test_multiply_with_mock
OutputSuccess
Important Notes
Use stubs when you want to replace a method's return value without caring if it was called.
Use expects when you want to check that a method is called with specific arguments.
Remember to require mocha/minitest to use mocking and stubbing with Minitest.
Summary
Mocking and stubbing help test code by faking parts of it.
Stubs replace method results; mocks check method calls.
They make tests faster and more reliable by avoiding real dependencies.