Home > Back-end >  RSpec - mock a private class method call inside a request spec?
RSpec - mock a private class method call inside a request spec?

Time:02-25

This is my class

class MyClass

  def run

    to_be_mocked("arg")

    ## etc

  end

  private

  def to_be_mocked(arg)
    # implementation
  end

end

and my Controller, which is what I am writing the request specs for, call this class. This are my request specs:

  context "Some context" do
    context "some sub context" do
      before :each do
        allow(MyClass). to receive(: to_be_mocked).with(account.url).and_return(false)
      end
      it "responds with a 200" do
        do_request
        expect(JSON.parse(response.body)["field"]).to eq true
        expect(response.status).to eq 200
      end
    end

However my mocking fails with an MyClass does not implement: to_be_mocked

Already tried removing the private keyword, but got the same results.

What am I missing here?

CodePudding user response:

You're mocking on the class, which is how you mock you "static" class-level methods. For example, if your method was def self.foo and you called it via MyClass.foo, then allow(MyClass) is the way to go.

Your method is not a class-level method, it's an instance method. You invoke it by first creating an instead of MyClass and then calling the method on that instance. You need to use allow_any_instance_of to mock the method for all future instances of the class:

allow_any_instance_of(MyClass).to receive(....)
  • Related