117

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?

Peter Sankauskas
  • 2,882
  • 4
  • 27
  • 28

1 Answers1

202

You should do

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

Check out the doco Method stubs.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • 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 stub – sixty4bit Mar 05 '15 at 16:34
  • 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.) – Ray Fix Mar 21 '15 at 01:26
  • 2
    @sixty4bit Is there a reason you can't call it with arguments? – David Moles Sep 03 '15 at 16:00
  • 6
    @sixty4bit `expect(Class.foo).to receive(bar).with(arg1, arg2).and_return({..object})` – zhisme Jun 28 '19 at 09:22