0
0
Rubyprogramming~5 mins

Test doubles concept in Ruby

Choose your learning style9 modes available
Introduction

Test doubles help you pretend parts of your program work in a simple way so you can test other parts easily.

When you want to test a part of your program without using a real database.
When a part of your program talks to an external service like a website or API.
When you want to check if a method was called without running its real code.
When the real part is slow or hard to set up for testing.
When you want to control what a method returns during a test.
Syntax
Ruby
double('Name', method_name: return_value)
allow(double).to receive(:method_name).and_return(return_value)

double('Name') creates a fake object with a name for clarity.

You can set methods and their return values directly or use allow to set expectations.

Examples
This creates a fake user object that returns 'Alice' when you ask for its name.
Ruby
user = double('User', name: 'Alice')
puts user.name  # prints 'Alice'
This sets up a fake calculator where the add method always returns 5, no matter the input.
Ruby
calculator = double('Calculator')
allow(calculator).to receive(:add).and_return(5)
puts calculator.add(2, 3)  # prints 5
Sample Program

This program uses a test double to fake a payment gateway. It checks that when pay is called, the fake gateway's charge method returns 'Success'.

Ruby
require 'rspec/mocks/standalone'

class Order
  def initialize(payment_gateway)
    @payment_gateway = payment_gateway
  end

  def pay(amount)
    @payment_gateway.charge(amount)
  end
end

# Create a test double for payment_gateway
payment_gateway = double('PaymentGateway')

# Tell the double to expect charge and return 'Success'
allow(payment_gateway).to receive(:charge).with(100).and_return('Success')

order = Order.new(payment_gateway)
result = order.pay(100)
puts result
OutputSuccess
Important Notes

Test doubles do not run real code, so they make tests faster and simpler.

Use descriptive names for doubles to keep tests clear.

You can check if methods were called on doubles to verify behavior.

Summary

Test doubles let you replace real parts with simple fake ones for testing.

They help isolate the part you want to test without outside effects.

You can control what doubles return and check how they are used.