Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between spy and stub?

I have just started using sinon.js and I am completely stumped with the terminology. I have used stubs where in the subview's render methods are stubbed out . But the explanation of the spy is not clear to me. Can anyone explain what exactly is the difference between these two ?

Also was wondering what the approach would be if I want to test if a new model has been added to a collection?

like image 963
Sushanth -- Avatar asked Jan 24 '13 00:01

Sushanth --


1 Answers

I'm not super-familiar with sinon.js, but since these are general TDD terms and not sinon-specific ones, I think I can still answer your quesiton.

The main difference is that a stub exists purely to "get through the code"; the stub itself doesn't do anything except hold dummy values and methods.

Spies on the other hand are stubs that check the values that get put in them, or the methods that get called on them. In other words, the main difference between the two is assert statements: stubs have none, while spies have some (or else they store values for asserts elsewhere in your test code).

In other words:

var Stub = Backbone.Model.extend();
var stub = new Stub({value: 'test value'});
// This can be fed to any view for testing

var Spy = Backbone.Model.extend({
    initialize: function() {
        this.on('change:value', this.handleValueChange);
    },
    handleValueChange: function(value) {
        assert(!isNaN(value));
    };
    value: 'test value'
});
var spy = new Spy({value: 'test value'});
// This can be fed to any view for testing AND it ensures that,
// if that view sets its "value", that that value is a number

Oh, and to answer:

Also was wondering what the approach would be if I want to test if a new model has been added to a collection?

Again, without getting in to Sinon specifically, there are two obvious places where you can "spy" on the model: the model itself, and its collection.

Either you can add an event handler to (or hard-wire in to a test method on) your model which checks this.collection to determine whether/which collection its been added to. Conversely, you could bind an event or overwrite a method on the collection itself, and check this.models.

like image 81
machineghost Avatar answered Sep 21 '22 06:09

machineghost