rspec 3 - stub a class method

Ruby on-RailsRubyRspecRspec3

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You should do

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

Check out the doco Method stubs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter SankauskasView Question on Stackoverflow
Solution 1 - Ruby on-RailsArup RakshitView Answer on Stackoverflow