In RSpec, what's the difference between a mock and a double?
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 t开发者_如何转开发hat disambiguates them.
What's the difference?
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.
精彩评论