Software creative always looking for a challenge

Posts from: August 19, 2014

Stubbing without RSpec

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:

Just do:

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.