Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between stub_model and mock_model in RSpec?

What's the difference between stub_model and mock_model in RSpec? So far, I know that stubs are used to just prevent the real method from being called and return a predefined value, and mocks are actually expectations and require that the method is called on the receiver.

I also know that these stubs/mocks are used to allow isolated testing, such as in controllers without touching the model. But I'm still confused with these two methods, when exactly are each used? Details and examples would be very much appreciated. Thanks a lot!

like image 798
gerky Avatar asked Sep 12 '12 10:09

gerky


1 Answers

stub_model

The stub_model method generates an instance of a Active Model model.

While you can use stub_model in any example (model, view, controller, helper), it is especially useful in view examples, which are inherently more state-based than interaction-based.

mock_model

The mock_model method generates a test double that acts like an Active Model model. This is different from the stub_model method which generates an instance of a real ActiveModel class.

The benefit of mock_model over stub_model is that its a true double, so the examples are not dependent on the behaviour (or mis-behaviour), or even the existence of any other code. If you're working on a controller spec and you need a model that doesn't exist, you can pass mock_model a string and the generated object will act as though its an instance of the class named by that string.

rspec docs: stub_model and mock_model

like image 84
danilopopeye Avatar answered Oct 24 '22 06:10

danilopopeye