Search code examples
ruby-on-railsrubyrspecrspec-rails

How to test non static method was being called by other method using Rspec


I'm trying to test a method being called by another method. I don't want to test what the other method do, because this is a separate unit test.

so let's say I have something like:

class MyService
    def method_a
      a = 1
      b = method_b
      
      return a + b
    end

    def method_b
      return 2
    end

end

Now, I want to test method_a - I want to verify that method_b was executed.

I know that this should work if the methods were static. But in my case, it's not static.

allow(MyService).to receive(:method_b)

I keep getting this error: MyService does not implement method_b And I understand that's because the method is not static, but I can't find anything in the documentation that fit my use case.


Solution

  • I think main problem problem is that you expecting for class method to be called and not instance

    describe MyService do
      it "should call method_b" do
        expect(subject).to receive(:method_b).and_return(2)
        subject.method_a
      end
    end
    
    # P.S. it's the same as:
    
    describe MyService do
      it "should call method_b" do
        service = MyService.new # instead of MyService.new you can also write described_class.new
        expect(service).to receive(:method_b).and_return(2)
        service.method_a
      end
    end