Search code examples
rubyrspecrspec-mocks

Replace instance method with rspec-mock


The RSpec documentation shows how to mock a class method. How can I replace an instance method instead. Here is a code example using rspec-mocks to make this more concrete:

require 'rspec'

class Foo
  def foo
    "foo"
  end

  def foobar
    foo + "bar"
  end
end

RSpec.describe "Foo" do
  it "mocks foo" do
    allow(Foo).to receive(:foo).and_return("bar")
    foo = Foo.new
    expect(foo.foobar).to eq("barbar")
  end
end

This gives "Foo does not implement: foo". Granted, this is contrived for simplification. In the actual class I'm testing, foo makes a HTTP request, so I want to mock it while writing a spec for foobar. I'd like to do this with rspec-mocks, but if another gem can help here, I'm open to that as well.


Solution

  • Just stub the method on the instance instead of the class:

    RSpec.describe "Foo" do
      it "mocks foo" do
        foo = Foo.new
        allow(foo).to receive(:foo).and_return("bar")
        expect(foo.foobar).to eq("barbar")
      end
    end