ChatGPT解决这个技术问题 Extra ChatGPT

rspec 3 - stub a class method

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?


A
Arup Rakshit

You should do

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

Check out the doco Method stubs.


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
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.)
@sixty4bit Is there a reason you can't call it with arguments?
@sixty4bit expect(Class.foo).to receive(bar).with(arg1, arg2).and_return({..object})

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now