Home > Software engineering >  RSpec: Expecting a method to be called causes that method to not actually be called
RSpec: Expecting a method to be called causes that method to not actually be called

Time:09-21

I have some code that could be represented in very simple terms as:

def method_a(key)
  hash = method b(key)
  hash.delete(key) 
end

def method_b(key)
 return { key => 1 }
end

and then an rspec test like

it 'calls method_b'
  expect(someClass).to receive(:method_b).with(key)
  method_a(key)
end

However I then get an error in the second line of method_a because it's trying to call delete on a nil object. When I debug, I can see that the logic inside method_b is never actually being invoked. It's not failing somewhere in method_b, it's literally not calling it at all. If I get rid of the expect statement in the test, this error goes away. It seems like the expect statement is causing it to just skip over the actual call to method_b, leaving me with a nil value instead of the hash I'm expecting.

Is there a way I can stop it from skipping over method_b, or at least terminate execution once the expect statement is successful, so I don't run into the error on the next line?

CodePudding user response:

When you set a message expectation, it overrides the original code, unless you explicitly tell RSpec not to:

expect(someClass).to receive(:method_b).with(key).and_call_original
  • Related