Pivotal Labs

Main menu

Skip to primary content
Skip to secondary content
  • About
  • Case Studies
  • Team
    • Executives
    • Locations
      • San Francisco (HQ)
      • Boston
      • Boulder
      • Denver
      • London
      • Los Angeles
      • New York
  • Community
    • Blogs
    • Tech Talks
    • Events
  • Careers
    • Lifestyle
    • Principles & Practices
    • Benefits
    • FAQ
    • Apply
  • Tools
  • Contact
    • Press Room
    • Press Releases
    • In The News
    • Press Kit
  • All
  • Labs
  • Standup
  • Tracker
Pivotal Labs

Standup 1/19/2011: How would you google this?

Pivotal Labs
Wednesday, January 19, 2011

Ask for Help

“Anyone using Selenium 2 and Webdriver?”

One of our internal projects is using it.

“How to stop time in Jasmine?”

There were a couple suggestions:

  • use a global function, such as ‘now’
  • send in your own clock object

“Whurl standalone, or more dynos?”

Apparently Whurl is running on a single dyno at Heroku, so a single bad request can tie up Whurl until the request times out. Where are you TildeWill?

“What’s this called?”

Imagin these are records in a relational database, with the records on the left having a one to many relationship with the records on the right. How would you google this?

one to many diagram

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Pivotal Labs

Standup Tuesday, 1/18/2011: Experience with head.js?

Pivotal Labs
Tuesday, January 18, 2011

Ask for Help

“Any experience using head.js?”

No one stepped forward with actual experience.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Mike Gehard

Capybara/Cucumber and waiting for Javascripty stuff to happen

Mike Gehard
Friday, August 20, 2010

A little ditty that makes it really easy to wait for something Javascripty to happen…like a Javascript dialog to appear that gets populated from an AJAX call.

The has_css? method call will wait until the element shows up and if it doesn’t show up before the Capybara timeout expires then it will return false.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Abhijit Hiremagalur

Standup 08/04/2010: Accounting on Rails anybody?

Abhijit Hiremagalur
Wednesday, August 4, 2010

Ask for Help

  • Double-entry/ledger based accounting in Rails (i.e. Quickbooks in Rails for free)

Ideally would be tied in with user/role system where each accounting entry would be tied to a user, but also reconciled against a master account.

Recommendations? Latest and greatest?

One suggestion was to look at the code that Wesabe open sourced code when they closed their doors.

  • Error message when opening Rubymine “Invalid Git Root”

This is likely because the project included a submodule that wasn’t configured correctly, fix this in under Rubymine’s version control preferences.

Add submodule screen in Rubymine

Interesting Things

  • Test 404 handling (e.g. rescue_from ActiveRecord::RecordNotFound, :with => :render_record_not_found) with Cucumber by temporarily setting ActionController::Base.allow_rescue = true. This is usually set to false in features/support/env.rb
  • JSON.pretty_generate hates Rails 3 Hashes

 

  • Use window.postMessage to communicate between IFrames in a standard way

This should work in most modern browsers. Follow the Mozilla docs, NOT the various blog posts about this.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Adam Milligan

iPhone UI Automation tests with Jasmine

Adam Milligan
Sunday, July 18, 2010

Since the language of the new iPhone UI Automation component is JavaScript I figured the easiest way to organize tests is to use a JavaScript testing framework, such as Jasmine. So, I created jasmine-iphone, which is little more than a few simple scripts to make UI Automation and Jasmine play nice.

Once you clone jasmine-iphone from GitHub (it includes Jasmine as a submodule, so be sure to git submodule init && git submodule update) you can copy the example-suite.js file, import your spec files, point Instruments at your suite.js and go.

As an example, I set up a trivial example in the Cedar project. The directory structure looks like this:

Project Directory
- Spec
    - UIAutomation
        - jasmine-iphone     <--- submodule
            - jasmine        <--- nested submodule
        - suite.js
        - thing-spec.js
        - other-thing-spec.js

The suite.js file is relatively simple (note that I moved it up one directory from where the example-suite.js file is, so the #import statements are slightly different):

#import "jasmine-iphone/jasmine-uiautomation.js"
#import "jasmine-iphone/jasmine-uiautomation-reporter.js"

// Import your JS spec files here.
#import "thing-spec.js"
#import "other-thing-spec.js"

jasmine.getEnv().addReporter(new jasmine.UIAutomation.Reporter());
jasmine.getEnv().execute();

You can write the specs themselves the same way you’d write Jasmine specs for anything else. The UIAutomation subclass of the Jasmine Reporter takes care of marking the start of each spec, as well as reporting if it passes or fails. You’ll need to use the UIAutomation classes and methods for driving your application’s state, of course.

That’s it. Try it out and see what you think.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Adam Milligan

The run loop

Adam Milligan
Saturday, June 12, 2010

When I started writing Objective-C for iPhone and iPad projects I started to hear about these mystical and all-powerful run loops objects. Everything seems to relate to run loops, all the class references talk about how one object or another depends on run loops, the most basic iPhone application documentation even talks about how the device starts and maintains the main run loop for you because it’s so important. However, I found few straightforward descriptions of what a run loop is or how it works.

So, I read Apple’s Threading Programming Guide. I read about timers and ports and sources, about the starting and stopping and timing out of run loops. After this reading, and a bit of thought, I realized that all the sound and fury surrounding run loops blinded me to the fact that they are actually very, very simple. To wit, run loops are a mechanism for single-threaded asynchronous programming. Sound familiar? Sounds to me a lot like JavaScript.

A lot was made during the recent WWDC of the difference between synchronous and asynchronous network programming, so as an example let’s consider an AJAX request in JavaScript. To get some information from a server you’d send off a request in one function, passing in another function (or functions) for the system to call when it receives a response.

makeARequest({onSuccess: function(response) {
  // do some success stuff.
}});

Your initial function exits, and while the request is making its merry way through the series of tubes between the client and your server the system is happily going about its business. But, it has its digital ear to the ground for your response, and when that comes back it calls your function. VoilĂ , asynchronicity.

That’s a run loop. It has event sources, like some form of network socket on which it listens for your server’s response; it has timers, in the form of setTimeout() and clearTimeout(). The Apple Core Foundation run loops take a fair bit more setup to use — the network request performed by those three lines of JS would involve NSURLConnection, NSURLRequest, some form of delegate object, etc. — but it’s exactly the same idea. It’s waiting for something to happen while you take a nap; when that something happens it tells you about it.

There is one extremely significant difference between the JavaScript implementation and the Core Foundation implementation, at least in my mind: testing. In JavaScript this type of asynchronous code isn’t a run loop, it’s just JavaScript. As such, when you run your tests your code does everything you’d expect it to do; it’s the same interpreter running the tests as the production code, after all. So, when your test setup reaches into your AJAX library and stubs out the part that actually talks to the network everything continues to hum along. If you want, you step behind the curtain and send fake responses back through the AJAX object.

In comparison, a Core Foundation run loop is a special construct that the system sets up for you. When you run an app on your iPhone the device takes care of all the setup, care, and feeding of the main run loop. So, in tests, you if you want to run code that depends on a run loop you have to start the run loop yourself. Worse, starting a run loop blocks the execution of your tests until you stop the run loop. So, if you stub out the network code that actually talks to the network your code may sit and wait forever for a response that can’t possibly come. If you set up your code to return a fake response before starting the run loop your code will receive that response, but the run loop will continue to run, potentially blocking your test code forever.

This is, in my opinion, a significant problem for testing Cocoa projects. Asynchronous programming using run loops is simpler than mucking about with threads, and largely endorsed by Apple via their frameworks. But, there’s no reasonably simple way to test code written this way. You could set up a test run loop with test-specific run loop sources or timeouts to prevent it from blocking forever, but that seems immensely complex when compared to the JavaScript implementation. I would very much like to see some support from Apple in the form of a stub run loop for test environments that provides mechanisms for passing fake data to run loop sources, freezing and incrementing time to test timers and delayed invocations, etc.

I’m interested to hear other ideas you’ve had for how to get around this, or test mechanisms you’d like to see from Apple.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Adam Milligan

Pseudo-classical inheritance in JavaScript — a rebuttal

Adam Milligan
Sunday, March 7, 2010

A couple weeks ago Davis wrote about using pseudo-classical inheritance to make your JavaScript more object-oriented. I agree with a number of his points about the goal of well-structured code. However, based on my just-over-a-month experience in JavaScript, I personally don’t like to shoehorn the language into object-orientation via pseudo-classical inheritance.

For the sake of examples consider the following class hierarchy: Athlete, Footballer, and Defender.

Implementing this with pseudo-classical inheritance would look something like this, assuming the implementation of Object.extend() from here (I’ve had bad luck with the __super attribute in the past, but let’s assume it works for the moment).

This creates relationships between constructor functions and prototypes that look something like this (if you’ll excuse the ASCII art):

                     Object.prototype
                          ^
                          |
Athlete()    ---->   Athlete.prototype
                          ^
                          |

Footballer() ---->   Footballer.prototype
                          ^
                          |
Defender()   ---->   Defender.prototype

Arrows represent prototype attributes. Creating a new instance defender of the Defender class creates these relationships between the prototoypes and the instance:

                     Object.prototype
                          ^
                          |
                     Athlete.prototype
                          ^
                          |

                     Footballer.prototype
                          ^
                          |
defender     ---->   Defender.prototype

This should look familiar; it’s exactly the pattern that Ruby uses for basic inheritance, with the prototype objects representing instances of Ruby’s Class object, and prototype attributes representing Ruby’s Object#class (horizontal) or Class#superclass (vertical) attributes. The lookup rules work the same as Ruby as well: start with methods on the instance (in Ruby these would be methods on the instance’s singleton class); if not found, look for a method on the instance’s class; if not found, look on the Class instance’s superclass; repeat until found or you run out of classes/prototypes.

This looks comfortable and familiar, but unfortunately JavaScript and Ruby have a fundamental difference: Ruby is a class-based language and JavaScript is not. Object instances have instance-specific state — instance variables — which the instance methods use. However, while the instance variable are attributes of the instance, the instance methods live on the class/prototype object. This isn’t a problem in Ruby, because the interpreter knows what’s going on and gives the methods defined on the class access to the instance variables defined on the instance. JavaScript has no such capacity, so all instance variables in these pseudo-classes must be public attributes of the instance. This attempt to create object-oriented behavior by approximating classes actually ends up precluding encapsulation, one of the fundamental aspects of object-orientation.

A different approach to creating our classes could look like this (with a nod to Douglas Crockford). There are a few things I prefer about this approach:

  • Privates are private. Implementation methods such as #shoot and #feignInjury are hidden from the outside world. The same can be done for instance variables.
  • Object definitions have a clearly defined structure: instance variables at the top of the function definition, ending with the declaration and definition of self; public instance methods next, ending with the return of self; private instance methods at the end, where they belong.
  • Object definitions are nicely contained. In the first example the methods are defined at the top level, outside the constructor definition. In this second example everything that defines the class is nicely contained within a single function scope.
  • No dependence on, or pollution of the global namespace with, a method such as #extend.

I’ve heard brought up a couple concerns with this style:

  • Methods are, necessarily, defined on the object rather than the prototype, which can lead to duplication and inefficiency. This is a fair point, but I have yet to see it cause a problem. I’d be interested to see actual numbers that show how much of a performance hit this causes, given a certain number of object creations. In the meantime, I haven’t noticed a performance problem with code written this way, so I’m inclined to prefer encapsulation over theoretical performance issues.
  • Objects defined this way do not properly set their constructor attribute upon creation. Some test methods (notably Jasmine’s any method) depend on this.
  • Closures can be hard to grok.

We’ve recently finished up a reasonably sized project largely using this functional style of object definition, and it worked quite well. I’m sure there’s some reason that it shouldn’t have that I’ve overlooked; I’m curious to hear what that is.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Glenn Jahnke

Standup 2/17/2010: A New Jasmine Release

Glenn Jahnke
Wednesday, February 17, 2010

Interesting Things

There is a new release of Jasmine, the Javascript testing framework written by several people here at Pivotal Labs, due to a bug found in CI related to implementing Rack.

For those uninitiated to Javascript BDD testing, here is a quick example.

it('should be a test', function () {
  var foo = 0
  foo++;

  expect(foo).toBeTruthy();
  expect(foo).toEqual(1);
});

Be sure to check out Jasmine at Github.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
JB Steadman

javascriptTests.bind(reality)

JB Steadman
Friday, February 5, 2010

Javascript tests are good, but manually-maintained HTML fixtures are painful. It’s time consuming to keep fixture markup in sync with the actual markup produced by your app. Despite best efforts, deviations arise, leading to bugs and false positives in tests.

For the past few months on Mavenlink, we’ve been pre-generating real-life fixture markup and making it available in our javascript tests. Results have been positive.

The basic approach is simple:

1) Pre-generate real-life markup using any convenient mechanism.

2) When javascript tests run, load the pre-baked markup into the DOM for access by JS code.

For #1, we use a small set of RSpec controller specs that exist solely to generate fixtures. For #2, we retrieve fixture markup from our Jasmine server via ajax, and inject it into the DOM with jQuery. While our approach leans on the various bits of our stack, any part of it could be swapped out to adapt to different tools.

Big thanks to Jonathan Barnes for the code that got us started.

Generating the fixtures

Taking a closer look, here’s an RSpec test that generates an HTML fixture file named ‘workspace-page’:

describe WorkspacesController do
  it "generates a workspace page" do
    @workspace = create_workspace
    log_in @workspace.creator
    get :show, :id => @workspace.to_param
    response.should be_success
    save_fixture(html_for('body'), 'workspace-page')
  end
end

We create a workspace, hit the WorkspaceController‘s show method, and save the full text of the response’s <body> element to a file. This spec lives in a file with others like it, separate from the real controller specs. We have about a dozen of these specs, all in the same file.

We added save_fixture() and html_for() to ControllerExampleGroup to help with fixture generation. This gist has implementation details.

Our javascript tests sometimes require that we load different versions of the same page. We generate a different fixture for each version, giving them meaningful names like ‘busy-workspace-page’ and ‘empty-workspace-page’.

When we change markup consumed by our javascript tests, we re-run the controller specs that generate fixtures. Changes are picked up the next time we run our javascript tests. Fixture generation is hooked into continuous integration, so our javascript tests see the latest markup when running in CI.

Loading fixtures into the javascript test DOM

On the javascript side, fixture loading is handled by the code in this gist. Of note:

  • We use two methods for making fixture content available to our tests. loadFixture() inserts the fixture markup into the DOM for use by code that accesses the DOM. readFixture() returns fixture content as text; we use it to test our ajax callback methods.

  • Within the same test run, we cache fixture text in javascript to avoid multiple requests to the server for the same markup. Across test runs, we ensure our markup is fresh by appending a cache busting timestamp to our request path.

Ready to test!

Here’s how we typically use loadFixture() within our Jasmine tests:

describe('the status module', function() {
  it('switches tabs', function() {
    spec.loadFixture('workspace-page');
    var $tabContainer = $('#jasmine_content').find('.tab-container');
    expect($tabContainer).toHaveSelectedTab('team');
    $tabContainer.find('li[tab=schedule]').click();
    expect($tabContainer).toHaveSelectedTab('schedule');
  });
});

loadFixture() inserts markup into the #jasmine_content div. Then we examine the DOM, do stuff to it, and inspect it again. toHaveSelectedTab() is a custom Jasmine matcher. Jasmine matchers are super easy to write. We love them.

You may be wondering how we’ve established our event bindings. jQuery’s html() method, used within loadFixture(), executes any scripts in the markup passed to it. If you’ve bound events in your fixture markup, within a $(document).ready() or not, they will execute when you call loadFixture(). This is really nice, because it means the same mechanism used for binding events in real life is also used within tests, keeping our tests that much closer to reality.

If, on the other hand, you bind events not within fixture markup, but instead within a script loaded once per suite globally, you’ll have to invoke your event binding code explicitly before each test.

Speaking of event bindings, you’ll need to clean them up properly between tests. For example, jQuery live events are bound to document. We clear them in a global beforeEach():

beforeEach(function() {
  $('#jasmine_content').empty();
  spec.clearLiveEventBindings();
  jasmine.Clock.useMock();
});

spec.clearLiveEventBindings = function() {
  var events = jQuery.data(document, "events");
  for (prop in events) {
    delete events[prop];
  }
};

Any events bound on elements within #jasmine_content are cleared out by jQuery when we call $('#jasmine_content').empty(), which also wipes the DOM clean between our test runs.

Results

Managing html fixtures like this has been a big win. In a recent team retrospective, consensus was “I can’t imagine doing it any other way.”

Building fixtures for tests is often simple as writing a 5-line controller spec. Maintaining fixtures just means re-running the specs, or perhaps enhancing the specs with additional data. We don’t see any production bugs from fixture markup vs. real markup discrepancies, and we spend very little time dealing with the fixtures.

We sometimes forget to re-generate fixtures after we change our markup, but, by now, realizing our mistake is a reflex action.

Test speed was one of our concerns going into this. Loading the fixtures takes time, of course. In practice, the runtime hit is dwarfed by the time saved by automating fixtures.

We have 224 javascript tests, and 200 of them load an html fixture. Our suite runs in 38 seconds in Chrome on a 2.4 GHz Core 2 iMac. (Other browsers are considerably slower). Of that 38 seconds, 9 seconds are spent loading fixtures and re-binding events.

We end up running our tests on fairly large DOM. We could probably save some running time by more narrowly focusing the markup that we generate and load. However, we haven’t felt it worth the additional development overhead. Additionally, running tests on our full DOM has an advantage – it exposes event handlers that conflict with each other.

Other gotchas

Nested describes are another great feature of Jasmine. It can be difficult, though, to keep track of where you’ve called loadFixture() within your hierarchy of describes. We sometimes found that we were calling loadFixure() twice in the same spec. To prevent that, we now keep track of how many times loadFixture() is called within a single test, and fail the test if the count exceeds 1.

At one point, we noticed that our javascript suite was consuming hundreds of megabytes of memory as it executed. We traced the problem to two jQuery plugins. Each time we loaded a fixture, the plugins claimed memory that never got freed. Now we mock out the plugins where we’re not explicitly testing them.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Edward Hieatt

JsUnit moved to GitHub

Edward Hieatt
Saturday, November 28, 2009

We’ve moved JsUnit from SourceForge (where it’s been hosted for over 8 years) to GitHub, under Pivotal’s account:

http://github.com/pivotal/jsunit

The motivation is (1) to bring JsUnit development more officially in-house at Pivotal Labs, where it has a better chance of getting more attention than it has historically, and (2) to more easily allow the wider community to contribute.

Fork away!

JsUnit has a public Tracker project here and CI here.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter

Topics

  • agile (783)
  • rails (117)
  • testing (90)
  • ruby (86)
  • ruby on rails (71)
  • jobs (62)
  • javascript (59)
  • techtalk (44)
  • ironblogger (42)
  • rspec (39)
  • bloggerdome (34)
  • productivity (34)
  • activerecord (30)
  • rubymine (30)
  • git (29)
  • gogaruco (29)
  • nyc (27)
  • design (24)
  • mobile (23)
  • pivotal tracker (22)
  • process (21)
  • cucumber (21)
  • jasmine (19)
  • ios (18)
  • tracker ecosystem (17)
  • webos (17)
  • objective-c (17)
  • fun (16)
  • android (16)
  • palm (16)
  • ci (16)
  • "soft" ware (16)
  • bdd (15)
  • tdd (15)
  • cedar (15)
  • rails3 (14)
  • performance (14)
  • css (14)
  • gem (13)
  • mouse-free development (12)
  • selenium (12)
  • goruco (12)
  • bundler (12)
  • api (12)
  • keyboard (11)
  • meetup (11)
  • railsconf (11)
  • nyc-standup (11)
  • capybara (10)
  • mac (10)
Subscribe to javascript Feed
  1. ←
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  7. 6
  8. →
  • About
  • Case Studies
  • Team
  • Community
  • Careers
  • Tools
  • Contact
  • Labs
  • Events

Contact Us

contact@pivotallabs.com
+1 415-77-PIVOT
TwitterLinkedInFacebook

Pivotal Tracker

Tracker is the award-winning agile project management tool that enables real-time collaboration around a shared, prioritized backlog.
Visit pivotaltracker.com >