Skip to content

Instantly share code, notes, and snippets.

@GrantBirki
Last active October 9, 2024 17:53
Show Gist options
  • Save GrantBirki/982e178fc7ad990596abeba0a94f2202 to your computer and use it in GitHub Desktop.
Save GrantBirki/982e178fc7ad990596abeba0a94f2202 to your computer and use it in GitHub Desktop.
Ruby Logger Mocking

Ruby Logger Mocking

TL;DR Best Option

The following statement is generally the best overall for mocking:

let (:log) { instance_double(Logger).as_null_object }
# - Creates an instance double of Logger with interface validation
# - Converts it into a null object that absorbs any unexpected method calls

Ensures interface compliance with Logger while absorbing any unexpected method calls.

Interface validation in this context means that when you use instance_double(Logger), RSpec ensures that any methods you stub or call on the double exist on the actual Logger class. This helps catch errors where you might be using methods that don't exist on Logger, ensuring your test double accurately reflects the real object's interface.

Other Mocking Options

let (:log) { double.as_null_object }
# - Creates a generic test double without interface validation
# - Converts it into a null object
let (:log) { instance_double(Logger) }
# - Creates an instance double of Logger with interface validation
# - Does not absorb unexpected method calls (will raise an error if an undefined method is called)
let (:log) { double("Logger").as_null_object }
# - Creates a generic test double named "Logger" without interface validation
# - Converts it into a null object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment