In rspec you can either create a mock
or a double
. These two seem to be almost the same thing and I can't find anything in the documentation that disambiguates them.
What's the difference?
RSpec features doubles that can be used as 'stand-ins' to mock an object that's being used by another object. Doubles are useful when testing the behaviour and interaction between objects when we don't want to call the real objects - something that can take time and often has dependencies we're not concerned with.
Mocking is a technique in test-driven development (TDD) that involves using fake dependent objects or methods in order to write a test. There are a couple of reasons why you may decide to use mock objects: As a replacement for objects that don't exist yet.
Stub: a dummy piece of code that lets the test run, but you don't care what happens to it. Substitutes for real working code. Mock: a dummy piece of code that you verify is called correctly as part of the test.
You now may verify doubles, which means "RSpec will check that the methods being stubbed are actually present on the underlying object if it is available", but "no checking will happen if the underlying object or class is not defined".
Both mock
and stub
are aliases of the more generic double
. Like context
and describe
, they can be used interchangeably to make the intent of the specs more clear. This is described in a lot more detail in The RSpec Book.
The seem to be just aliases since :__declared_as
doesn't seem to be used but for messages.
doubles
when we depend on components with nondeterministic characteristics, we may find that files get corrupted, disk fail, networks timeout, and servers go down in the middle of running specs. because these are things that we have no control over, they can lead to inconsistent and surprising results when we run our specs. doubles can disconnect our examples from real implementations of these dependencies.
stub
when the system behaviour based on a sequence. a stub is perfect for this .Because each example can specify a different sequence.example:- In case of random generator, it is clearly a source of non determination. we want to replace the real random generator with stable sequence.
Mocks
some time we need some service from another object that may not yet exist. In cases like this we can introduce mock object. which we can program to behave as the object we are currently expects. so when we focus on interaction mock objects make it much easier to achieve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With