New Project! šŸ–¼ļø Run your AI agents on an infinite canvasTry it now

Stubbing without RSpec

August 20, 2014āˆ™1 min read

InĀ rspec you can typically call the stub method to stub something out. However, thisĀ method only works inside an example or Ā a before(:each) block. Try usingĀ rspec stubs anywhere else andĀ youĀ get the following error message

The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported.

What if you wanted to temporarily stub out one object inside a before(:all) (since you like those fast test, don't you ;) or globally for the entire test suite for say disabling image processing. How would you do that?

Simple, Ruby has this magic word called metaprogramming to rescue us.

Instead of doing:

image = Image.new
image.stub(:process).and_return(true)

Just do:

image = Image.new
def image.process
  true
end

That is it. We just overwrote the definition of the process method for only thisĀ one image instance. No side-effect or stub-code leakage will occur here.

Ā© 2026 Michael Yagudaev