Collecting with Moksi

Manfred Stienstra, 18 Apr 2009, 14:54 in testing and javascript (edit).

For some reason language designers and implementers usually do a bad job a designing the API of the standard library. That’s why I’m pretty happy with the bareness of the JavaScript standard library: it leaves room for libraries like Prototype and JSQuery to step in and tailor the API’s to the task the everyday programmer is trying to achieve.

I do mind that JavaScript doesn’t allow you to introspect or invoke event handlers because that’s bad for people who like to write tests.

Getting your test to introspect observers is not that hard, you just collect all the calls to Event.observe and element.observe.

Event.observers = [];
Moksi.stub(Event, 'observe', function(element, name, handler) {
  Event.observers.push([element, name, handler]);
});
$$('input').each(function(element) {
  Moksi.stub(element, 'observe', function(name, handler) {
    Event.observers.push([element, name, handler]);
  });
});

Now you can look in Event.observers and see what handlers got defined on which elements.

this.assertObserves = function(expectedElement, expectedName) {
  this.assert(Event.observers.any(function(args) {
    return (args[0] == expectedElement) && (args[1] == expectedName);
  }));
};

this.assertObserves($('input[name="artist_name"]'), 'blur');

And you can also call them from a test to make sure they work as expected. To keep the example short we assume you don’t have to pass arguments to the handler.

this.callObserver = function(element, eventName) {
  var observer = Event.observers.detect(function(args) {
    return (args[0] == element) && (args[1] == eventName);
  });
  observer[2]();
};

this.callObserver($('input[name="artist_name"]'), 'blur');

You can find Moksi on GitHub and testunit.js is part of script.aculo.us.

No comments yet

Ruby on OS X Conference registration now open

Thijs van der Vossen, 09 Apr 2009, 15:50 in ruby on rails and events (edit).

Registration for the Ruby on OS X Conference is now open. Tickets are selling much faster than expected, so don’t wait too long if you’re thinking about attending.

The conference is about building Mac apps with Ruby and Cocoa. We’ve tried to organise a conference that’s of interest to Ruby developer who want to get started with Mac desktop application development, as well as experienced RubyCocoa and MacRuby developers, and Cocoa/Objective-C developers interested in using Ruby.

We’ve gathered a great collection of speakers from the USA, Japan, and Europe, all of which are active in the RubyCocoa and MacRuby communities. This will be a small and intimate conference with sessions in the morning and afternoon, followed by an informal hackfest in the evening.

No comments yet