New! Learn to build search with Rails + Postgres.Get Early Access!

Stubbing without RSpec

August 20, 20141 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.

© 2021 Michael Yagudaev