116

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?

1 Answer 1

200

You should do

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

Check out the doco Method stubs.

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 stub
    – sixty4bit
    Mar 5, 2015 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, 2015 at 1:26
  • 2
    @sixty4bit Is there a reason you can't call it with arguments? Sep 3, 2015 at 16:00
  • 6
    @sixty4bit expect(Class.foo).to receive(bar).with(arg1, arg2).and_return({..object})
    – zhisme
    Jun 28, 2019 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.