Multiple 'it' statements inside of for loops are tied to each other #420

Closed
jkarmel opened this Issue May 10, 2012 · 7 comments

3 participants

@jkarmel

When I have some code in a for loop where each statement executes properly, looping over the 'it' statements seems to work fine.

  var field, writableFields, _i, _len;

  writableFields = 'email phone'.split(/\s+/);

  for (_i = 0, _len = writableFields.length; _i < _len; _i++) {
    field = writableFields[_i];
    it("can write to " + field, function(done) {
      var fakeEntry, methodName;
      methodName = "set" + field;
      clientGroup.now.should.respondTo(methodName);
      fakeEntry = "fake " + field;
      return clientGroup.now[methodName](fakeEntry, function() {
        return Client.findOne({}, function(error, client) {
          client[field].should.equal(fakeEntry);
          return done();
        });
      });
    });
  }

However if the 'it' statement fails for one of the loops it appears to fail for all of them. For example changing

writableFields = 'email phone'.split(/\s+/)

to

writableFields = 'email phone flake'.split(/\s+/)

All three mocha tests fail
1) ClientGroup can write to email:
actual expected
functdefioned

2) ClientGroup can write to phone:
actual expected
functdefioned

3) ClientGroup can write to tel:
actual expected
functdefioned

Whats going on?

@tj
tj commented May 10, 2012

js plzz

@jkarmel

flixed

@exogen

Classic problem of all three closures seeing the last value of the loop variable. Do something like:

(function(field) {

it(..., function(done) { ... });

})(writeableFields[_i]);
@exogen

...or if you're using CoffeeScript, use do.

@tj
tj commented May 11, 2012

what he said :D

@jkarmel

Haha, oops!

@jkarmel jkarmel closed this May 11, 2012
@jkarmel

thanks for helping me out with my newb error!

@kanetkarster kanetkarster referenced this issue in espenhogbakk/tortuga May 22, 2014
Merged

Sort #2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment