rspec 3 - stub a class method
Asked Answered
D

1

119

I am upgrading from rspec 2.99 to rspec 3.0.3 and have converted instance methods to use allow_any_instance_of, but haven't figured out how to stub a class method. I have code like this:

module MyMod
  class Utils
    def self.find_x(myarg)
      # Stuff
    end
  end
end

and my rspec 2 test does this:

MyMod::Utils.stub(:find_x).and_return({something: 'testing'})

What is the Rspec 3 way of doing this?

Draggle answered 31/7, 2014 at 18:48 Comment(0)
M
205

You should do

allow(MyMod::Utils).to receive(:find_x).and_return({something: 'testing'})

Check out the doco Method stubs.

Makepeace answered 31/7, 2014 at 18:49 Comment(4)
I'm trying to implement this but when I write that mock and then write expect(Class.foo).to eq(bar) I get a "wrong number of arguments error" because the foo method normally wants 2 arguments....but I just want it to return what I put in the stubUnwearied
FWIW, this form would crash my ruby interpreter. However, and_return is not strictly needed and can be left off. (My ruby interpreter also doesn't crash.)Hadron
@Unwearied Is there a reason you can't call it with arguments?Alvey
@Unwearied expect(Class.foo).to receive(bar).with(arg1, arg2).and_return({..object})Inferno

© 2022 - 2024 — McMap. All rights reserved.