This article is a simple explanation of mock and stub used in unit testing.
- A stub is a small program routine that substitutes for a longer program.
- You should use a stub in order to pass to the code under test.
- Mock is a method/object that simulates the behavior of a real method/object.
- A mock is an object that we can set expectations on, and which will verify that the expected actions have indeed occurred.
As for why it is necessary to reproduce method / object:
- If you try to test everything with “real method/data”, you have to prepare all processing and data.
- To make it easier to test objects like time.
If you want to return a specific value when a method of an object is called, prepare a stub like the following:
# When Foo#method is invoked, :return_value will be returned
For example, if you write like this, “count method of Array class will always return 20”.
test_array = 
If you want to expect that a method is called with :argument, and want to return “:return_value” when called, you should prepare the following mock:
Mock of instance method is as follow:
The mock that generates the error like this:
- Raising an error - Configuring responses - RSpec Mocks - RSpec - Relish
- ruby on rails - RSpec: Stub private method - Stack Overflow
🖥 Recommended VPS Service
VULTR provides high performance cloud compute environment for you.
Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour).
In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!