Introducing Vows-bdd

| Comments

My work with Node.js has recently transformed from the occassional experiment to the building of a full-on side project. It’s fascinating to be working with a set of tools that are so rapidly developing; the energy and excitement in the Node ecosystem far outweighs any annoyances with needing to adjust to changing APIs.

Embracing Vows

One of the tools which I’ve really enjoyed learning is Vows.js. Vows.js is a fully async Javascript testing library that allows for blazingly fast execution. (It’s amazing how little changes in test speed can make TDD feel much less onerous.) Vows’ syntax can be a little tough to adjust to, but the speed, combined with the ability to construct “test batches”, make the barrier to entry worth the effort.

While Vows is a near pefect tool for unit testing, I began to run into trouble with full-stack integration testing. Check out the contrived example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
vows.describe("Creating a User")
  .addBatch
    "To create a user":

      "Given the server has started":
        topic:
          server.ready, @callback

        "and the DB is populated":
          topic:
            setupFixtures @callback

          "and another setup function is required":
            topic: ->
              anotherSetup @callback

            "When visiting the form at /user/new":
              topic: ->
                ctx = this
                server.ready ->
                  zombie.visit "http://localhost:#{port}/user/new", ctx.callback
                return

              "then should allow entry of a username": (err,browser,status) ->
                assert.ok browser.querySelector ":input[name=username]"

              "should allow entry of first and last name": (err,b,s) ->
                assert.ok b.querySelector ":input[name=firstName]"
                assert.ok b.querySelector ":input[name=lastName]"

              "should allow entry of a password": (err,b,s) ->
                assert.ok b.querySelector ":input[name=password]"

              "should allow confirmation of a password": (err,b,s) ->
                assert.ok b.querySelector ":input[name=passwordConfirm]"

              "and submitting the form":
                topic: (browser,status) ->
                  browser.fill("username", "test")
                         .fill("firstName", "Justin")
                         .fill("lastName", "Reidy")
                         .fill("password", "foobar")
                         .fill("password", "foobar")
                         .pressButton "Sign Up!", @callback

                "should create a new User": (err,browser,status) ->
                  assert.ok findNewUser()

        .export module

Ouch. All that nesting makes for pretty unreadable code – even in CoffeeScript.

vows-bdd: an easier way to test

I’ve never been a huge Cucumber fan, but modeling integration tests in a “given-when -then” format makes them much easier for me to construct mentally. While the prenup library made long Vows tests easier to read by introducing a fluent interface, I thought that I’d love to marry this fluent approach with BDD’s “given-when-then”.

A couple days later and vows-bdd was born:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Feature("Creating a User")
  .scenario("Create a User via Form")

  .given "the server is running", ->
    server.ready @callback

  .and "the DB is popuplated", ->
    setupFixtures @callback

  .and "another setup function is called", ->
    anotherSetup @callback

  .when "I visit the form at user/new", ->
    zombie.visit "http://localhost:#{port}/user/new", @callback

  .then "I should see a username field", (err,browser,status) ->
    assert.ok browser.querySelector ":input[name=username]"

  .and "I should see entries for first and last name", (err,browser,status) ->
    assert.ok browser.querySelector ":input[name=firstName]"
    assert.ok browser.querySelector ":input[name=lastName]"

  .and "I should see a password entry", (err,browser,status) ->
    assert.ok browser.querySelector, ":input[name=password]"

  .and "I should see a password confirmation", (err,browser,status) ->
    assert.ok browser.querySelector, ":input[name=passwordConfirm]"

  .when "I submit the form", (browser,status) ->
    browser.fill("username", "test")
           .fill("firstName", "Justin")
           .fill("lastName", "Reidy")
           .fill("password", "foobar")
           .fill("password", "foobar")
           .pressButton "Sign Up!", @callback

  .then "a new User should be created", (err,browser,status) ->
    assert.ok findNewUser()

  .complete()
  .finish(module)

Checkout the repo on Github for more documentation and info.

Open-Source is scary!

The vast majority of my career has taken place in enterprise world, where code is rarely, if ever, shared with anyone on the outside, and even using open-source code is considered dangerous. While I’ve contributed to OSS libraries before, I’ve never posted my own creation. It’s fairly nerve-wracking to put your work out in the wild, especially when you’re building on top of such amazing contributions from incredible developers.

In fact, I probably would’ve sat on this little library forever, constantly trying to perfect it, if not for a fantastic blog post written by Charlie Robbins(@indexzero) over at Nodejitsu. I think his post perfectly expresses the spirt and mentality of the Node community right now, and his emphasis on experimentation via small bits of functionality made me realize: this code may not be perfect, and it might not even do that much, but if I find it useful, then maybe someone else will too.

So please – checkout vows-bdd and give it a whirl. Any suggestions or comments would be very much appreciated!

“This” in Anonymous Functions

| Comments

Sometimes it’s difficult to find an easy answer to common coding questions. Because Google ignores most punctuation, even the most exact queries fail to produce relevant results. Questions about the nature and value of this in Javascript present a particularly thorny problem, since “this” is about as common a word as you can find.

A common point of confusion in Javascript is that the value of this depends entirely on a function’s context, and can even be overridden depending on how a function is invoked. Hopefully this post will save time for new Javascript devs trolling through Google’s depths:

In anonymous functions, the value of this refers to the anonymous function itself, and not the calling scope. However, the nature of closures allows the anonymous function to still refer to the calling object.

The above rule is demonstrated with the following nodejs code:

1
2
3
4
var that = this;
that.foo = 'bar';
process.nextTick(function() {
  console.log("this " + this.foo + " and that " + that.foo) });

What Does Coffeescript’s “Do” Do?

| Comments

When reading over some Node.js source code written in Coffeescript, I came across a couple uses of the Coffeescript do operator. While do is a very familiar tool for Ruby developers, I wasn’t sure how Coffeescript used it, so I took at look at its documentation, which states:

When using a JavaScript loop to generate functions, it’s common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don’t just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

“All the generated functions don’t just share the final values.” Huh. This statement didn’t mean a lot to me. A little searching on Google led to a fairly helpful post on Stack Overflow. The question there presented the following Javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var closures = [];
function create() {
  for (var i = 0; i < 5; i++) {
    closures[i] = function() {
      alert("i = " + i);
    };
  }
}

function run() {
  for (var i = 0; i < 5; i++) {
    closures[i]();
  }
}

create();
run();

The question stated that the result of running this code was 5,5,5,5,5 instead of the expect 0,1,2,3,4. The answer which created the “correct” result provided the code below:

1
2
3
4
5
6
7
8
9
function create() {
  for (var i = 0; i < 5; i++) {
    closures[i] = (function(tmp) {
      return function() {
        alert("i = " + tmp);
      };
    })(i);
  }
}

and also explained:

JavaScript’s scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.

OK, this was even less helpful. But after going back and reading the Coffeescript docs again, the concept made sense. As always with Javascript, the context in which a function is called demands as much attention as the function itself. Reading the code in the Stack Overflow post, a developer’s brain automatically thinks of the returned function at the time of evaluation. But in reality, each of those functions created in the create function aren’t called until after the for loop has completed. Thus, by the time each function is called, it evaluates i when i has already finished the loop with a value of 5. The closure-wrapping provided in the answer is exactly what the do keyword in Coffeescript provides!

Here’s an example of the solution’s function, in Coffeescript:

1
2
3
4
5
closures = []
create ->
  for i in [0..5]
    closures[i] = do (i) ->
      -> alert i

Even with this contrived example, I find the Coffeescript easier to read, although of course it’s personal preference. If you wanted to go really crazy with Coffeescript syntax, you could write:

1
  closures = ((do (i) -> -> alert i) for i in [0..5])

Two points for cool implementation, no points for readability!

Classes in Coffeescript

| Comments

Javascript is a prototypal language, a concept which is quite challenging for programmers coming from almost any other language. The most well-known explanation of Javascript’s prototypal nature is written by Douglas Crockford, the famous author of the book Javascript: The Good Parts. Many Javascript libraries attempt to plaster class structures into the language, but they all depend on varying amounts of magic which can make me slightly uncomfortable.

To a certain extent, Javascript’s prototypal nature should be embraced; as a developer begins to understand how prototypes work, they recognize their power over traditional class-based code. That said, classical inheritance wouldn’t be as popular as it is if it weren’t a fantastic means of modeling real world objects, so it’d be nice to “map” Javascript code cleanly to a classical style, without manipulating the language unnecessarily.

Enter Coffeescript’s class directive.

Coffeescript doesn’t add classes to Javascript. However, Coffeescript does combine some syntactic sugar with code generation to allow classical-style coding.

Observe the following Coffeescript:

1
2
3
4
5
6
7
8
9
10
class Ninja
  constructor: (@numOfShurikens) ->

  throwShuriken: ->
    @numOfShurikens--

class Ronin extends Ninja

  constructor: (numOfShurikens) ->
    super numOfShurikens+1 #ronins know to carry a spare

I find Coffeescript code to be quite readable, but if you’re completely unfamiliar with the syntax, be sure to check out its fantastic documentation. So with the Coffeescript above, we’ve created two “classes”: a superclass, and a subclass which modifies its parent’s constructor while inheriting a function. What I find exciting about this example is that Coffeescript isn’t actually creating any “pseudoclass” objects behind the scenes; it’s simply mapping existing Javascript concepts into a more developer-friendly DSL.

Here, take a look at the generated JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var Ninja, Ronin;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
  for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
  function ctor() { this.constructor = child; }
  ctor.prototype = parent.prototype;
  child.prototype = new ctor;
  child.__super__ = parent.prototype;
  return child;
};
Ninja = (function() {
  function Ninja(numOfShurikens) {
    this.numOfShurikens = numOfShurikens;
  }
  Ninja.prototype.throwShuriken = function() {
    return this.numOfShurikens--;
  };
  return Ninja;
})();
Ronin = (function() {
  __extends(Ronin, Ninja);
  function Ronin(numOfShurikens) {
    Ronin.__super__.constructor.call(this, numOfShurikens + 1);
  }
  return Ronin;
})();

See? No weird manipulation of Object prototypes, creation of fake classes, anything like that. Just proper Javascript. Still, I found some of the idioms here a little confusing when I first started looking at generated Coffeescript code.

First, why are the “classes” implemented as self-executing functions? Coffeescript is simply protecting the code against potential namespace violations. Everything that happens within the Coffeescript “class” is actually executable Javascript code – similar to how Ruby’s classes work, actually. The “class” that’s returned, then, is really just your constructor function, its modified prototype, and any properties attached to the function object. Pretty straightforward. The major downside with this approach is that you can’t create any private variables! (Normally in JS you can hide a pseudo-private variable within a constructor function’s closure, but Coffeescript’s class implementation prevents this.) Coffeescript’s solution is to simply refer to “private” variables with an underscore and hope developers act like adults, but I’m guessing this open-mindedness will be tightened up a bit as Ecmascript 5 becomes the standard.

But… what is that mess of generated code at the top? The first part is pretty clear – just copy object properties from one “class” to another, so that (for example) Ninja.belt will be inherited by Ronin.belt. And assigning a __super pointer to the parent class is straightforward. But what is that “constructor” code? Why not just point the “subclass” prototype to the parent prototype?

It turns out this approach is the cleanest means of maintaining the prototype chain across functions. Since there’s only one prototype object for any function, simply assigning Ronin.prototype=Ninja.prototype will share a single object instance, so adding properties to Ronin’s prototype would actually also add properties to Ninja’s prototype — they’d be the same object instance. By creating an intermediary object, the prototype chain is kept intact while breaking any chance for incorrectly shared state. Finally, all Javascript objects have a constructor property which point to the “creator” function, whose initial value is determined by the object’s prototype. The intermediary object (which serves as the child’s prototype) thus gets a pointer back to the appropriate function.

Taken in full, Coffeescript’s “class” DSL demonstrates what I love most about the language: distilling Javascript idioms into clean, readable, maintainable code, and eliminating boilerplate, but avoiding any non-Javascript abstractions or manipulations. It just can take awhile to fully understand what’s going on under the hood.

A Note on Npm

| Comments

In the last week, I’ve been experimenting a greal deal with node.js and CoffeeScript. I’ve been thoroughly enjoying the node programming approach and the general “feel” of the CoffeeScript language (or really, dialect would be a better term, since CoffeeScript is really just Javascript). I’ll be writing much more about my experiments soon.

In the meantime, a quick note about getting up and running yourself. I’m using npm to manage dependencies for my node projects. If you have an old version of npm sitting around, you should note that it handles the installation of depencies differently now than it did pre-1.0. npm install “module” defaults to installing the dependency in the local directory – which is fine for a particular project, but doesn’t help you when you want to invoke a module from the command line or use a version acorss multiple projects. Globally installing a module requires you to supply a “-g” argument: npm install -g “module”. You can learn more about the rationale for the change on the node.js blog.

Attr_accessor Shortcut in Ruby

| Comments

Pivotal Labs’ blog provides one of the most consistent sources of quality code writing in my RSS reader. Whether in their Daily Standup posts, or their longer-form articles, I’m constantly finding tidbits of quality Ruby and JS code. A couple weeks ago, Jeff Dean wrote a solid piece on breaking out your form logic in Rails models and controllers. If you’re a Ruby developer, you should read the post in entirety. What most stuck out to me, though, was a little syntactic sugar that I hadn’t enountered before for stating your public attributes:

1
2
3
ATTRIBUTES = [:name, :email, :terms_of_service, :anti_bot_question_id, :anti_bot_answer, :ip_address]

attr_accessor *ATTRIBUTES

I’ll definitely be adding that to my shortcut list.

Mark Zuckerberg Eats What He Kills

| Comments

I don’t have an issue with anything people choose to eat, but I do think they should take responsibility and be thankful for what they eat rather than trying to ignore where it came from.

–Mark Zuckerberg, on his new food philosophy.

Interesting article from Fortune (of all places) on Mark Zuckerberg’s approach to eating, which he adopted as a sort of New Year’s resolution. Zuckerberg is apparently only eating meat from animals he has slaughtered himself. (How this sort of thing registers as financial news, I have no idea.

According to the article, Mark adopts a challenge for himself every year, in order to improve himself and better his understanding of the world, and this year’s challenge was to come to terms with the food he eats. “[M]y personal challenge is around being thankful for the food I have to eat. I think many people forget that a living being has to die for you to eat meat, so my goal revolves around not letting myself forget that and being thankful for what I have,” Zuckerberg wrote to Fortune.

Software engineers have a (partially undeserved) reputation of being ignorant pigs when it comes to food - with snack rooms at many offices stuffed with Funyuns and Twinkies - so it’s great to see one of the world’s most prominent engineers (and a celebrity in his own right) so consciously investigate the source of his food.

Hello World

| Comments

So here I am, back to actually writing. I somehow managed to write consistently for awhile over on tumblr, but I’ve only posted there once in the last six months. There have been a lot of “I’ve been meaning tos” and “I plan ons” and “I’m looking to starts” over that same period of time, so before the holiday weekend I decided to adopt an agile attitude toward my blog: I shutup and put the least implemented solution on the web. I had just a few requirements: working links, readable text, and a functional RSS feed. I’ve hit all those, so look to see an actual design implemented in the future, along with service hooks and all that good stuff. But in the meantime: content! And no excuses for me not to provide content.

This IS the first time I’ve actually been comfortable with my blogging setup. I decided to abandon a CMS entirely and start using Jekyll, which is basically just a static site generator written in Ruby. There’s some great benefits to this approach:

  • hosting of the site becomes a complete commodity: I’m on Github pages now, but could switch to Heroku or my own host with practically zero work;
  • I own my content, and I don’t need to worry about it ever being lost or taken down;
  • all of my content is stored in Git, so I know it’s safe and version controlled;
  • styling is as easy as editing HTML and CSS, so there’s no constraints of a CMS templating system;
  • I’m writing my posts in Vim, which may seem torturtous to some, but I’ve come to appreciate its power and lack of visual distraction.

Beyond these benefits, I also think that I did not truthfully represent myself on my Tumblr blog. I posted content in an attempt to earn re-blogs, and thus “go viral”. Beyond that, I self-edited in an attempt to prevent any post from accidentally being reblogged and triggering a flame war. Here, I have no illusions of an audience; I recognize that barely anyone will ever read this, and I’m completely fine with that. Instead, I hope that the people who DO end up reading this site come away with helpful technical information, solutions to vexing bugs, or the occassional good recipe. (Although I will be adding Disqus comments at some point).

So welcome to version 3 of this blog. I look forward to my attempts at providing some stimulating writing!