<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Being Agile]]></title>
  <link href="http://blog.thepete.net/atom.xml" rel="self"/>
  <link href="http://blog.thepete.net/"/>
  <updated>2013-05-21T07:50:59-07:00</updated>
  <id>http://blog.thepete.net/</id>
  <author>
    <name><![CDATA[Pete Hodgson]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Using Travis CI and xctool to build and test iOS apps]]></title>
    <link href="http://blog.thepete.net/blog/2013/05/07/using-travis-ci-and-xctool-to-build-and-test-ios/"/>
    <updated>2013-05-07T22:40:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2013/05/07/using-travis-ci-and-xctool-to-build-and-test-ios</id>
    <content type="html"><![CDATA[<p><a href="http://travis-ci.org">Travis CI</a> is a cloud-based Continuous Integration service which is free to use (but only on <em>public</em> github projects). They <a href="http://sauceio.com/index.php/2013/04/travis-ci-for-os-x-and-ios-powered-by-sauce/">recently</a> <a href="http://about.travis-ci.org/blog/introducing-mac-ios-rubymotion-testing/">announced</a> support for OS X agents, which means you can now use Travis to build and test iOS applications. In this post I&#8217;ll show how I set up basic CI for an example iOS app using Travis, with the help of <a href="https://github.com/facebook/xctool">xctool</a>. xctool is the &#8216;better xcodebuild&#8217; which Facebook recently open-sourced. It allows you to not only build your app on the command line but also run your app&#8217;s unit tests from the command line with the same capabilities that XCode offers when you run the tests from the IDE proper.</p>

<p>To see a working example of the sort of thing we&#8217;ll be setting up, take a look at the <a href="https://github.com/moredip/run2bart-iOS">github repo</a> and the corresponding <a href="https://travis-ci.org/moredip/run2bart-iOS">Travis page</a> for my Run2Bart example app.</p>

<h2>Getting started with Travis</h2>

<h3>How Travis works</h3>

<p>Travis is driven entirely through github integration. You configure Travis with information on how to build your app by adding a <code>.travis.yml</code> file to the root of your git repo. Then you log on to Travis using your github credentials and have it configure a github post-commit hook for the github repo. After doing that github will tell Travis every time you&#8217;ve pushed code to your repo. Travis will respond by dutifully downloading the commit which was pushed and will then do whatever build you&#8217;ve configured it to do in that <code>.travis.yml</code> file.</p>

<h3>an initial travis setup</h3>

<p>I&#8217;m not going to cover linking your github repo to Travis; their own docs <a href="http://about.travis-ci.org/docs/user/getting-started/">explain this well</a>. Once you have linked your repo the next step would be to add a <code>.travis.yml</code> file to the root of the repo. Here&#8217;s a basic setup similar to the one that I use to build my Run2Bart example app:</p>

<figure class='code'><figcaption><span>.travis.yml</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='yaml'><span class='line'><span class="nn">---</span>
</span><span class='line'>  <span class="l-Scalar-Plain">language</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">objective-c</span>
</span><span class='line'>
</span><span class='line'>  <span class="l-Scalar-Plain">before_script</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">travis/before_script.sh</span>
</span><span class='line'>  <span class="l-Scalar-Plain">script</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">travis/script.sh</span>
</span></code></pre></td></tr></table></div></figure>


<p>First I&#8217;m telling Travis that this is an objective-c project. Next I tell Travis how I&#8217;d like it to do CI against this repo by giving it instructions on what scripts it should run in order to actually perform a build. I also give some extra instructions on what to do just prior to running a build. It&#8217;s quite common to put all the build steps inline right in the <code>.travis.yml</code> file, but I prefer to actually create bash scripts in my repo inside a <code>travis</code> directory in my git repo and then just refer to those scripts from my <code>.travis.yml</code>. This keeps the .yml file nice and small, and also makes it easy for me to test the travis build scripts locally.</p>

<p>We gave Travis a before_script in the .yml file above. This is intended to be used by the Travis agent to download tools needed as part of the build. Here&#8217;s what it looks like:</p>

<figure class='code'><figcaption><span>travis/before_script.sh</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="c">#!/bin/sh</span>
</span><span class='line'><span class="nb">set</span> -e
</span><span class='line'>
</span><span class='line'>brew update
</span><span class='line'>brew install xctool
</span></code></pre></td></tr></table></div></figure>


<p>Very simple. We just use homebrew to install xctool on the build agent. All travis build agents come with homebrew pre-installed, but sometimes the formula aren&#8217;t up to date, so it&#8217;s best to run a <code>brew update</code> before attempting a <code>brew install</code>.</p>

<p>That&#8217;s all we need to do to prepare our agent for the build. Next let&#8217;s look at the build script itself:</p>

<figure class='code'><figcaption><span>travis/script.sh</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="c">#!/bin/sh</span>
</span><span class='line'><span class="nb">set</span> -e
</span><span class='line'>
</span><span class='line'>xctool -workspace MyWorkspace -scheme MyScheme build <span class="nb">test</span>
</span></code></pre></td></tr></table></div></figure>


<p>Again, this is really simple. We first do a basic sanity check by asking xctool to build our app, specifying a workspace and scheme. This just checks that we don&#8217;t have any compilation errors. Assuming that succeeds xctool will then build and run the unit testing target for our app, launching the Simulator on the Travis agent if needed.</p>

<h2>It&#8217;s that easy</h2>

<p>And that&#8217;s all there is to it for a basic build-and-test setup. At this point you&#8217;re going to get very fast feedback from Travis as soon as anyone pushes code which either causes compilation errors or causes your unit tests to fail. From here you can easily build upon this basic CI set up. There are a lot of things you can do to expand this, some of which I&#8217;ve done in my example Run2Bart app.</p>

<p>You can have xctool generate pretty output by specifying a different <a href="https://github.com/facebook/xctool#reporters">reporter</a>, and then archive that report as a build artifact using something like <a href="http://about.travis-ci.org/blog/2012-12-18-travis-artifacts/">travis-artifacts</a>.</p>

<p>You can add extra stages to your build such as <a href="http://www.testingwithfrank.com">Frank acceptance tests</a>.</p>

<p>You could even have Travis distribute a build of your app to alpha users using something like <a href="https://testflightapp.com/">TestFlight</a> or <a href="http://hockeyapp.net">HockeyApp</a>. That&#8217;s definitely an advanced topic though - it would be very fiddly to achieve due to having to do code-signing of a device build on the Travis agent.</p>

<h2>You don&#8217;t need to use Travis for this</h2>

<p>And of course you can do all of the above on your own Jenkins (or TeamCity, or Go, or Bamboo) CI server rather than on Travis. In fact unless you&#8217;re building an open-source app or you&#8217;re a beta customer of <a href="http://travis-ci.com">Travis Pro</a> then you&#8217;ll likely want to use a different CI technology. Regardless, the basic approach remains the same.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Test-driven Backbone.js - Part Three]]></title>
    <link href="http://blog.thepete.net/blog/2013/02/24/test-driven-backbone-dot-js-part-three/"/>
    <updated>2013-02-24T21:04:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2013/02/24/test-driven-backbone-dot-js-part-three</id>
    <content type="html"><![CDATA[<p>In the <a href="http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-one/">previous</a> <a href="http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-two/">posts</a> in this series we&#8217;ve done some test-driven development of Backbone Models, Collections, and Views. In this post I&#8217;m going to cover another role which I believe should be present in most <abbr title="Single Page App">SPA</abbr> Backbone apps: Controllers.</p>

<h2>Controllers in a Backbone app</h2>

<p>There&#8217;s nothing in the Backbone.js library for building Controllers. There&#8217;s not a <code>Backbone.Controller</code> for you to extend from. But that doesn&#8217;t mean that Controllers don&#8217;t have a part to play in your Backbone app. I suspect that the reason we don&#8217;t see Backbone.Controller in the library is simply because there isn&#8217;t much helpful shared functionality that could be put there. The Controller role is more loosly defined than other more concrete roles such as View or Model and so there&#8217;s not a need for a concrete base implementation in the Backbone.js library. However that does <em>not</em> mean that your app wouldn&#8217;t benefit from code organized under the Controller role.</p>

<h2>No Controller class or prototype</h2>

<p>Since we don&#8217;t need any shared functionality in our controller we won&#8217;t need to use any inheritance (prototypical or pseudo-classical) when building it. We can build controllers using simple <a href="http://blog.thepete.net/blog/2012/02/06/class-less-javascript">constructor functions</a>. I prefer to use constructor functions over inheritance heirarchies whenever possible - I think they&#8217;re a better fit with the &#8216;good parts&#8217; of JavaScript - so that&#8217;s what we&#8217;ll use here.</p>

<h2>What does a Controller do?</h2>

<p>Simply put, a controller mediates between the UI and the rest of your application. In the case of a Backbone app this generally means reacting to events published from your View layer. A controller may respond to these events by updating Model instances, or by making calls to Services (which we&#8217;ll get to in a later post in this series).</p>

<h2>Doesn&#8217;t a View do that in a Backbone app?</h2>

<p>In a lot of Backbone applications which <em>don&#8217;t</em> have Controllers you see Backbone Views that do a lot of the coordination work I just described. Rather than just acting as a translation layer between the UI and the rest of the application these <strong>Fat Backbone Views</strong> take on additional responsibilities, often acting as Controllers too. These views tend to be large, unwieldy, and tough to test. Their implementations are hard to read and hard to maintain. They cause these issues because they are violating the Single Responsibility Principle, both acting as an abstraction over the DOM and also implementing application logic. Introducing a Controller helps avoid this situation. Views can remain focussed on their single responsibility - mapping between the UI and the application. Controllers take on the additional responsibilities which would otherwise muddy the View&#8217;s role. Additionally, as Controllers aren&#8217;t coupled to a DOM the way Views are they are much more amenable to testing in isolation.</p>

<h1>Back to our example</h1>

<p>Now we&#8217;ll see what a typical Controller might look like, using our Card Wall app as an example.</p>

<h2>Adding new cards to a card wall</h2>

<p>When we left our Cards application in our last post we had a <code>CardWall</code> model which represented a set of cards. We also had a <code>NewCardView</code> which allowed a user to enter a new card. What&#8217;s missing is something which ties those two elements together. When a user fills out the text for a new card and hits create then a new card should be added to the CardWall. This is exactly the place where a Controller would come into play - bridging between a View and a Collection or Model (or both).</p>

<p>Let&#8217;s get going and use tests to drive out that controller.</p>

<h2>Implementation</h2>

<p>Once again, we&#8217;ll write an initial silly-simple test to get us started. We&#8217;ll test that we can create a controller:</p>

<figure class='code'><figcaption><span>main_controller_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;main controller&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;can be created&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">controller = </span><span class="nx">createMainController</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">controller</span> <span class="p">).</span><span class="nx">toBeDefined</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>This will fail because we don&#8217;t have that constructor function defined yet. We easily remedy that and get our test back to green:</p>

<figure class='code'><figcaption><span>main_controller.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">createMainController = </span><span class="nf">()-&gt;</span>
</span><span class='line'>  <span class="p">{}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Simple enough. A function that takes no parameters and return an empty object literal. That&#8217;s enough to get us to green.</p>

<p>OK, what should we test next? Well, this controller needs to react to a <code>NewCardView</code> firing an <code>create-card</code> event by adding a card to a <code>CardWall</code>. That&#8217;s quite a lot of functionality to bite off in one test but I don&#8217;t really see a way to break it down, so let&#8217;s just give it a go and see if we can express all of that in a reasonably small step:</p>

<figure class='code'><figcaption><span>main_controller_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;main controller&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;reacts to a create-card event by creating a new card in the card wall&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">fakeNewCardView = </span><span class="nx">_</span><span class="p">.</span><span class="nx">extend</span><span class="p">({},</span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Events</span><span class="p">)</span>
</span><span class='line'>    <span class="nv">fakeCardWall = </span><span class="nx">_</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span>
</span><span class='line'>      <span class="nv">addCard: </span><span class="nx">sinon</span><span class="p">.</span><span class="nx">spy</span><span class="p">()</span>
</span><span class='line'>    <span class="p">})</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">createMainController</span><span class="p">(</span> <span class="nv">newCardView: </span><span class="nx">fakeNewCardView</span><span class="p">,</span> <span class="nv">cardWall: </span><span class="nx">fakeCardWall</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">fakeNewCardView</span><span class="p">.</span><span class="nx">trigger</span><span class="p">(</span><span class="s1">&#39;create-card&#39;</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span><span class="nx">fakeCardWall</span><span class="p">.</span><span class="nx">addCard</span><span class="p">).</span><span class="nx">toHaveBeenCalled</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>There&#8217;s a lot going on here. We are creating fake instances of <code>NewCardView</code> and <code>CardWall</code> and passing them into our controller&#8217;s constructor function. Then we simulate a <code>create-card</code> event by explicitly triggering it on our fake <code>NewCardView</code> instance. Finally we check that our controller reacted to that <code>create-card</code> event by calling <code>addCard</code> on the <code>CardWall</code> instance it was given during construction.</p>

<p>We created our fake instance of <code>NewCardView</code> by just taking the base <code>Backbone.Events</code> module and mixing it into an empty object. That Events module is the same module which is mixed into pretty much every Backbone-derived object (Model, View, Collection, Router, even the Backbone object itself!). Mixing the Events module into our empty object gives it the standard Backbone event methods like <code>on</code> and <code>trigger</code>. That&#8217;s all we needed our fake instance to be able to do in this case - be an empty object with some event methods mixed in.</p>

<p>So now that we understand what the test is doing let&#8217;s get it to pass:</p>

<figure class='code'><figcaption><span>main_controller.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">createMainController = </span><span class="nf">({newCardView,cardWall})-&gt;</span>
</span><span class='line'>  <span class="nx">newCardView</span><span class="p">.</span><span class="kc">on</span> <span class="s1">&#39;create-card&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">cardWall</span><span class="p">.</span><span class="nx">addCard</span><span class="p">()</span>
</span><span class='line'>  <span class="p">{}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Reasonably straight-forward. When the controller is constructed it now immediately registers a handler for any <code>create-card</code> events from the <code>NewCardView</code> instance - note that the controller is now being provided the <code>NewCardView</code> instance (and a <code>CardWall</code> instance) via the constructor function. The handler for that <code>create-card</code> event simply calls <code>addCard</code> on the <code>CardWall</code> instance.</p>

<p>That gets our previous test to green, but unfortunately it breaks our initial simple test. That test wasn&#8217;t passing any arguments to the controller&#8217;s constructor function. That means that <code>newCardView</code> is undefined, and calling <code>newCardView.on</code> fails. We could solve this by modifying that initial test to pass in some kind of fake <code>newCardView</code>. However, looking at that test it is providing no real value now. It was there to get us started TDDing our controller, and now that we&#8217;re started we don&#8217;t really need that test to stick around. It&#8217;s very unlikely to catch any regressions or provide any other value in the future so we&#8217;ll just delete that first test, which will bring out full test suite back to green again.</p>

<p>If a test isn&#8217;t providing any value then don&#8217;t be afraid to delete it.</p>

<p>We now have a controller which reacts to <code>create-card</code> events by asking the <code>CardWall</code> to add a card, but it&#8217;s not passing any information about the card from the <code>NewCardView</code> to the <code>CardWall</code>. Specifically, it&#8217;s not passing the text which the user entered into the new card view. To drive out that functionality we could add a new test which describes the additional behaviour. However in this case that test would just be an expanded version of the existing test, so instead we&#8217;ll just take our existing test and flesh it out more:</p>

<figure class='code'><figcaption><span>main_controller_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;main controller&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;reacts to a create-card event by creating a new card in the card wall&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">fakeNewCardView = </span><span class="nx">_</span><span class="p">.</span><span class="nx">extend</span><span class="p">(</span> <span class="p">{</span><span class="nv">getText: </span><span class="o">-&gt;</span> <span class="s1">&#39;text from new card&#39;</span><span class="p">},</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Events</span> <span class="p">)</span>
</span><span class='line'>    <span class="nv">fakeCardWall = </span><span class="nx">_</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span>
</span><span class='line'>      <span class="nv">addCard: </span><span class="nx">sinon</span><span class="p">.</span><span class="nx">spy</span><span class="p">()</span>
</span><span class='line'>    <span class="p">})</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">createMainController</span><span class="p">(</span> <span class="nx">newCardView</span><span class="o">:</span><span class="nx">fakeNewCardView</span><span class="p">,</span> <span class="nv">cardWall: </span><span class="nx">fakeCardWall</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">fakeNewCardView</span><span class="p">.</span><span class="nx">trigger</span><span class="p">(</span><span class="s1">&#39;create-card&#39;</span><span class="p">,</span><span class="nx">fakeNewCardView</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span><span class="nx">fakeCardWall</span><span class="p">.</span><span class="nx">addCard</span><span class="p">).</span><span class="nx">toHaveBeenCalledWith</span><span class="p">(</span><span class="nx">text</span><span class="o">:</span><span class="s1">&#39;text from new card&#39;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;ve expanded our <code>fakeNewCardView</code> to include a stub implementation of the <code>getText</code> method. This method would be present on a <code>NewCardView</code> instance. We&#8217;ve also extended the event triggering in the test to also include the sender of the event. This is what the actual <code>NewCardView</code> implemention which we built in the previous post does. Finally we modify our verification step. Instead of just checking that <code>addCard</code> was called it checks that it is called with a <code>text</code> parameter equal to the card text returned by the <code>NewCardView</code> instance&#8217;s <code>getText</code> method.</p>

<p>We run this test and of course it fails, but it&#8217;s very simple to get it passing:</p>

<figure class='code'><figcaption><span>main_controller.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">createMainController = </span><span class="nf">({newCardView,cardWall})-&gt;</span>
</span><span class='line'>  <span class="nx">newCardView</span><span class="p">.</span><span class="kc">on</span> <span class="s1">&#39;create-card&#39;</span><span class="p">,</span> <span class="nf">(sender)-&gt;</span>
</span><span class='line'>    <span class="nx">cardWall</span><span class="p">.</span><span class="nx">addCard</span><span class="p">(</span> <span class="nv">text: </span><span class="nx">sender</span><span class="p">.</span><span class="nx">getText</span><span class="p">()</span> <span class="p">)</span>
</span><span class='line'>  <span class="p">{}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The only thing we&#8217;ve changed here is to take the sender argument passed with the <code>create-card</code> event, grab the text from that sender and then include it when calling <code>cardWall.addCard</code>. Tests are green once more. Looking at this implementation you can see why we had to add the extra parameter in the explicit <code>fakeNewCardView.trigger('create-card',fakeNewCardView)</code> call in our test code. If we didn&#8217;t pass the <code>fakeNewCardView</code> with the event then <code>sender</code> would be undefined in our controller code, which would cause the test to fail. It&#8217;s unfortunate that this level of implementation detail leaked into our test writing, but that implementation detail is part of the <code>NewCardView</code> public API, so this isn&#8217;t too big a concern.</p>

<h2>Our Controller is complete</h2>

<p>And at this point we&#8217;re done. We have a Controller which mediates between our Views and the rest of our app, creating new cards when a view tells it that the user wants a new card.</p>

<h2>That&#8217;s our Controller?!</h2>

<p>Our controller ended up being 3 lines of code. Was that worth it? Why didn&#8217;t we just throw that logic into <code>NewCardView</code>?</p>

<p>Well, if we had done that then <code>NewCardView</code> would now have to know which <code>CardWall</code> it was associated with (so that it could call <code>addCard</code> on the right object. That means <code>NewCardView</code> would now be coupled directly to the <code>CardWall</code>. That means you&#8217;d either need to wire up each <code>NewCardView</code> with a <code>CardWall</code> - probably via constructor params or by setting fields - or worse you&#8217;d need <code>CardWall</code> to become a singleton. Both of these are design compromises. It&#8217;s better to keep the different parts of your system decoupled if you can.</p>

<p>Also note that if <code>NewCardView</code> knows about a <code>CardWall</code> then you are likely to start to have circular dependencies - Collections or Models  know about Views, which in turn know about other Collections or Models. Your design becomes quite hard to reason about - you don&#8217;t really know what objects are involved in a particular interaction. More coupling also makes things harder to test. If a <code>NewCardView</code> is directly calling a <code>CardWall</code> whenever card creation is requested then you need to supply fake versions of <code>CardWall</code> in a lot of tests. That&#8217;s one more piece of complexity in your tests for you to read, understand and maintain. Better to keep things decoupled so that your tests can remain isolated and focussed, along with the rest of your code.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Test-driven Backbone.js - Part Two]]></title>
    <link href="http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-two/"/>
    <updated>2013-01-23T18:23:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-two</id>
    <content type="html"><![CDATA[<p>In the <a href="http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-one/">previous installment</a> of this series we looked at the basics of test-driving the development of a Backbone.js app by TDDing some simple functionality for Backbone Models.</p>

<p>In this installment we&#8217;re going to get a bit more advanced, looking at how we can test-drive Backbone Views. Because views integrate with the DOM they can be a little more fiddly to test, but TDDing your views is still a very achievable goal.</p>

<h2>Jasmine-jQuery</h2>

<p>Testing backbone views is in large part about testing how JavaScript interacts with the DOM via jQuery. A helpful tool for this is a little extension to Jasmine called <a href="https://github.com/velesin/jasmine-jquery">Jasmine-jQuery</a>. Jasmine-jQuery adds a set of custom matchers to Jasmine which make it easier to assert on various properties of a $-wrapped DOM element. For example you can assert that a DOM element contains specific text, matches a specific selector, is visible (or hidden), etc. The project&#8217;s <a href="https://github.com/velesin/jasmine-jquery#readme">github README</a> describes all the matchers added by the plugin in detail.</p>

<h2>HTML test fixtures - to be avoided if possible</h2>

<p>Jasmine-jQuery also provides a feature called <em><a href="https://github.com/velesin/jasmine-jquery#html-fixtures">fixtures</a></em>. The idea here is that you describe any specific HTML content that you need to be available in the browser DOM during a test. Jasmine-jQuery will ensure that that content is in the browser DOM before your test runs, and will take care of cleaning the content out after the test completes. This is a useful feature if you are testing JavaScript code which acts on content across the entire document using a $ selector. In that situation you sometimes have to pre-load the DOM with the HTML which that $ selector is expecting in order to test how the JavaScript under test behaves.</p>

<p>However in the context of a Backbone we shouldn&#8217;t need to lean on fixtures too often. In fact if we need to use fixtures often in our Backbone View tests then we should be concerned. This is because in most cases a Backbone view should not be accessing parts of the DOM outside of its own <code>el</code> property and thus should not need fixtures during testing. The DOM is essentially one big chunk of mutable shared state (or, put another way, one big global variable) and we should avoid relying upon that shared state in our design unless absolutely necessary.</p>

<p>Mutable shared state is a tricky thing to deal with in code. You can never be sure what code is going the change the state, and when. You have to think about how your entire application works whenever you change how you interact with that state. A Backbone view which restricts itself to just modifying its own <code>el</code> on the other hand is easy to reason about - all code that modifies that state is localized within that view&#8217;s implementation, and it is usually easy to hold in your head all at once. This very powerful advantage goes out of the window when we start accessing state that&#8217;s not owned by the view. So, we should strive to avoid access to the wider DOM whenever possible by restricting our view to only touching its own <code>el</code> property. If we do this then we have no need for fixtures. This means that if we are relying on fixtures a lot then that should be considered a test <a href="http://www.codinghorror.com/blog/2006/05/code-smells.html">smell</a> which is telling us that we are failing in our goal of keeping as much DOM-manipulation code as possible localized to within a single view.</p>

<p>The one place where we must relax this guidance a little is when we have what I call <em>Singleton Views</em>. These are top-level Backbone views in our Single Page App which bind themselves to pre-existing &#8216;shell&#8217; sections of the DOM which came down into the browser when the app was first loaded. These views are generally the highest level visual elements in the application, and as such there tend to be no more than 3 or 4 Singleton Views in a given <abbr title="Single Page App">SPA</abbr>. For example a Gmail-type app may have Singleton Views for a navigation bar, a tool bar, the left-hand folder view and the main right-hand email container.</p>

<p>In order to test these Singleton Views properly we need to test them in the context of the initial DOM structure which they will bind themselves to, since this is the context they will always be within in when the full app is running. HTML fixtures allow us to write tests for these Singleton Views in the context of their DOM structure but in an independent way, without affecting other tests. We&#8217;ll see an example of TDDing a Singleton View when we create the New Card view later on.</p>

<h2>Our first View</h2>

<p>Let&#8217;s start off by building a <code>CardView</code>, which our app will use to render an instance of a <code>Card</code> model. As we did before we&#8217;ll start off with a test, before we even have a <code>CardView</code> defined at all. Also like before it&#8217;s good to start off with a simple test that drives out an basic initial implementation of what we&#8217;re building.</p>

<figure class='code'><figcaption><span>card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardView</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;renders a div.card&#39;</span><span class="p">,</span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">CardView</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">render</span><span class="p">().</span><span class="nx">$el</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="s1">&#39;div.card&#39;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>This test should be pretty self-explanatory. We&#8217;re saying that we expect a card view to render itself as a div of class &#8216;card&#8217;. Note that we take advantage of Jasmine-jQuery&#8217;s <code>toBe</code> matcher here, which says &#8216;the element in question should match this css selector&#8217;.</p>

<p>Of course this test will fail initially because we haven&#8217;t even defined a <code>CardView</code>. Let&#8217;s get the test passing by defining a <code>CardView</code> along with the necessary configuration specifying what class and type of tag it renders as:</p>

<figure class='code'><figcaption><span>card_view.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">CardView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">tagName: </span><span class="s1">&#39;div&#39;</span>
</span><span class='line'>  <span class="nv">className: </span><span class="s1">&#39;card&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>With that we&#8217;re back to green. Now let&#8217;s move on to our next test for this view. It&#8217;s rendering as a div with the appropriate class, but what content is inside that div? If we&#8217;re rendering a <code>Card</code> model then we probably want the <code>text</code> attribute within that card model to be rendered in our <code>CardView</code>:</p>

<figure class='code'><figcaption><span>card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardView</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;renders a div.card&#39;</span><span class="p">,</span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">CardView</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">render</span><span class="p">().</span><span class="nx">$el</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="s1">&#39;div.card&#39;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;renders the card text&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">model = </span><span class="k">new</span> <span class="nx">Card</span><span class="p">(</span><span class="nx">text</span><span class="o">:</span><span class="s1">&#39;I &lt;3 HTML!&#39;</span><span class="p">)</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">CardView</span><span class="p">(</span> <span class="nv">model: </span><span class="nx">model</span> <span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">render</span><span class="p">().</span><span class="nx">$el</span><span class="p">.</span><span class="nx">find</span><span class="p">(</span><span class="s1">&#39;p&#39;</span><span class="p">)</span> <span class="p">).</span><span class="nx">toHaveText</span><span class="p">(</span><span class="s2">&quot;I &lt;3 HTML!&quot;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>In our new test we create an instance of a <code>Card</code> model with some specific text. We then create a <code>CardView</code> instance for that model. Finally we render that <code>CardView</code> instance and verify that its <code>$el</code> contains a <code>&lt;p&gt;</code> tag which itself contains the <code>Card</code> model&#8217;s text. Note we also include some funky characters in our card text to get some confidence that we&#8217;re escaping our HTML correctly.</p>

<p>That&#8217;s quite a complex test, but it&#8217;s pretty easy to get passing:</p>

<figure class='code'><figcaption><span>card_view.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">CardView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">tagName: </span><span class="s1">&#39;div&#39;</span>
</span><span class='line'>  <span class="nv">className: </span><span class="s1">&#39;card&#39;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">render: </span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">@$el</span><span class="p">.</span><span class="nx">html</span><span class="p">(</span> <span class="s2">&quot;&lt;p&gt;#{@model.escape(&#39;text&#39;)}&lt;/p&gt;&quot;</span> <span class="p">)</span>
</span><span class='line'>    <span class="err">@</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;ve added a <code>render</code> method to our view. This method replaces whatever html is currently in the view&#8217;s <code>$el</code> with a <code>&lt;p&gt;</code> tag containing the html-escaped contents of the model&#8217;s <code>text</code> attribute.</p>

<p>We&#8217;re still following Simplest Possible Thing here. we could start using some sort of client-side templating to render our view, but for the sake of this one <code>&lt;p&gt;</code> tag it seems unnecessary. So we&#8217;re using good old-fashioned string interpolation until we reach a point where a template makes more sense.</p>

<p>It turns out that this new <code>render</code> method gets our second test passing but also breaks our first test. Our first test doesn&#8217;t pass a model to the <code>CardView</code> constructor, which means that the subsequent call to <code>@model.escape('text')</code> fails. We&#8217;ll quickly fix up our tests:</p>

<figure class='code'><figcaption><span>card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardView</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nv">createView = </span><span class="p">(</span> <span class="nv">model = </span><span class="k">new</span> <span class="nx">Card</span><span class="p">()</span> <span class="p">)</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="k">new</span> <span class="nx">CardView</span><span class="p">(</span><span class="nx">model</span><span class="o">:</span><span class="nx">model</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;renders a div.card&#39;</span><span class="p">,</span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="nx">createView</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">render</span><span class="p">().</span><span class="nx">$el</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="s1">&#39;div.card&#39;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;renders the card text&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">model = </span><span class="k">new</span> <span class="nx">Card</span><span class="p">(</span><span class="nx">text</span><span class="o">:</span><span class="s1">&#39;I &lt;3 HTML!&#39;</span><span class="p">)</span>
</span><span class='line'>    <span class="nv">view = </span><span class="nx">createView</span><span class="p">(</span> <span class="nx">model</span> <span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">render</span><span class="p">().</span><span class="nx">$el</span><span class="p">.</span><span class="nx">find</span><span class="p">(</span><span class="s1">&#39;p&#39;</span><span class="p">)</span> <span class="p">).</span><span class="nx">toHaveText</span><span class="p">(</span><span class="s2">&quot;I &lt;3 HTML!&quot;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>That gets us back to green. We&#8217;ve added a little <code>createView</code> helper function. We can explicitly pass it a model to use when it constructs a view, but if we don&#8217;t care we can just have the helper function create some generic model to supply the view with.</p>

<h2>a View for adding new cards</h2>

<p>A card wall isn&#8217;t much use if you can&#8217;t add new cards to the wall. Let&#8217;s start addressing that by creating a <code>NewCardView</code>. This view which will represent the user interface used to supply text for a new card and then add it to the card wall.</p>

<p>This <code>NewCardView</code> will be a <em>Singleton View</em> - rather than creating its own <code>el</code> DOM element at construction time it will instead bind <code>el</code> to a DOM element which already exists on the page when it loads. First off let&#8217;s take a first stab at what that pre-existing HTML will look like by creating a shell index.html file:</p>

<figure class='code'><figcaption><span>index.html</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;html&gt;</span>
</span><span class='line'>  <span class="nt">&lt;body&gt;</span>
</span><span class='line'>    <span class="nt">&lt;section</span> <span class="na">id=</span><span class="s">&#39;new-card&#39;</span><span class="nt">&gt;</span>
</span><span class='line'>      <span class="nt">&lt;textarea</span> <span class="na">placeholder=</span><span class="s">&#39;Make a new card here&#39;</span><span class="nt">&gt;&lt;/textarea&gt;</span>
</span><span class='line'>      <span class="nt">&lt;button&gt;</span>add card<span class="nt">&lt;/button&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/section&gt;</span>
</span><span class='line'>  <span class="nt">&lt;/body&gt;</span>
</span><span class='line'><span class="nt">&lt;/html&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Pretty simple. a <code>&lt;textarea&gt;</code> to enter the card&#8217;s text into a <code>&lt;button&gt;</code> to add a card with that text to the wall.  Now let&#8217;s drive out the basics of our <code>NewCardView</code>:</p>

<figure class='code'><figcaption><span>new_card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;NewCardView&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;binds $el to the right DOM element&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">loadFixtures</span> <span class="s1">&#39;index.html&#39;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">NewCardView</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">$el</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span> <span class="s1">&#39;section#new-card&#39;</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here we use Jasmine-jQuery&#8217;s <code>loadFixtures</code> helper to insert the contents of our index.html file into the DOM, but only for the duration of the test. Note that we&#8217;re inserting the regular index.html into our DOM during testing, not a test-specific fixture. Doing this gives us more confidence that we&#8217;re testing the Singleton View in the same context as when it&#8217;s running in our real app. Next we create a <code>NewCardView</code> instance and verify that its <code>$el</code> is bound to the right <code>&lt;section&gt;</code> within that initial static HTML coming from <code>index.html</code>. Let&#8217;s get that first test passing:</p>

<figure class='code'><figcaption><span>new_card_view.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">NewCardView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">el: </span><span class="s2">&quot;section#new-card&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>As we can see, Backbone makes it very easy to create a Singleton View. We simple specify a css selector as the <code>el</code> field. When the view is constructed that CSS selector string is used to select a DOM element within the page which the view instance&#8217;s <code>el</code> will then refer to.</p>

<h2>Test-driven DOM event handling</h2>

<p>Now that we have driven out the basic view, let&#8217;s write a test for some event firing behaviour. We want our view to trigger an event whenever the user clicks the &#8216;add card&#8217; button. As we did before, we&#8217;ll use Sinon spy functions in our test to describe the behavior we expect:</p>

<figure class='code'><figcaption><span>new_card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;NewCardView&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;binds $el to the right DOM element&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">loadFixtures</span> <span class="s1">&#39;index.html&#39;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">NewCardView</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">$el</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span> <span class="s1">&#39;section#new-card&#39;</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;triggers a create-card event when the add card button is clicked&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">loadFixtures</span> <span class="s1">&#39;index.html&#39;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">NewCardView</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>    <span class="nv">eventSpy = </span><span class="nx">sinon</span><span class="p">.</span><span class="nx">spy</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">view</span><span class="p">.</span><span class="kc">on</span><span class="p">(</span> <span class="s1">&#39;create-card&#39;</span><span class="p">,</span> <span class="nx">eventSpy</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;section#new-card button&#39;</span><span class="p">).</span><span class="nx">click</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">eventSpy</span> <span class="p">).</span><span class="nx">toHaveBeenCalled</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this new test we register a spy on a <code>NewCardView</code> instance&#8217;s <code>create-card</code> event, so that whenever that instance triggers an event of that type it will be recorded by the spy. Then we use jQuery to simulate a click on the &#8216;add card&#8217; button. Finally we verify that the <code>create-card</code> event was triggered by checking whether the spy we registered for that event has been called.</p>

<p>This test will fail of course, since we haven&#8217;t implemented any custom <code>create-card</code> event in <code>NewCardView</code>. Let&#8217;s do that now and get the test passing:</p>

<figure class='code'><figcaption><span>new_card_view.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">NewCardView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">el: </span><span class="s2">&quot;section#new-card&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">events:</span>
</span><span class='line'>    <span class="s2">&quot;click button&quot;</span><span class="o">:</span> <span class="s2">&quot;onClickButton&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">onClickButton: </span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">@trigger</span><span class="p">(</span> <span class="s1">&#39;create-card&#39;</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here we use the <code>events</code> field to declaratively tell our Backbone View that whenever a <code>&lt;button&gt;</code> within the view&#8217;s <code>el</code> receives a <code>click</code> event it should call the view&#8217;s <code>onClickButton</code> method. In addition we implement that <code>onClickButton</code> method to trigger a <code>create-card</code> event on the view itself.</p>

<p>This is a very common pattern in Backbone views. They react to low-level DOM events within their <code>el</code> and re-publish a higher-level application-specific event. Essentially the Backbone view is acting as a translation layer between the messy low-level details like DOM elements and click events and the more abstract higher-level application concepts like creating a card.</p>

<p>Now that our tests are green again we can do a little refactor of our test code, DRYing it up a little:</p>

<figure class='code'><figcaption><span>new_card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;NewCardView&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">view = </span><span class="kc">null</span>
</span><span class='line'>  <span class="nx">beforeEach</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">loadFixtures</span> <span class="s2">&quot;index.html&quot;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">NewCardView</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;binds $el to the right DOM element&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">$el</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span> <span class="s1">&#39;section#new-card&#39;</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;triggers a create-card event when the add card button is clicked&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">eventSpy = </span><span class="nx">sinon</span><span class="p">.</span><span class="nx">spy</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">view</span><span class="p">.</span><span class="kc">on</span><span class="p">(</span> <span class="s1">&#39;create-card&#39;</span><span class="p">,</span> <span class="nx">eventSpy</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;section#new-card button&#39;</span><span class="p">).</span><span class="nx">click</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">eventSpy</span> <span class="p">).</span><span class="nx">toHaveBeenCalled</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>Nothing exciting here, we just extracted out the common test setup stuff into a <code>beforeEach</code>.</p>

<p>Now, maybe we can improve <code>NewCardView</code>&#8217;s API a little here. Something that&#8217;s receiving one of these <code>create-card</code> events will probably want to react to that event by finding out more details about the new card which the user is asking to create. Let&#8217;s elaborate on that second test and say that we want the <code>create-card</code> event to pass along the view which triggered the event.</p>

<figure class='code'><figcaption><span>new_card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;NewCardView&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">view = </span><span class="kc">null</span>
</span><span class='line'>  <span class="nx">beforeEach</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">loadFixtures</span> <span class="s2">&quot;index.html&quot;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">NewCardView</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;binds $el to the right DOM element&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">$el</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span> <span class="s1">&#39;section#new-card&#39;</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;triggers a create-card event when the add card button is clicked&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">eventSpy = </span><span class="nx">sinon</span><span class="p">.</span><span class="nx">spy</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">view</span><span class="p">.</span><span class="kc">on</span><span class="p">(</span> <span class="s1">&#39;create-card&#39;</span><span class="p">,</span> <span class="nx">eventSpy</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;section#new-card button&#39;</span><span class="p">).</span><span class="nx">click</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">eventSpy</span> <span class="p">).</span><span class="nx">toHaveBeenCalledWith</span><span class="p">(</span><span class="nx">view</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>All we&#8217;ve done here is expanded our expectation at the bottom to say that we expect our event spy to have been passed the view which triggered the event as an argument. That test will now fail, but it&#8217;s trivial to get it passing:</p>

<figure class='code'><figcaption><span>new_card_view.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">NewCardView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">el: </span><span class="s2">&quot;section#new-card&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">events:</span>
</span><span class='line'>    <span class="s2">&quot;click button&quot;</span><span class="o">:</span> <span class="s2">&quot;onClickButton&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">onClickButton: </span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">@trigger</span><span class="p">(</span> <span class="s1">&#39;create-card&#39;</span><span class="p">,</span> <span class="err">@</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>An extra 3 characters and we&#8217;ve added an argument to the <code>trigger</code> call which passes a reference to the view itself to anyone listening for that <code>create-card</code> event.</p>

<p>So if someone has received this event and has a reference to the view they&#8217;re probably going to want to get access to whatever text the user has entered into the text area. Let&#8217;s drive that API out:</p>

<figure class='code'><figcaption><span>new_card_view_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="s1">&#39;NewCardView&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">view = </span><span class="kc">null</span>
</span><span class='line'>  <span class="nx">beforeEach</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">loadFixtures</span> <span class="s2">&quot;index.html&quot;</span>
</span><span class='line'>    <span class="nv">view = </span><span class="k">new</span> <span class="nx">NewCardView</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># ... other tests ....</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;exposes the text area text&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;section#new-card textarea&#39;</span><span class="p">).</span><span class="nx">val</span><span class="p">(</span><span class="s1">&#39;I AM A NEW CARD&#39;</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">view</span><span class="p">.</span><span class="nx">getText</span><span class="p">()</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span> <span class="s1">&#39;I AM A NEW CARD&#39;</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;re using jQuery to simulate a user entering text into the text area, and then verifying that we can fetch that text using a <code>getText</code> method on the view. Of course this test will fail because the view has no <code>getText</code> method. Let&#8217;s address that:</p>

<figure class='code'><figcaption><span>new_card_view.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">NewCardView = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">el: </span><span class="s2">&quot;section#new-card&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">events:</span>
</span><span class='line'>    <span class="s2">&quot;click button&quot;</span><span class="o">:</span> <span class="s2">&quot;onClickButton&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">onClickButton: </span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">@trigger</span><span class="p">(</span> <span class="s1">&#39;create-card&#39;</span><span class="p">,</span> <span class="err">@</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">getText: </span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">@$</span><span class="p">(</span><span class="s1">&#39;textarea&#39;</span><span class="p">).</span><span class="nx">val</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;re using the view&#8217;s <code>$(...)</code> helper method to do a scoped lookup of the <code>&lt;textarea&gt;</code> element inside our view&#8217;s <code>el</code>. It is a shorthand way of saying <code>@$el.find('textarea')</code>. Then we just grab the value of that <code>&lt;textarea&gt;</code> and return it. Tests are green once more.</p>

<h2>Wrap up</h2>

<p>Our new card view now provides all the functionality we need, so we&#8217;ll wrap this up.</p>

<p>In this installment we&#8217;ve seen how Jasmine-jQuery can help assert what HTML is being rendered by our Backbone Views, and how its Fixtures functionality can help set up pre-requisite chunks of HTML content for the duration of a test. That said, we&#8217;ve also learned that if we require fixtures to test our views then this could indicate a poor design. We&#8217;ve observed that Backbone views act as a translation layer between the core of the application and the DOM. Finally, we&#8217;ve seen how to use jQuery to simulate user interactions and how sinon spy&#8217;s can be used to check that events are being triggered correctly.</p>

<p>In the <a href="http://blog.thepete.net/blog/2013/02/24/test-driven-backbone-dot-js-part-three/">next installment</a> of this series I cover where Controllers fit into a Backbone app and show how we can TDD the implementation of them.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Test-driven Backbone.js  - Part One]]></title>
    <link href="http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-one/"/>
    <updated>2013-01-23T08:02:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-one</id>
    <content type="html"><![CDATA[<p>In this series of posts I&#8217;m going to walk through some practical details on how we can develop Backbone.js applications in a test-driven manner. Developing this way leads to better structured applications, as we&#8217;ll discover.</p>

<h2>Setup</h2>

<p>We&#8217;ll be using backbone and underscore to build a single page app which simulates a card wall. We&#8217;ll be writing our app and our tests using coffeescript. If there&#8217;s enough interest I&#8217;d be happy to set up a JavaScript translation of the code snippets - please <a href="mailto:blog@thepete.net">let me know</a>. We&#8217;ll be  using Jasmine as our test runner and we&#8217;ll be using sinon.js to create test doubles (mocks and stubs). We&#8217;ll also use a few other small utilities and plugins as we go.</p>

<h2>Part one - test driven models</h2>

<p>Let&#8217;s start off simple and test-drive a Backbone model which will represent a card on the wall. Test-driven means writing the test <em>before</em> the production code, so we&#8217;ll start off by writing a test for the model, before the model even exists. I like to start off a new test file with a really dumb test that just drives out the initial setup of the class:</p>

<figure class='code'><figcaption><span>card_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">Card</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;is defined&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">Card</span> <span class="p">).</span><span class="o">not</span><span class="p">.</span><span class="nx">toBeUndefined</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>Pretty much the simplest test I can think of: check that <code>Card</code> has been defined somewhere. Of course when we run this test it will fail, because we haven&#8217;t defined that model yet. Let&#8217;s do that.</p>

<figure class='code'><figcaption><span>card.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">Card = </span><span class="s1">&#39;slime&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>OK, with that done our first test is passing.</p>

<p>I know, I know. We didn&#8217;t define <code>Card</code> to be a backbone model. I&#8217;m being a bit dogmatic here for a moment and following the test-driven tenent of doing the Simplest Possible Thing to get the test passing. In this case defining <code>Card</code> as a string is a simple thing to do, so that&#8217;s what I did. Using the keyword &#8216;slime&#8217; is a trick I picked up from Gary Bernhardt to indicate that this is obviously not finished code.</p>

<p>So, we have a slimed Card definition which passes the test. Our next step is to write a test which drives us to remove that slime and make <code>Card</code> a real Backbone.Model.</p>

<figure class='code'><figcaption><span>card_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">Card</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;is defined&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">Card</span> <span class="p">).</span><span class="o">not</span><span class="p">.</span><span class="nx">toBeUndefined</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;looks like a BB model&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">card = </span><span class="k">new</span> <span class="nx">Card</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">_</span><span class="p">.</span><span class="nx">isFunction</span><span class="p">(</span><span class="nx">card</span><span class="p">.</span><span class="nx">get</span><span class="p">)</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="kc">true</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">_</span><span class="p">.</span><span class="nx">isFunction</span><span class="p">(</span><span class="nx">card</span><span class="p">.</span><span class="nx">set</span><span class="p">)</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="kc">true</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>This new test verifies that Card instances &#8216;quack like a Model&#8217;. Since JavaScript doesn&#8217;t really have a strong notion of type I follow a duck-typing approach here and just verify that the Card instance implements methods that I&#8217;d expect a Backbone Model to have. This is good enough to drive us towards a more sensible initial implementation of <code>Card</code>:</p>

<figure class='code'><figcaption><span>card.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">Card = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that I&#8217;m still sticking to the Simplest Possible Thing tenent. Our test doesn&#8217;t expect <code>Card</code> to have any additional functionality beyond the vanilla functionality it gets as a Backbone.Model, so I don&#8217;t bother to use <code>Backbone.Model.extend</code>. When I&#8217;m driving out code this way it&#8217;s not unusual that I <em>never</em> have to go beyond what I thought at the time was a placeholder implementation. I wouldn&#8217;t be surprised if that holds true here and that we end up never needing to extend <code>Card</code> beyond this vanilla implementation.</p>

<h2>A Card Wall</h2>

<p>  Now that we have a <code>Card</code> defined, let&#8217;s look at building a Wall of cards. There&#8217;s a temptation here to think &#8216;Oh, a wall of cards is like a collection of cards; let&#8217;s define it as a Backbone.Collection&#8217;. That&#8217;s a bad idea here. A card wall does <em>contain</em> a collection of cards, but it will likely also have other attributes. It might have a title, and an owner maybe. I&#8217;ve found that with Backbone if you&#8217;re modeling an entity in your system that&#8217;s more than just purely a collection of other things then it&#8217;s best to represent that entity as a Backbone.Model which <em>contains</em> a Backbone.Collection as an attribute, rather than modelling that entity as a Backbone.Collection with additional custom properties. If you use custom properties rather than the attributes of a Backbone.Model then you lose all the nice functionality that Backbone gives your model&#8217;s attributes (e.g. serialization, change events).</p>

<p>Given that, let&#8217;s test-drive a <code>CardWall</code> which contains a collection of <code>Cards</code>. Again we&#8217;ll start off really simply:</p>

<figure class='code'><figcaption><span>card_wall_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardWall</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;is defined&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cardWall = </span><span class="k">new</span> <span class="nx">CardWall</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span> <span class="p">).</span><span class="o">not</span><span class="p">.</span><span class="nx">toBeUndefined</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>This test will fail because we haven&#8217;t defined <code>CardWall</code> anywhere. Let&#8217;s get it to pass:</p>

<figure class='code'><figcaption><span>card_wall.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">CardWall = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span>
</span></code></pre></td></tr></table></div></figure>


<p>That gets our tests back to green.</p>

<p>Note that I&#8217;ve drifting a little from my previous Simplest Possible Thing dogmatism. I know that I&#8217;m going to be making a Backbone.Model and I&#8217;m gaining a bit more confidence in my TDD flow, so I&#8217;m going to start taking slightly bigger TDD steps and define <code>CardWall</code> as a Backbone.Model even though the test isn&#8217;t strictly requiring that.</p>

<p>Taking bigger TDD steps like this is OK, as long as we&#8217;re always ready to slow down and taking smaller steps if we start feeling uncomfortable with our code. A good rule of thumb is that if you&#8217;re stuck in the Red part of your TDD cycle for more than a few minutes then you&#8217;re probably taking steps which are too big and should dial it back. As an aside, Kent Beck has a very interesting discussion around this in a <a href="http://www.infoq.com/presentations/responsive-design">presentation he did a few years ago</a> on design principles - it&#8217;s well worth a watch. And hey, if Kent bends the TDD &#8216;rules&#8217; sometimes then we&#8217;re allowed to too.</p>

<p>OK, now let&#8217;s drive out a <code>cards</code> collection on the <code>CardWall</code> model as we discussed earlier.</p>

<figure class='code'><figcaption><span>card_wall_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardWall</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;is defined&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cardWall = </span><span class="k">new</span> <span class="nx">CardWall</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span> <span class="p">).</span><span class="o">not</span><span class="p">.</span><span class="nx">toBeUndefined</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;has a collection of cards&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cardWall = </span><span class="k">new</span> <span class="nx">CardWall</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span><span class="p">.</span><span class="nx">has</span><span class="p">(</span><span class="s1">&#39;cards&#39;</span><span class="p">)</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="kc">true</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;cards&#39;</span><span class="p">).</span><span class="nx">models</span> <span class="p">).</span><span class="nx">toBeDefined</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;re checking that our card wall has a <code>cards</code> attribute, and then we&#8217;re checking that the <code>cards</code> attribute &#8216;quacks like&#8217; a Backbone.Collection by checking that is has a <code>models</code> property.</p>

<p>Now let&#8217;s get this test passing:</p>

<figure class='code'><figcaption><span>card_wall.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">Cards = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span>
</span><span class='line'>
</span><span class='line'><span class="nv">CardWall = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">defaults:</span>
</span><span class='line'>    <span class="nv">cards: </span><span class="k">new</span> <span class="nx">Cards</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is a pretty big step, but it gets our tests back to green. We&#8217;ve defined a <code>Cards</code> collection, and we&#8217;ve extended our <code>CardWall</code> model to have an instance of that collection as a <code>cards</code> attribute  by default.</p>

<h2>Pause to refactor</h2>

<p>Our tests are green again, but instead of moving on to our next test I&#8217;m going to take a moment to refactor. It&#8217;s really easy to forget the Refactor part of the Red-Green-Refactor cycle but focusing on Refactor is crucial if you want TDD to drive you towards cleaner code. Without refactoring frequently you will end up with a codebase which is functional but not maintainable. Over time changes will become more and more expensive, and tests will take longer and longer to write and get passing.</p>

<p>So, let&#8217;s refactor! I&#8217;m going to <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY up</a> our card wall tests a little bit:</p>

<figure class='code'><figcaption><span>card_wall_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardWall</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nv">cardWall = </span><span class="kc">null</span>
</span><span class='line'>  <span class="nx">beforeEach</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cardWall = </span><span class="k">new</span> <span class="nx">CardWall</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;is defined&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span> <span class="p">).</span><span class="o">not</span><span class="p">.</span><span class="nx">toBeUndefined</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;has a collection of cards&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span><span class="p">.</span><span class="nx">has</span><span class="p">(</span><span class="s1">&#39;cards&#39;</span><span class="p">)</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="kc">true</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;cards&#39;</span><span class="p">).</span><span class="nx">models</span> <span class="p">).</span><span class="nx">toBeDefined</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>All I&#8217;ve done here is pull out a shared <code>cardWall</code> variable and set it up in a <code>beforeEach</code> function. A small change, but it reduces some duplication from the tests and makes them a little bit easier to read. Small refactorings like this sometimes seem unnecessary in the moment but applying refactorings like this continuously over time they will do amazing things to your code. Imagine living in a codebase which always feels like a greenfield project.</p>

<p>What&#8217;s next? Let&#8217;s give <code>CardWall</code> a <code>title</code> attribute, and have it default to something sensible:</p>

<figure class='code'><figcaption><span>card_wall_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardWall</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nv">cardWall = </span><span class="kc">null</span>
</span><span class='line'>  <span class="nx">beforeEach</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cardWall = </span><span class="k">new</span> <span class="nx">CardWall</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># ... other tests here ...</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;has a default title&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">cardWall</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;title&#39;</span><span class="p">)</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span> <span class="s1">&#39;Card Wall&#39;</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>And let&#8217;s get that test to pass:</p>

<figure class='code'><figcaption><span>card_wall.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">Cards = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span>
</span><span class='line'>
</span><span class='line'><span class="nv">CardWall = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">defaults: </span><span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cards: </span><span class="k">new</span> <span class="nx">Cards</span>
</span><span class='line'>    <span class="nv">title: </span><span class="s1">&#39;Card Wall&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>And we&#8217;re back to green.</p>

<h2>Adding cards to a card wall</h2>

<p>We are going to want to add <code>Card</code> instances to our <code>CardWall</code>. A client of <code>CardWall</code> could do that with the existing implementation by doing something like <code>myCardWall.get('cards').add( cardProperties )</code>, but that&#8217;s not a nice approach. It&#8217;s ugly to read and it&#8217;s a <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a> violation which exposes the internals of <code>CardWall</code>. Let&#8217;s expose a nice helper method on <code>CardWall</code> that hides those details and makes the client&#8217;s life easier. Here&#8217;s a test describing what we want the method to do:</p>

<figure class='code'><figcaption><span>card_wall_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardWall</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nv">cardWall = </span><span class="kc">null</span>
</span><span class='line'>  <span class="nx">beforeEach</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cardWall = </span><span class="k">new</span> <span class="nx">CardWall</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># ... other tests here ...</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;can add cards to the cards collection&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nx">cardWall</span><span class="p">.</span><span class="nx">addCard</span><span class="p">(</span> <span class="nv">text: </span><span class="s1">&#39;new card text&#39;</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'>    <span class="nv">addedCard = </span><span class="nx">cardWall</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;cards&#39;</span><span class="p">).</span><span class="nx">at</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">addedCard</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;text&#39;</span><span class="p">)</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="s1">&#39;new card text&#39;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We expect to be able to call an <code>addCard</code> method which will add a card to the CardWall&#8217;s <code>cards</code> collection with the appropriate attributes. We can get that test passing with a one-line method:</p>

<figure class='code'><figcaption><span>card_wall.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">Cards = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span>
</span><span class='line'>
</span><span class='line'><span class="nv">CardWall = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">defaults:</span>
</span><span class='line'>    <span class="nv">cards: </span><span class="k">new</span> <span class="nx">Cards</span>
</span><span class='line'>    <span class="nv">title: </span><span class="s1">&#39;Card Wall&#39;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">addCard: </span><span class="nf">(attrs)-&gt;</span>
</span><span class='line'>    <span class="nx">@get</span><span class="p">(</span><span class="s1">&#39;cards&#39;</span><span class="p">).</span><span class="nx">add</span><span class="p">(</span> <span class="nx">attrs</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Testing events</h2>

<p>Clients of our <code>CardWall</code> model are going to want to know when cards are added to our wall. By default a Backbone model only fires a change event when one of its attributes is re-assigned, not when one of its attributes changes internally. That means that a client which has subscribed to changes on a <code>CardWall</code> instance won&#8217;t be notified when its <code>cards</code> collection changes. Let&#8217;s confirm that problem via a test:</p>

<figure class='code'><figcaption><span>card_wall_spec.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nx">describe</span> <span class="nx">CardWall</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>  <span class="nv">cardWall = </span><span class="kc">null</span>
</span><span class='line'>  <span class="nx">beforeEach</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">cardWall = </span><span class="k">new</span> <span class="nx">CardWall</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># ... other tests here ...</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">it</span> <span class="s1">&#39;fires a change:cards event when a card is added&#39;</span><span class="p">,</span> <span class="o">-&gt;</span>
</span><span class='line'>    <span class="nv">eventSpy = </span><span class="nx">sinon</span><span class="p">.</span><span class="nx">spy</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">cardWall</span><span class="p">.</span><span class="kc">on</span><span class="p">(</span><span class="s1">&#39;change:cards&#39;</span><span class="p">,</span><span class="nx">eventSpy</span><span class="p">)</span>
</span><span class='line'>    <span class="nx">cardWall</span><span class="p">.</span><span class="nx">addCard</span><span class="p">()</span>
</span><span class='line'>    <span class="nx">expect</span><span class="p">(</span> <span class="nx">eventSpy</span><span class="p">.</span><span class="nx">called</span> <span class="p">).</span><span class="nx">toBe</span><span class="p">(</span><span class="kc">true</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;re creating a Sinon <a href="http://sinonjs.org/docs/#spies">spy function</a> and registering that function with our <code>cardWall</code> instance as an event handler for the <code>change:cards</code> event. So whenever <code>cardWall</code> fires a <code>change:cards</code> event that spy function will be called. We then add a card to <code>cardWall</code> using the <code>addCard</code> method we created previously and then check whether our spy has been called. If the spy was called then that <code>change:cards</code> event has indeed been published. If it wasn&#8217;t called then we know that the <code>change:cards</code> event isn&#8217;t firing when we add a card via <code>addCard</code>.</p>

<p>As expected, this test fails because a Model doesn&#8217;t automatically notify subscribers of changes <em>inside</em> its attributes. However we can get the test to pass pretty simply:</p>

<figure class='code'><figcaption><span>card_wall.coffee</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='coffeescript'><span class='line'><span class="nv">Cards = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span>
</span><span class='line'>
</span><span class='line'><span class="nv">CardWall = </span><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span><span class="p">.</span><span class="nx">extend</span>
</span><span class='line'>  <span class="nv">defaults:</span>
</span><span class='line'>    <span class="nv">cards: </span><span class="k">new</span> <span class="nx">Cards</span>
</span><span class='line'>    <span class="nv">title: </span><span class="s1">&#39;Card Wall&#39;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nv">addCard: </span><span class="nf">(attrs)-&gt;</span>
</span><span class='line'>    <span class="nx">@get</span><span class="p">(</span><span class="s1">&#39;cards&#39;</span><span class="p">).</span><span class="nx">add</span><span class="p">(</span> <span class="nx">attrs</span> <span class="p">)</span>
</span><span class='line'>    <span class="nx">@trigger</span><span class="p">(</span><span class="s1">&#39;change:cards&#39;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;ve added a <code>trigger</code> call at the end of our <code>addCard</code> method. This will fire off the expected event whenever we add a card. With that change our tests are back to green, and we&#8217;re at a good point to wrap up this installment.</p>

<h2>What have we covered</h2>

<p>So what did we cover in this installment?</p>

<p>We&#8217;ve learned the basics of how to test-drive a Backbone model. We&#8217;ve learned that we should strive to get tests passing by doing the Simplest Possible Thing, but that we don&#8217;t need to be to dogmatic about that. We&#8217;ve discovered that a Backbone.Collection is only approriate for modelling a pure collection of items. We&#8217;ve seen that it&#8217;s better to encapsulate access to internal attributes by using helpful functions like <code>addCard</code>. Finally we&#8217;ve seen how to use Sinon spies to test basic Backbone event publication.</p>

<h2>No DOM, no jQuery</h2>

<p>One final thing to note before we wrap up - we have not made any reference to the DOM in these tests. In fact, when developing this code I ran my tests within node.js with not a DOM implementation in sight. This is a very important point, and a key property of a well-structured Backbone application - Backbone views should be the only thing referencing the DOM (and therefore the only thing using JQuery&#8217;s almighty $).</p>

<p>The flip side of keeping the DOM and jQuery contained without our Views is that we should always strive to keep our Backbone Views as skinny and logic-free as possible. Because Views interact with the DOM they are particularly tricky to test, and our tests are slower to run because we have to run them in a browser. We want to keep our views as simple as possible so that we don&#8217;t have to write too many of those tricky tests. Instead we want to push logic into other parts of our application where it can be easily tested in isolation.</p>

<p>In the <a href="http://blog.thepete.net/blog/2013/01/23/test-driven-backbone-dot-js-part-two/">next installment</a> we&#8217;ll dive into testing Backbone Views and their interaction with the DOM. I&#8217;ll also go into more details on what a View&#8217;s responsibilities should be.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Deploying to Heroku from CI - the gory details]]></title>
    <link href="http://blog.thepete.net/blog/2013/01/22/deploying-to-heroku-from-ci-the-gory-details/"/>
    <updated>2013-01-22T17:14:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2013/01/22/deploying-to-heroku-from-ci-the-gory-details</id>
    <content type="html"><![CDATA[<p>In my <a href="http://blog.thepete.net/blog/2013/01/21/deploying-to-heroku-from-ci">previous post</a> I discussed why you might want to deploy to Heroku as part of a CI build. I demonstrated how my <code>heroku-headless</code> gem makes it very easy to script such a deployment. In this post I&#8217;ll go into the details on how that gem does its work. I&#8217;ll talk about what the Heroku deployment tooling expects to be available, why that&#8217;s not necessarily going to be there in the context of a CI build environment, and how the gem helps resolve that.</p>

<h2>Heroku&#8217;s deployment model</h2>

<p>Heroku&#8217;s deployment model centers around pushing git commits to a special heroku git repo. When you want to deploy a new version of your application you push the git commit corresponding to that build up to the special heroku repo. As a side effect of updating the remote repo heroku will deploy a copy of the application as of that commit.</p>

<p>Of course Heroku won&#8217;t let anyone deploy a new version of your application. It only allows a registered collaborator to push to an app&#8217;s repo. You can manage which heroku users are collaborators of the app via the Heroku <a href="https://dashboard.heroku.com/apps">web interface</a>, or via the <code>heroku sharing</code> set of commands.</p>

<p>But how does Heroku know which user is trying to push to an app&#8217;s heroku repo? It looks at the ssh key that git is using when it makes the push. Unless the ssh key is registered to a listed collaborator of the app then Heroku will reject the push.</p>

<p>A Heroku user usually registers their ssh key with Heroku using the <code>heroku keys:add</code> command. The average Heroku user only has to perform this procedure when they&#8217;re setting up a new dev machine. Once it&#8217;s done Heroku deploys are very low-friction since your registered ssh key is automatically used by git whenever you push. <code>git push heroku</code> is all you need to do. It&#8217;s easy to forget that you registered your ssh key with Heroku at one point.</p>

<h2>What&#8217;s different for a headless CI deploy</h2>

<p>Things can be a bit different when deploying from a CI agent. The CI agent&#8217;s user may not even have an ssh key generated, and if it does it is probably not associated with a Heroku user that has collaborator access to the Heroku app you want to deploy to.</p>

<p>One way to solve this would be to ensure that the CI agent user has a ssh key generated and to manually register that key for a Heroku user who has collaborator rights to the target app. This works, but it&#8217;s not ideal. The manual setup is tedious and error prone, and you have to do it for every agent in your CI system. You also have to make sure that the Heroku user which the CI agent is acting as is registered as a collaborator for every Heroku app that it might be deploying to. If you&#8217;re using a cloud-like CI system such as <a href="http://travis-ci.org">Travis</a> then you might not even have access to the CI agent in order to generate and register an ssh key, and even if you did you have no control over which agent will be running your next build. With some systems you will be given an agent with a totally pristine environment for each build. In other words, you can&#8217;t always rely on manually pre-configuring an agent&#8217;s environment.</p>

<p>All of this means that it&#8217;s better to avoid the need for manual setup of pre-existing ssh keys. A better approach is to generate a <em>disposable ssh key</em>, register it with a Heroku user, do a git push using that key, and then remove the disposable key.</p>

<p>As luck would have it Heroku exposes API for adding and removing ssh keys for a user. When you use the Heroku API you pass a secret API key which Heroku uses to both authenticate you and also to figure out which user you are acting as. That allows the API to know which user&#8217;s keys you are managing.</p>

<p>This <em>disposable key</em> approach is more secure and has no requirements on a CI agent having a previously configured environment. You could take a totally pristine box and use it to run a deploy without any other setup. Transversely, you can test a deploy script on a full-configured developer workstation without your local environment affecting the deploy script and without the deploy affecting your environment.</p>

<p>Note that the disposable key approach still requires that you have previously set up a Heroku user who has collaborator access to the app you are deploying to. It also requires that your build scripts have access to that user&#8217;s secret Heroku API key. You need to be careful here - if that key gets into the wrong hands it could be used to run up a very large bill with Heroku. As I said in <a href="http://blog.thepete.net/blog/2013/01/21/deploying-to-heroku-from-ci">my previous post</a>, you&#8217;ll want to use a feature in your CI system along the lines of Travis&#8217;s <a href="http://about.travis-ci.org/docs/user/build-configuration/#Secure-environment-variables">secure environment variables</a> to protect access to that key. Most CI/CD systems provide similar functionality.</p>

<h2>The steps for a headless deploy using disposable keys</h2>

<p>So we have our basic approach laid out. Whenever we want to deploy our app we need our script to:</p>

<ul>
<li>generate a new disposable ssh key</li>
<li>register that key with Heroku</li>
<li>use the key to deploy the app via a git push</li>
<li>unregister the key with Heroku</li>
<li>delete the key locally</li>
</ul>


<h2>Implementation details</h2>

<p>I&#8217;ll now briefly describe how the <strong>heroku-headless</strong> gem does all that. If you want more details I encourage you to study the <a href="https://github.com/moredip/heroku-headless">gem&#8217;s implementation</a>. It&#8217;s really pretty simple - a handful of classes, about 200 lines of code in total.</p>

<h3>Creating a local scratch directory</h3>

<p>We use ruby&#8217;s <a href="http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tmpdir/rdoc/Dir.html">tmpdir module</a> to generate a temporary working directory which will contain our disposable ssh keys and some configuration files. After we&#8217;re done with the deploy we&#8217;ll delete this directory.</p>

<h3>Generating a disposable ssh key</h3>

<p>Next we&#8217;ll generate our disposable public/private key pair inside our new scratch directory. We use the <code>ssh-keygen</code> command which is available on pretty much any unix box: <code>ssh-keygen -t rsa -N "" -C #{ssh_key_name} -f #{ssh_key_path}</code></p>

<h3>Registering the key with Heroku</h3>

<p>The <code>heroku-api</code> gem is our friend here. We create an instance of the Heroku API with <code>heroku = Heroku::API.new()</code>. If you don&#8217;t explicitly pass in an API key the gem will use the value of the <code>HEROKU_API_KEY</code> environment variable, so you need to make sure that that environment variable is set correctly by your CI system just prior to running your deploy script. Alternatively you can explicitly pass in an API key to the constructor, but again you need to be careful you <strong>don&#8217;t expose this key</strong>.</p>

<p>Given all of that, we can register our disposable ssh key with that API key&#8217;s Heroku user by doing something like:</p>

<figure class='code'><figcaption><span>register-disposable-key</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">heroku</span> <span class="o">=</span> <span class="no">Heroku</span><span class="o">::</span><span class="no">API</span><span class="o">.</span><span class="n">new</span><span class="p">()</span>
</span><span class='line'><span class="n">public_ssh_key</span> <span class="o">=</span> <span class="no">File</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="n">path_to_public_ssh_key</span><span class="p">)</span>
</span><span class='line'><span class="n">heroku</span><span class="o">.</span><span class="n">post_key</span><span class="p">(</span><span class="n">public_ssh_key</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that we&#8217;re sending the <em>public</em> key to Heroku. Private ssh keys are never exposed.</p>

<h3>Pushing to the heroku git remote using our disposable key</h3>

<p>This is the fiddly bit. We need to have git push to heroku using that newly generated ssh key, but we don&#8217;t want to mess with any system ssh configuration which might be in place. Luckily git allows you to override the path to the underlying ssh executable it uses when connecting to a remote repo, via a <code>GIT_SSH</code> environment variable. We&#8217;ll use that to point git to a little wrapper script. This script calls through to the system&#8217;s standard ssh executable but adds a few command line arguments along the way. Those command line arguments will tell ssh to identify itself using our disposable key (as opposed to whatever may be setup in <code>~/.ssh/</code>). We also add a few arguments which tell ssh to not ask for confirmation the first time we connect to the heroku host, and also to prevent ssh from recording the heroku host as a known host.</p>

<p>The wrapper script looks like this:</p>

<figure class='code'><figcaption><span>git_ssh_wrapper.sh</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="c">#!/bin/sh</span>
</span><span class='line'><span class="nb">exec </span>ssh -o <span class="nv">StrictHostKeychecking</span><span class="o">=</span>no -o <span class="nv">CheckHostIP</span><span class="o">=</span>no -o <span class="nv">UserKnownHostsFile</span><span class="o">=</span>/dev/null -i /path/to/disposable_ssh_key -- <span class="s2">&quot;$@&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>All credit to <a href="http://stackoverflow.com/questions/3496037/how-to-specify-which-ssh-key-to-use-within-git-for-git-push-in-order-to-have-git">this Stack Overflow question</a> which that wrapper script is based on.</p>

<p>Once we&#8217;ve generated that script and placed it in our scratch directory we can ask git to push to our app&#8217;s heroku repo using that custom ssh wrapper like so:</p>

<figure class='code'><figcaption><span>push-to-heroku</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="nb">system</span><span class="p">(</span> <span class="p">{</span><span class="s1">&#39;GIT_SSH&#39;</span><span class="o">=&gt;</span><span class="n">custom_git_ssh_path</span><span class="p">},</span> <span class="s2">&quot;git push git@heroku.com:</span><span class="si">#{</span><span class="n">app_name</span><span class="si">}</span><span class="s2">.git HEAD:master&quot;</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that in this example we&#8217;re pushing whatever HEAD currently points to, but we could push any arbitrary commit up to Heroku using this same command.</p>

<h3>Deregistering the disposable ssh key</h3>

<p>This one is easy: <code>heroku.delete_key(ssh_key_name)</code>. The ssh_key_name we pass in should be the same key name we passed to ssh-keygen via the -C flag.</p>

<h3>Cleanup</h3>

<p>Lastly, we clean up after ourselves by deleting the local scratch directory.</p>

<h2>Fin</h2>

<p>That&#8217;s it. It did take a fair amount of Internet research to figure all that out, but I should be clear that almost all of what I&#8217;ve described was lifted from other blog posts, Stack Overflow answers, etc. Hopefully by collating that info here I&#8217;ll help someone else travelling down a similar path. And again, if you don&#8217;t really care about the details and just want to get your app deployed via CI then just use the heroku-headless gem and move on!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Deploying to Heroku from CI]]></title>
    <link href="http://blog.thepete.net/blog/2013/01/21/deploying-to-heroku-from-ci/"/>
    <updated>2013-01-21T21:17:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2013/01/21/deploying-to-heroku-from-ci</id>
    <content type="html"><![CDATA[<p>If you&#8217;re working on top of a modern web stack then the <a href="http://www.heroku.com/">Heroku</a> hosting platform is a compelling option for standing up an instance of your app with what is usually a trivial amount of effort. No need to provision EC2 servers, write chef recipes, or mess with deploy tools. Just run a couple of commands in the shell and then <code>git push heroku</code>.</p>

<h2>Heroku as a staging environment</h2>

<p>This makes Heroku a compelling choice for hosting a staging environment for your application. Staging environment contains the latest &#8216;good&#8217; build of your app. They are used for things like automated acceptance testing, manual QA, story sign-off, or internal demos.</p>

<p>Hooking up an automatic staging environment deploy to the end of a CI run is a nice way of ensuring that your staging environment always contain the freshest good build of your app.</p>

<h2>Headless Heroku deploys are fiddly</h2>

<p>Unfortunately Heroku&#8217;s tooling isn&#8217;t really optimized for deploying from a CI agent - sometimes referred to as <em>headless</em> deployment. Heroku is really geared towards deployment from a developer or operator workstation. It expects you to have an SSH key registered with Heroku before deploying, and to have a heroku remote configured in the local git repo you&#8217;re deploying from. That&#8217;s a very reasonable assumption for a developer working on an app, but it&#8217;s not so reasonably for a CI agent. A CI agent may well be building multiple different apps, and often clears out things like git repos between builds. In the extreme case there are hosted tools like <a href="https://travis-ci.org/">Travis CI</a> where each build of your app takes place on essentially a totally fresh box, with no ability to pre-configure things like SSH keys.</p>

<p>This isn&#8217;t an insurmountable problem. It is <em>possible</em> to deploy from a git commit to Heroku in these circumstances. It&#8217;s just a bit of a hassle to figure out. But luckily for you I&#8217;ve figured it out on your behalf, and even released a ruby gem which does the work for you.</p>

<h2>gem install heroku-headless</h2>

<p>This gem grew out of me setting up Travis to deploy to a Heroku app after each successful CI build. After getting it working I distilled the relevant magic into the heroku-headless gem.</p>

<p>Using it is as simple as:</p>

<figure class='code'><figcaption><span>travis-after-script</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="nb">require</span> <span class="s1">&#39;heroku-headless&#39;</span>
</span><span class='line'><span class="no">HerokuHeadless</span><span class="o">::</span><span class="no">Deployer</span><span class="o">.</span><span class="n">deploy</span><span class="p">(</span> <span class="s1">&#39;your-app-name&#39;</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>This script will deploy the commit you currently have checked out in your local repo to the Heroku app name you specify. The only other setup needed for that script is to have a <code>HEROKU_API_KEY</code> environment variable set, where the user associated with that api key is registered as a collaborator on the Heroku app you&#8217;re deploying to. Obviously Heroku doesn&#8217;t let random people just deploy arbitrary code to an app.</p>

<p>If you register a script like the one above as an after-script in your Travis setup then that Heroku app will always be running the last successful build of your application. Very handy for acceptance tests, manual QA, or showcasing.</p>

<h2>Keep that API key secret</h2>

<p>That Heroku API key should be considered a very private secret unless you want someone running up a huge bill on your Heroku account. I would advise not checking that key into source control. Using something like Travis&#8217;s <a href="http://about.travis-ci.org/docs/user/build-configuration/#Secure-environment-variables">secure environment variables</a> is a good way to get that secret injected into your build scripts without exposing it to prying eyes.</p>

<h2>Bonus Feature: disposable apps</h2>

<p>While building out the functionality in heroku-headless I also experimented with the creation of disposable apps. The concept there is that you might want to create an entirely new Heroku app, deploy to it, run some tests, and then delete the app entirely. I never ended up using this functionality, but it&#8217;s in the gem. To use it you&#8217;d do something like:</p>

<figure class='code'><figcaption><span>deploy-to-disposable-app</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="nb">require</span> <span class="s1">&#39;heroku-headless/disposable_deployer&#39;</span>
</span><span class='line'><span class="no">HerokuHeadless</span><span class="o">::</span><span class="no">DisposableDeployer</span><span class="o">.</span><span class="n">new</span><span class="o">.</span><span class="n">go</span>
</span></code></pre></td></tr></table></div></figure>


<h2>UPDATE: Behind the curtain</h2>

<p>I wrote a <a href="http://blog.thepete.net/blog/2013/01/22/deploying-to-heroku-from-ci-the-gory-details/">follow up post</a> to this one which describes how the heroku-headless gem actually works. Check that out if you&#8217;re interested in the gory details.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Writing iOS acceptance tests using Kiwi]]></title>
    <link href="http://blog.thepete.net/blog/2012/11/18/writing-ios-acceptance-tests-using-kiwi/"/>
    <updated>2012-11-18T19:24:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2012/11/18/writing-ios-acceptance-tests-using-kiwi</id>
    <content type="html"><![CDATA[<p>In this post I&#8217;ll describe an experiment where rather than using <a href="http://testingwithfrank.com">Frank</a> to write iOS acceptance tests I instead combined <a href="https://github.com/allending/Kiwi">Kiwi</a> with the low-level libraries that Frank uses internally. This allowed me to write acceptance tests in pure Objective-C which run in the app process itself, very similarly to the way <a href="http://github.com/square/kif">KIF</a> works.</p>

<h2>What?</h2>

<p>Before I start, let me be clear that I personally wouldn&#8217;t use this approach to writing acceptance tests. I much prefer using a higher-level language like ruby to write these kinds of tests. The test code is way less work and way more expressive, assuming you&#8217;re comfortable in ruby. And that&#8217;s why I wanted to try this experiment. I&#8217;ve spoken to quite a few iOS developers over time who are <em>not</em> comfortable writing tests in ruby. They are more comfortable in Objective-C than anything else, and would like to write their tests in the same language they use for their production code. Fair enough.</p>

<h2>Why not KIF?</h2>

<p>I suspect that the ability to write your tests in Objective-C is the main reason that some developers turn to KIF for their acceptance tests.</p>

<p>I have two problems with KIF though. First, the tool conflates three distinct activities - test organization, view selection, and simulating interactions. I think these activities are better served when broken out into distinct responsibilities. In the case of test organization, tools like Cedar and Kiwi have had a lot of uptake and Kiwi in particular is becoming a very popular choice. Alternatively you can use one of the more established tools like OCUnit. These tools handle things like organizing test code into test cases and test suites, running those tests, asserting on values, and reporting the output in a useful way. Why re-invent that wheel in KIF, when it&#8217;s the core competency of these other tools? When it comes to view selection and simulating interactions, because these two are intertwined in KIF you end up with really verbose code if you want to do something like find an element, check it&#8217;s visible, tap it, then check it went away.</p>

<p>The second concern I have with KIF is simply that it doesn&#8217;t seem to be under active development. I have also heard from a few people that it&#8217;s not really used much by teams within Square at this point.</p>

<h2>So what&#8217;s the alternative?</h2>

<p>I visited a couple of iOS development teams in Australia recently and this topic came up with both teams while chatting with them. It occurred to me that you could probably implement KIF-style tests pretty simply using the view selection and automation library which Frank uses, plus Kiwi for a test runner. I had a 15 hour flight back to San Francisco, and this seemed like a fun experiment to while away a couple of those hours.</p>

<p>The idea is simple really. Wire up Kiwi just like you would for <a href="http://developer.apple.com/library/ios/#documentation/DeveloperTools/Conceptual/UnitTesting/02-Setting_Up_Unit_Tests_in_a_Project/setting_up.html#//apple_ref/doc/uid/TP40002143-CH3-SW6">Application Unit Tests</a>, but rather than doing white-box testing on individual classes inside your app you instead drive your app&#8217;s UI by selecting views programmatically using <a href="https://github.com/testingwithfrank/Shelley">Shelley</a> (Frank&#8217;s view selection engine) and then simulate interacting with those views using <a href="https://github.com/testingwithfrank/PublicAutomation">PublicAutomation</a> (the lightweight wrapper over Apple&#8217;s private UIAutomation framework that Frank also uses). Alternatively after selecting views using Shelley you might then just programatically inspect the state of the views to confirm that the UI has responded appropriately to previous steps in your test.</p>

<h2>How does it work?</h2>

<p>To prove this concept out I wrote a really simple User Journey test which was exercising the same 2012 Olympics app I&#8217;ve used as an example in <a href="http://blog.thepete.net/blog/2012/06/24/writing-your-first-frank-test">previous</a> <a href="http://blog.thepete.net/blog/2012/07/22/running-frank-as-part-of-ios-ci">posts</a>. Here&#8217;s what it looks like:</p>

<figure class='code'><figcaption><span>BasicUserJourney_Spec.m</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
</pre></td><td class='code'><pre><code class='obj-c'><span class='line'><span class="cp">#import &quot;AcceptanceSpecHelper.h&quot;</span>
</span><span class='line'><span class="cp">#import &quot;EventsScreen.h&quot;</span>
</span><span class='line'>
</span><span class='line'><span class="n">SPEC_BEGIN</span><span class="p">(</span><span class="n">BasicUserJourney</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="n">describe</span><span class="p">(</span><span class="s">@&quot;User Journey&quot;</span><span class="p">,</span> <span class="o">^</span><span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">beforeAll</span><span class="p">(</span><span class="o">^</span><span class="p">{</span>
</span><span class='line'>        <span class="n">sleepFor</span><span class="p">(</span><span class="mf">0.5</span><span class="p">);</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>    <span class="n">it</span><span class="p">(</span><span class="s">@&quot;visits the event screen and views details on a couple of events&quot;</span><span class="p">,</span> <span class="o">^</span><span class="p">{</span>
</span><span class='line'>        <span class="n">EventsScreen</span> <span class="o">*</span><span class="n">eventsScreen</span> <span class="o">=</span> <span class="p">[</span><span class="n">EventsScreen</span> <span class="n">screen</span><span class="p">];</span>
</span><span class='line'>        <span class="p">[[</span><span class="n">theValue</span><span class="p">([</span><span class="n">eventsScreen</span> <span class="n">currentlyOnCorrectTab</span><span class="p">])</span> <span class="n">should</span><span class="p">]</span> <span class="n">beTrue</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">[</span><span class="n">eventsScreen</span> <span class="nl">selectEvent:</span><span class="s">@&quot;beach volleyball&quot;</span><span class="p">];</span>
</span><span class='line'>        <span class="p">[[</span><span class="n">theValue</span><span class="p">([</span><span class="n">eventsScreen</span> <span class="nl">currentlyViewingEventDetailsFor:</span><span class="s">@&quot;Beach Volleyball&quot;</span><span class="p">])</span> <span class="n">should</span><span class="p">]</span> <span class="n">beTrue</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">[</span><span class="n">eventsScreen</span> <span class="n">goBackToOverview</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">[</span><span class="n">eventsScreen</span> <span class="nl">selectEvent:</span><span class="s">@&quot;canoe sprint&quot;</span><span class="p">];</span>
</span><span class='line'>        <span class="p">[[</span><span class="n">theValue</span><span class="p">([</span><span class="n">eventsScreen</span> <span class="nl">currentlyViewingEventDetailsFor:</span><span class="s">@&quot;Canoe Sprint&quot;</span><span class="p">])</span> <span class="n">should</span><span class="p">]</span> <span class="n">beTrue</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'><span class="p">});</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="n">SPEC_END</span>
</span></code></pre></td></tr></table></div></figure>


<p>I&#8217;m using the <a href="http://www.cheezyworld.com/2010/11/09/ui-tests-not-brittle/">Page Object</a> pattern to encapsulate the details of how each screen is automated. In this case the <code>EventsScreen</code> class is playing that Page Object role.</p>

<p>The aim here is that you can read the high-level flow test above and quite easily get the gist of what it&#8217;s testing. Now let&#8217;s dive into the details and see how the magic happens inside <code>EventsScreen</code>:</p>

<figure class='code'><figcaption><span>EventsScreen.m</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
<span class='line-number'>62</span>
<span class='line-number'>63</span>
</pre></td><td class='code'><pre><code class='obj-c'><span class='line'><span class="cp">#import &quot;EventsScreen.h&quot;</span>
</span><span class='line'>
</span><span class='line'><span class="k">@interface</span> <span class="nc">EventsScreen</span><span class="p">()</span>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="n">NSArray</span> <span class="o">*</span><span class="p">)</span><span class="nl">viewsViaSelector:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">selector</span><span class="p">;</span>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="n">UIView</span> <span class="o">*</span><span class="p">)</span><span class="nl">viewViaSelector:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">selector</span><span class="p">;</span>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="nl">tapViewViaSelector:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">selector</span><span class="p">;</span>
</span><span class='line'><span class="k">@end</span>
</span><span class='line'>
</span><span class='line'><span class="k">@implementation</span> <span class="nc">EventsScreen</span>
</span><span class='line'>
</span><span class='line'><span class="o">+</span> <span class="p">(</span><span class="n">EventsScreen</span> <span class="o">*</span><span class="p">)</span> <span class="n">screen</span><span class="p">{</span>
</span><span class='line'>    <span class="n">EventsScreen</span> <span class="o">*</span><span class="n">screen</span> <span class="o">=</span> <span class="p">[[[</span><span class="n">EventsScreen</span> <span class="n">alloc</span><span class="p">]</span> <span class="n">init</span><span class="p">]</span> <span class="n">autorelease</span><span class="p">];</span>
</span><span class='line'>    <span class="p">[</span><span class="n">screen</span> <span class="n">visit</span><span class="p">];</span>
</span><span class='line'>    <span class="k">return</span> <span class="n">screen</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="n">visit</span><span class="p">{</span>
</span><span class='line'>    <span class="p">[</span><span class="n">self</span> <span class="nl">tapViewViaSelector:</span><span class="s">@&quot;view:&#39;UITabBarButton&#39; marked:&#39;Events&#39;&quot;</span><span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">BOOL</span><span class="p">)</span> <span class="n">currentlyOnCorrectTab</span><span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">[</span><span class="n">self</span> <span class="nl">viewViaSelector:</span><span class="s">@&quot;view:&#39;UITabBarButton&#39; marked:&#39;Events&#39; view:&#39;UITabBarSelectionIndicatorView&#39;&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="nb">nil</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="nl">selectEvent:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">eventName</span><span class="p">{</span>
</span><span class='line'>    <span class="n">NSString</span> <span class="o">*</span><span class="n">viewSelector</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSString</span> <span class="nl">stringWithFormat:</span><span class="s">@&quot;view:&#39;UIScrollView&#39; button marked:&#39;%@&#39;&quot;</span><span class="p">,</span><span class="n">eventName</span><span class="p">];</span>
</span><span class='line'>    <span class="p">[</span><span class="n">self</span> <span class="nl">tapViewViaSelector:</span><span class="n">viewSelector</span><span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="n">goBackToOverview</span><span class="p">{</span>
</span><span class='line'>    <span class="p">[</span><span class="n">self</span> <span class="nl">tapViewViaSelector:</span><span class="s">@&quot;view:&#39;UINavigationButton&#39; marked:&#39;Back&#39;&quot;</span><span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">BOOL</span><span class="p">)</span> <span class="n">currentlyViewingEventDetails</span><span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">[</span><span class="n">self</span> <span class="nl">viewViaSelector:</span><span class="s">@&quot;label marked:&#39;Key Facts&#39;&quot;</span><span class="p">]</span> <span class="o">&amp;&amp;</span> <span class="p">[</span><span class="n">self</span> <span class="nl">viewViaSelector:</span><span class="s">@&quot;label marked:&#39;The basics&#39;&quot;</span><span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">BOOL</span><span class="p">)</span> <span class="nl">currentlyViewingEventDetailsFor:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">eventName</span><span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">[</span><span class="n">self</span> <span class="n">currentlyViewingEventDetails</span><span class="p">]</span> <span class="o">&amp;&amp;</span> <span class="p">[</span><span class="n">self</span> <span class="nl">viewViaSelector:</span><span class="p">[</span><span class="n">NSString</span> <span class="nl">stringWithFormat:</span><span class="s">@&quot;label marked:&#39;%@&#39;&quot;</span><span class="p">,</span><span class="n">eventName</span><span class="p">]];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="cp">#pragma mark internals</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="n">NSArray</span> <span class="o">*</span><span class="p">)</span><span class="nl">viewsViaSelector:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">selector</span><span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">[[</span><span class="n">Shelley</span> <span class="nl">withSelectorString:</span><span class="n">selector</span><span class="p">]</span> <span class="nl">selectFrom:</span><span class="p">[[</span><span class="n">UIApplication</span> <span class="n">sharedApplication</span><span class="p">]</span> <span class="n">keyWindow</span><span class="p">]];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="n">UIView</span> <span class="o">*</span><span class="p">)</span><span class="nl">viewViaSelector:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">selector</span><span class="p">{</span>
</span><span class='line'>    <span class="n">NSArray</span> <span class="o">*</span><span class="n">views</span> <span class="o">=</span> <span class="p">[</span><span class="n">self</span> <span class="nl">viewsViaSelector:</span><span class="n">selector</span><span class="p">];</span>
</span><span class='line'>    <span class="k">if</span><span class="p">(</span> <span class="p">[</span><span class="n">views</span> <span class="n">count</span><span class="p">]</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">)</span>
</span><span class='line'>        <span class="k">return</span> <span class="nb">nil</span><span class="p">;</span>
</span><span class='line'>    <span class="k">else</span>
</span><span class='line'>        <span class="k">return</span> <span class="p">[</span><span class="n">views</span> <span class="nl">objectAtIndex:</span><span class="mi">0</span><span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="nl">tapViewViaSelector:</span><span class="p">(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="n">viewSelector</span><span class="p">{</span>
</span><span class='line'>    <span class="p">[</span><span class="n">UIAutomationBridge</span> <span class="nl">tapView:</span><span class="p">[</span><span class="n">self</span> <span class="nl">viewViaSelector:</span><span class="n">viewSelector</span><span class="p">]];</span>
</span><span class='line'>    <span class="n">sleepFor</span><span class="p">(</span><span class="mf">0.1</span><span class="p">);</span> <span class="c1">//ugh</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">@end</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, most of <code>EventsScreen</code> methods are only a line or two long. They generally either tap on a view or check that a view exists in the heirarchy. They use Shelley view selectors, which is a big part of keeping the code declarative and concise. There are also a few internal helper methods inside <code>EventsScreen</code> which would probably get moved out into a shared location pretty soon, maybe a <code>BaseScreen</code> class from which concrete Page Object classes could be derived.</p>

<h2>Proof of Concept satisfied</h2>

<p>And that&#8217;s pretty much all that was needed. There was the usual tedious XCode plumbing to get Kiwi and everything else working together, plus a few other bits and pieces, but really there wasn&#8217;t much to it.</p>

<p>A few people have asked to see all the moving parts of this experiment, so I&#8217;ve pushed the changes to <a href="https://github.com/moredip/2012-Olympics-iOS--iPad-and-iPhone--source-code/tree/kiwi-acceptance-mk1">this branch</a> on github.</p>

<h2>What else would you need?</h2>

<p>For any large test suite you&#8217;d want a lot more helpers. Based on my experience writing acceptance tests with Frank you usually need things like:</p>

<ul>
<li>wait for something to happen, with timeout</li>
<li>scroll things into view so you can interact with them</li>
<li>support for higher-level generic questions (is this view currently visible, is anything animating, etc).</li>
</ul>


<p>Eventually you&#8217;d probably also evolve a little internal DSL that lets you implement your Page Object classes in a more expressive way.</p>

<h2>What do you think?</h2>

<p>I&#8217;m very interested to see if this approach is appealing to people. If you&#8217;re interested - or even better if you take this and run with it - then please let me know.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cookie-based feature flag overrides]]></title>
    <link href="http://blog.thepete.net/blog/2012/11/06/cookie-based-feature-flag-overrides/"/>
    <updated>2012-11-06T18:55:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2012/11/06/cookie-based-feature-flag-overrides</id>
    <content type="html"><![CDATA[<h2>Introduction</h2>

<p>If you&#8217;re practicing Continuous Delivery then you&#8217;re probably using Feature Flags to hide half-baked features which are being shipped into production as latent code. It&#8217;s useful to allow individual users to <strong>manually override</strong> those feature flags so that they can get a preview of these latent features before they are released to everyone. People wanting to do this would be testers, product stakeholders, and external beta testers.</p>

<p>This is a similar concept to the Canary Releasing approach which organizations like Facebook use to trial new features. The difference is that with manual overrides each individual is opting in for features themselves, as opposed to being arbitrarily placed into the pool of users assigned as canaries.</p>

<h2>A lightweight flag override</h2>

<p>In the past I&#8217;ve blogged about <a href="http://blog.thepete.net/blog/2012/05/09/javascript-feature-flags/">manually setting feature flags using query strings</a>. On my current project we took an alternate approach using cookies instead. It was still a simple lightweight implementation, but rather than specifying an override using query params we instead used a permanent cookie.</p>

<p>General information about the current set of feature flags in play within our app is stored inside a per-environment configuration file which ships with the rest of our server-side code. This configuration file lists which feature flags are available, along with a brief description of the flag and a default state (on or off).</p>

<p>However in addition to that default server-side state we also allow flags to be overridden via a <code>feature_flags</code> cookie. This cookie is a simple JSON document describing which flags should be overridden. Any flag states listed in that cookie&#8217;s JSON payload will override the default state specified in the environment&#8217;s feature flag configuration.</p>

<h2>An example</h2>

<p>Let&#8217;s say our production environment&#8217;s feature flag config looks like this:</p>

<figure class='code'><figcaption><span>feature_flags.yaml</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='yaml'><span class='line'><span class="l-Scalar-Plain">enable_chat_feature</span><span class="p-Indicator">:</span>
</span><span class='line'>  <span class="l-Scalar-Plain">description</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Expose our new experimental chat interface (WIP)</span>
</span><span class='line'>  <span class="l-Scalar-Plain">default</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">false</span>
</span><span class='line'>
</span><span class='line'><span class="l-Scalar-Plain">use_new_email_service</span><span class="p-Indicator">:</span>
</span><span class='line'>  <span class="l-Scalar-Plain">description</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">Send registration emails using our new email service (still under pilot)</span>
</span><span class='line'>  <span class="l-Scalar-Plain">default</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">false</span>
</span></code></pre></td></tr></table></div></figure>


<p>By default anyone accessing our application will not see the new chat interface which we&#8217;re still working on because the default state for that feature is <em>off</em>. Likewise when someone signs up for a new account they will be sent welcome email using our old creaky email service, rather than the fancy new one that our buddies in a backend service team have been working on.</p>

<p>Now let&#8217;s say I&#8217;m a QA and I want to test whether that email service is ready for prime time. All I need to do is set my <code>feature_flags</code> cookie in my browser to something like:</p>

<figure class='code'><figcaption><span>feature_flags cookie</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="p">{</span>
</span><span class='line'> <span class="s2">&quot;use_new_email_service&quot;</span><span class="o">:</span> <span class="kc">true</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Once that cookie is set in my browser then whenever I register a new account using that browser then the application will notice the override, interpret the <code>use_new_email_service</code> feature as <em>on</em>, and send my welcome email using the new email service.</p>

<h2>Simple usability improvements</h2>

<p>Obviously it&#8217;s not ideal to have users manually editing raw JSON within a cookie. In our app we added a simple admin-restricted page for viewing and modifying these overrides. This page listed all known feature flags in the environment and allowed users to control which flags are being manually overridden via radio buttons with three states - On, Off, or Default. Changing those buttons simply modified which flag overrides were stored in the cookie JSON.</p>

<p>This page also highlighted stale overrides - flags which no longer existed in the environment but were still being &#8216;overridden&#8217; in the cookie. This is a fairly common occurance if you&#8217;re retiring your feature flags regularly (which you absolutely should be doing). These stale flags have no effect on the application; listing them is simply a way of prompting the user that the overrides are stale and should probably be removed.</p>

<h2>Limitations</h2>

<p>This approach is pretty simplistic and clearly there are some limitations. Firstly the overrides are stored client-side. That means you can&#8217;t restrict which flags are overriden, you can&#8217;t audit which flags are overridden, and you can&#8217;t go in as an administrator and modify the overrides. There are obviously also security concerns to be aware of when you&#8217;re allowing client-side state to impact what happens server-side.</p>

<p>Another issue is that the overrides are per-browser rather than per-login. That means that users have to explicitly configure the overrides for each browser (and mobile device) they access your app with, and remember to keep them in sync. You also need to remember that you&#8217;re setting the flags for all users that you log in as via that browser, not just the current user. This is probably counter to a lot of people&#8217;s intuition. However the fact that the overrides aren&#8217;t tied to a specific user can sometimes be helpful for testing - the registration email example above was actually a good example of that.</p>

<h2>Wrapping up</h2>

<p>All in all this is a nice simple approach to get started along the path of configurable feature flags. An organization that really embraces this idea will probably outgrow this basic implementation fairly quickly, but I belive it is a simple way to get started and show the value of feature overrides without a bunch of effort. If you&#8217;re using feature flagging but not using overrides currently then I encourage you to consider this approach too.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Frank with CocoaPods]]></title>
    <link href="http://blog.thepete.net/blog/2012/10/16/frank-with-cocoapods/"/>
    <updated>2012-10-16T16:38:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/10/16/frank-with-cocoapods</id>
    <content type="html"><![CDATA[<h2>A Frank field trip</h2>

<p>Today I&#8217;m visiting <a href="http://955dreams.com">955 Dreams</a> (the guys who make Band of the Day, amongst other things) visiting my friend (and their CTO) <a href="https://twitter.com/chris_stevenson">Chris</a>. We had a fun time figuring out how to get <a href="http://testingwithfrank.com">Frank</a> to play nicely with <a href="http://cocoapods.org/">CocoaPods</a>. It wasn&#8217;t that tricky, and I&#8217;m going to document what we found here to hopefully make it easier for other Cocoapod users.</p>

<h2>Problem the first</h2>

<p>Frank had trouble with cocoapods for two reasons. Firstly when frankifying the app we needed to frankify the app&#8217;s Xcode <em>project</em>, but to build the app we needed to point <code>frank build</code> at the main Xcode <em>workspace</em>, so that cocoapods could work its magic during the build. This was simply a case of passing the appropriate <code>--workspace</code> and <code>--scheme</code> arguments to <code>frank build</code>.</p>

<h2>Problem the second</h2>

<p>Cocoapods uses a Pods.xcconfig which overides the <code>OTHER_LDFLAGS</code> linker flag setting (amongst other things). Part of the work that <code>frank setup</code> does is to include some frank-specific settings in the project&#8217;s linker flags. Since cocoapods overrides <code>OTHER_LDFLAGS</code> the frank-specific additions are lost, meaning that the Frank server doesn&#8217;t get linked into the app. To fix this we created a seperate .xcconfig file that included both the cocaoapods and the frank .xcconfig files:</p>

<figure class='code'><figcaption><span>frank_and_pods.xcconfig</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="cp">#include &quot;Pods.xcconfig&quot;</span>
</span><span class='line'><span class="cp">#include &quot;Foo/Frank/frankify.xcconfig&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>However to get xcodebuild to use that file we had to abandon <code>frank build</code> (which is really just a thin wrapper around xcodebuild) and instead just invoke xcodebuild directly, passing in a <code>-xcconfig</code> argument. That worked and solved the problem but I think there&#8217;s an alternative approach that would let you still use <code>frank build</code>. Adding a <code>#include "../Pods.xcconfig"</code> line to the top of the frankify.xcconfig file should achieve the same ends.</p>

<h2>The happy ending</h2>

<p>Either way, after making those changes we were able to get a Frankfied app up and running and inspectable within Symbiote. I told Chris that I think long term it usually ends up being better to create a Frankified app in CI by creating a custom xcodebuild setup. We&#8217;ve established today what&#8217;s needed to do that with an app which uses Cocoapods.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Towards Frank 1.0]]></title>
    <link href="http://blog.thepete.net/blog/2012/09/06/towards-frank-1-point-0/"/>
    <updated>2012-09-06T18:44:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/09/06/towards-frank-1-point-0</id>
    <content type="html"><![CDATA[<p>One of the many geeky hats I wear is that of maintainer for <a href="http://www.testingwithfrank.com">Frank</a>, an open-source tool for automated testing of native iOS applications. Frank has been around for over 2 years now, which is actually quite a long time in the mobile space. It has evolved a fair amount in that time, but has had a surprisingly small amount of change to the core architecture. I&#8217;m actually quite proud of that. I think that the core concepts have been proven out enough that Frank is ready for a 1.0 release which cleans up some long-standing cruft and solidifies at least parts of its client/server API.</p>

<p>The main motivator for the Big One Oh is that I want to remove some old unmaintained libraries which Frank currently depends upon. This can be done in a <em>mostly</em> backwards-compatible way, but by doing this as part of a major version bump I can make some reasonably aggressive improvements without letting down existing users who would rightly expect backwards compatibility from a point release.</p>

<h2>Adios UISpec</h2>

<p>The main dependency I&#8217;d like to remove is <a href="http://code.google.com/p/uispec/">UISpec</a>. We have used it in the past for both view selection and for touch synthesis. At the time I started building Frank it was a great option, but it has since become unmaintained, and surpassed by other, newer tools.</p>

<p>About a year ago I wrote a new view selection engine called Shelley from scratch with the goal of replacing our use of UISpec, and a few months back we started using KIF for touch synthesis. So at this point new users of Frank aren&#8217;t really using UISpec for anything, and they&#8217;re benefiting from faster view selection, and more robust touch synthesis. However I kept UISpec around for backwards compatibility. With a 1.0 release I can finally cut the cord and fully remove UISpec.</p>

<p>A big issue that several users have had with UISpec is its GPL license. This license was necessarily inherited by the rest of our Frank server code, which made some users nervous, and prevented some folks from using Frank in a commercial setting. By removing UISpec fully from the Frank repo we no longer need to have a GPL license for any part of Frank, which should make people more comfortable. We&#8217;ll be moving to an Apache 2.0 license for the server parts of Frank, the same license which other Frank components have always had.</p>

<h2>Adios KIF</h2>

<p>The other big library dependency I&#8217;ll be leaving behind is <a href="http://github.com/square/KIF">KIF</a>. I really like KIF, and in general there aren&#8217;t many reasons to not use it. It&#8217;s a very nicely written library, and a good choice for Objective-C developers who are looking for a lower-level testing tool.</p>

<p>The motivation for leaving KIF is the opportunity to switch to using Apple&#8217;s own UIAutomation private framework. I recently opened up a library called <a href="http://github.com/TestingWithFrank/PublicAutomation">PublicAutomation</a> which exposes this private framework for use by tools like Frank, and I&#8217;m excited to be able to use the same super-solid touch-synthesis code that Apple themselves use.</p>

<p>As an example of why I&#8217;d like Frank to switch, it appears that with PublicAutomation you can simulate device rotation on a physical device without having to physically rotate the hardware, something which I believe was impossible before. It is also possible to extend PublicAutomation with whatever complex multi-touch gesture simulation your tests might need to perform. Finally, I can be confident that when Apple release new iOS SDKs they will do a lot of work to ensure that UIAutomation remains compatible and fully functional.</p>

<h2>Timeline</h2>

<p>I already have <a href="http://github.com/moredip/Frank/tree/onepointoh">a branch</a> of the Frank repo which contains the above changes, and it appears to be working well with the apps I&#8217;ve tested it on. I hope to release that soon (within the next couple of weeks) as a 1.0.pre1 version of the frank-cucumber gem. At that point I&#8217;ll be asking folks in the Frank community to try it out and give me feedback on what works and what doesn&#8217;t. I expect a few minor teething troubles with tests that use older, more obscure UISpec helper methods that Frank will have lost, but there shouldn&#8217;t be any issue that take more than a few lines of code to solve.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Introducing PublicAutomation]]></title>
    <link href="http://blog.thepete.net/blog/2012/08/20/introducing-publicautomation/"/>
    <updated>2012-08-20T07:37:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/08/20/introducing-publicautomation</id>
    <content type="html"><![CDATA[<p>I&#8217;m excited to announce <a href="http://github.com/TestingWithFrank/PublicAutomation">PublicAutomation</a>, <strong>a friendly wrapper around Apple&#8217;s private UIAutomation framework</strong>. PublicAutomation allows you to use Apple&#8217;s own private framework to simulate user interactions (taps, swipes, keyboard typing) via a simple Objective-C API.</p>

<p>Previous approaches to this problem have relied on reverse-engineering and monkey-patching iOS&#8217;s touch events system. PublicAutomation takes a different approach. It links in the low-level API of the private framework which Apple itself uses for its own UIAutomation tooling. PublicAutomation provides the stability of Apple&#8217;s proprietary UIAutomation tool with the flexibility of an open source library maintained by the community.</p>

<p>I have already had great success in my experiments using PublicAutomation as the user-simulation backend for <a href="http://testingwithfrank.com">Frank</a> (the automated acceptance testing tool I maintain), replacing our previous dependency on <a href="http://github.com/square/KIF">KIF</a>. KIF is a great tool but Frank was only using it for its user-simulation features, which was always a bit of a weird fit. I&#8217;m confident we can now replace our KIF dependency with a smaller more focused user-simulation library in the form of PublicAutomation.</p>

<h2>Some history</h2>

<p>As I said above, Frank currently uses KIF to do the low-level work of simulating user interactions. KIF achieves this with some clever monkey-patching of iOS&#8217;s event system. This works remarkably well, but there are some issues with simulating certain interactions (e.g. tapping a deletion confirmation button in a table view cell). It also has some strange side-effects at times - an app which has KIF linked in doesn&#8217;t react to tap events from an actual user in the same way.</p>

<p>Recently I spent a bit of time investigating the feasibility of using Apple&#8217;s private UIAutomation framework outside of their official UIAutomation tooling. I blogged about that initial research <a href="http://blog.thepete.net/blog/2012/07/11/using-the-uiautomation-private-framework">in a previous post</a>. The findings were both good and bad. The good news was that the private framework <strong>can</strong> be linked in and used both in the simulator and on the device. The bad news was that only the low-level <code>UIASyntheticEvents</code> API works reliably. The high-level API that UIAutomation exposes via JavaScript does not appear to be usable programatically.</p>

<p>My goal in investigating the UIAutomation private framework was to replace KIF&#8217;s event monkey-patching. I&#8217;d also hoped to get some nice new high-level API (e.g. send a flick to this view), but that was really more of a nice-to-have than an absolute requirement. The main outcome of this research is the discovery that we can expose and use the UIAutomation private framework&#8217;s low level API.</p>

<h2>Bringing in KIF&#8217;s keyboard typing</h2>

<p>It turns out that this low level <code>UIASyntheticEvents</code> API has a drop-in replacement for almost every feature of KIF we use in Frank. The only thing missing was keyboard typing. I extracting KIF&#8217;s keyboard typing code into a separate class inside of KIF and sent them a <a href="https://github.com/square/KIF/pull/141">pull request</a>. Then I took that <code>KIFTypist</code> class and ported it into PublicAutomation. At this point PublicAutomation has everything Frank needs. It also appears to not have the issues we&#8217;ve seen when monkey-patching the event system. For example we can now tap on deletion confirmation buttons.</p>

<h2>The future</h2>

<p>I&#8217;m working on solidifying Frank&#8217;s usage of PublicAutomation. There will probably be an official switch over to using it as part of a 1.0 release of Frank (along with removing our UISpec dependency, but that&#8217;s a different story).</p>

<p>I&#8217;m also hoping that other non-UIAutomation tools can take advantage of it - <a href="https://github.com/calabash/calabash-ios">Calabash</a> for example. My hope is that PublicAutomation can become a standard shared library for user simulation in iOS. To achieve that it does need some extra work. Right now it only supports single-finger taps and swipes. Extending support to more complex multi-touch gestures should be trivial.</p>

<p>It should also be trivial to add support for features which have previously not been easily accessible to non-UIAutomation tools. For example simulating the home button being pressed, the screen being locked, etc. As far as I can tell <a href="https://github.com/TestingWithFrank/PublicAutomation/blob/master/PublicAutomation/UIAutomation.h#L937">everything exposed by UIASyntheticEvents class</a> is up for grabs. An exciting prospect!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[marker branches in git]]></title>
    <link href="http://blog.thepete.net/blog/2012/08/09/marker-branches-in-git/"/>
    <updated>2012-08-09T21:40:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/08/09/marker-branches-in-git</id>
    <content type="html"><![CDATA[<p>In my <a href="http://blog.thepete.net/blog/2012/08/02/octopress-deployment-pipeline/">last post</a> I talked about setting up a basic deployment pipeline using marker branches in git to keep track of what was where.</p>

<p>In this post I want to go into a little more detail describing how these marker branches work. To do that I&#8217;ll walk through a simple example showing the state of a git repo as code moves through being committed, being pushed to master, deployed to pre-prod, and finally promoted to prod.</p>

<h2>A sample git branch progression</h2>

<p>In these diagrams the rounded boxes are git commits, the rectangles are git branches. The &#8216;WD&#8217; rounded box represents uncommitted local changes in the current working directory.</p>

<p>Many thanks to Scott Chacon, git teacher extrodinaire, who very generously <a href="https://github.com/schacon/git-presentations/">shares an omnigraffle file</a> containing all the really nice git diagrams he uses in his books and presentations. I&#8217;ve shamelessly used that as the basis of these diagrams.</p>

<figure class="diagram">
  <img src="http://blog.thepete.net/images/post_images/octopress_cd/0.png">
  <figcaption>
    starting state
  </figcaption>
</figure>


<p>At the start of this scenario we have our master branch pointing at the <em>C5</em> commit. We also have a couple of <strong>marker branches</strong>, <em>pre-prod</em> and <em>prod</em>. We&#8217;ll talk more about these guys momentarily. Finally we have some local code changes inside our working directory. These are the changes which we are going to be following as the travel their <strong>path to production</strong>.</p>

<figure class="diagram">
  <img src="http://blog.thepete.net/images/post_images/octopress_cd/1.png">
  <figcaption>
  changes checked in
  </figcaption>
</figure>


<p>In this next diagram you can see I&#8217;ve now checked in the local changes I had in my working directory to my <em>master</em> branch as <em>C6</em>. <em>master</em> is now pointing to the newly created <em>C6</em> commit but nothing else has changed.</p>

<h2>A release candidate is born</h2>

<p>At this point I run some acceptance tests, and decide that what I currently have in master is a viable <strong>release candidate</strong>. I want to push it to <em>pre-prod</em> to start more exhaustive testing of this candidate.</p>

<p>To do that I run a deployment script which pushes the code revision which <em>master</em> is currently pointing to into the pre-prod environment. If the deployment succeeds the script will also update the <em>pre-prod</em> marker branch to point to the code revision which is now deployed to pre-prod. That&#8217;s the essence of the marker branch concept. It&#8217;s a way to indicate which revision of the codebase is in which environment.</p>

<figure class="diagram">
  <img src="http://blog.thepete.net/images/post_images/octopress_cd/2.png">
  <figcaption>
    after deploying to pre-prod
  </figcaption>
</figure>


<p>Here&#8217;s what our git repo looks like after that deploy to pre-prod. The <em>pre-prod</em> branch has been updated to point to <em>C6</em>, since that&#8217;s the commit which my script just successfully deployed to the pre-prod environment. <em>Master</em> also continues to point to <em>C6</em>, because there haven&#8217;t been any other checkins to <em>master</em> since I decided to deploy to pre-prod.</p>

<h2>Pre-prod signoff</h2>

<p>Now I will do some more exhaustive testing in my pre-prod environment. Probably some exploratory QA testing, and probably some sign-off with my product and design friends as well. Note that there&#8217;s a very easy way to see exactly what is in pre-prod that has changed since our last release to prod. We have a <em>prod</em> marker branch which indicates which code revision is currently in production, and a <em>pre-prod</em> marker branch which shows what code revision the current pre-prod release candidate is from. If anyone needs to know exactly what changes are involved in this release candidate we can use standard git diffing and logging tools to find out.</p>

<h2>Release candidates don&#8217;t stop other work</h2>

<p>While we&#8217;re verifying our release candidate other development work can continue to happen, with more commits to master.</p>

<figure class="diagram">
  <img src="http://blog.thepete.net/images/post_images/octopress_cd/3.png">
  <figcaption>
  meanwhile, work continues&#8230;
  </figcaption>
</figure>


<p>Here we see that the <em>master</em> branch has continued to move forward with new commits <em>C7</em> and <em>C8</em>. I included this in the scenario to highlight the benefits of the <em>pre-prod</em> marker branch. We don&#8217;t have to stop forward development while we verify that a specific code revision is good for release. We also don&#8217;t need to create a true branch in the repo. We simply use a marker branch to make a note of what revision is currently in pre-prod while allowing unrelated development to move forward.</p>

<h2>Promote to production</h2>

<p>At this point our friends in QA and Product have given us a happy thumbs up and agreed that what&#8217;s in pre-prod is ready for release to production. We&#8217;ll now run a deployment script which takes the code revision pointed to by the <em>pre-prod</em> marker branch and <strong>promotes</strong> (i.e. re-deploys) that code revision to the production environment.</p>

<figure class="diagram">
  <img src="http://blog.thepete.net/images/post_images/octopress_cd/4.png">
  <figcaption>
  released to production
  </figcaption>
</figure>


<p>Here&#8217;s the state of the git repo after a successful promotion from pre-prod to prod. After some smoke tests against the production environment have passed the script updates the <em>prod</em> marker branch to reflect the new reality - the current code in production is the code at commit 6 in the repo.</p>

<h2>Conclusion</h2>

<p>I&#8217;ve shown how marker branches can act as a simple way to track which version of your application is live in which environment. I&#8217;ve also shown that you can use marker branches to enforce lightweight process constraints - for example you can&#8217;t deploy an arbitrary code revision to prod, it has to be the code revision that&#8217;s currently in pre-prod.</p>

<p>Marker branches are not a substitute for a real grown-up build pipeline with build artifacts and an associated artifact repository. However for a really simple system (e.g. deploying a blog) marker branches can make sense.</p>

<p>The lightweight constraints can also potentially work as a way to manage how code changes enter CI when working in a large team of developers. For example you could only allow developers to check in code on top of a <em>passed&#8211;ci-smoke</em> marker branch. This would prevent a developer from accidentally checking in on top of code which has not yet gone through a CI smoke test.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Octopress deployment pipeline]]></title>
    <link href="http://blog.thepete.net/blog/2012/08/02/octopress-deployment-pipeline/"/>
    <updated>2012-08-02T08:15:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/08/02/octopress-deployment-pipeline</id>
    <content type="html"><![CDATA[<p>I spent a fun evening recently setting up a deployment pipeline for this blog. I&#8217;d like to share some details on what I set up and why.</p>

<p>The motivation was that I wanted some way to publish draft blog entries for other people to review, but I didn&#8217;t want these drafts to show up on my public site.  I played with Octopress&#8217;s <code>published: false</code> option, but it really didn&#8217;t give me what I needed. Then I saw someone commenting that the ideal would be to have a preview version of the entire site available at a separate url. A <strong>pre-production environment</strong>, essentially. Hmm, I thought. Every web project I work on has one of these. It&#8217;s used to showcase the version of the system which is going to be released to production. That&#8217;s what I need - why don&#8217;t I just set that up for my blog?</p>

<h2>Delivery pipelines</h2>

<p>When using a pre-prod environment to showcase it&#8217;s important that what goes to prod is exactly what was showcased on pre-prod. A delivery pipeline helps ensure that. You could think of it as Continuous Integration on steroids. Every time code is committed it is built, unit tested, and then packaged into a <strong>build artifact</strong>. That build artifact (or just &#8216;build&#8217;) then moves through a <strong>pipeline</strong> which potentially ends in production. The build is often initially deployed to a dev/integration environment. Assuming it passes muster it may then be <strong>promoted</strong> to a QA environment, and perhaps then promoted again to pre-prod. Promoting a build means deploying it to the next environment in the pipeline. Finally that build may go through some sort of manual sign-off process in pre-prod and then finally be promoted to production.</p>

<p>The key principle here is that of a well-defined build artifact which is moving through these different environments. Jez Humble talks about this pipeline as a sort of obstacle course, where you gain confidence in the quality of the build artifact as it moves through your pipeline, passing stricter and stricter quality hurdles at each stage. This delivery pipeline is a core part of a Continuous Delivery system.</p>

<h2>CD for a blog?! Srsly?</h2>

<p>Now clearly what I&#8217;ve just described is a little bit over the top for this lowly blog. I realize that. But setting up a sort of lightweight pipeline was a fun and surprisingly useful project. It helped clarify some CD concepts for me (the best learning is by doing) and I do actually use the pipeline. In fact I made use of it while writing this very post!</p>

<h2>Pre-production environment</h2>

<p>This blog is powered by <a href="http://octopress.org/">Octopress</a>, and it&#8217;s published as a set of static files which are hosted by Amazon&#8217;s S3 service. Happily this means that creating a &#8216;pre-prod environment&#8217; was as simple as creating a new S3 bucket and wiring it up to a subdomain via a CNAME entry.</p>

<h2>The approach</h2>

<p>I didn&#8217;t want to go <em>too</em> overboard, so rather than tracking a physical build artifact I opted to instead pass around git commits as my &#8216;artifact&#8217;. Now this is actually a <strong>bad</strong> idea to do in a real CD system. You have to repeatedly re-build and re-package your code at each stage in the pipeline, and you risk differences in how that build process occurs during at those different stages. That said, for my purposes just tracking commits in version control will work well enough.</p>

<p>My goal was to be able to deploy from any git commit to my pre-prod environment using a simple script. I&#8217;d then be able to &#8216;showcase&#8217; my changes by pointing my browser at the pre-prod site. Assuming everything passes muster I could then run another script to promote whatever is in pre-prod to prod. Note that I allowed <strong>no way</strong> for me to deploy an arbitrary (and thus un-verified) commit to production. Anything I want to push to prod has to move through my pre-prod environment first.</p>

<h2>Tracking what&#8217;s where</h2>

<p>I track what is in pre-prod and prod using git marker branches. After successfully deploying a commit to an environment the corresponding marker branch is updated to point to that commit. That way my scripts can always know which commit is deployed to each environment just by checking with git.</p>

<p>For concrete details on how I do the git branch manipulation you can take a look at the <a href="https://github.com/moredip/blog.thepete.net/blob/fea96051bf4dbaaf46b1d5ef203353edbf7ef36b/scripts/push_preprod">push_preprod</a> and <a href="https://github.com/moredip/blog.thepete.net/blob/fea96051bf4dbaaf46b1d5ef203353edbf7ef36b/scripts/promote_preprod_to_prod">promote_preprod_to_prod</a> scripts themselves.</p>

<h2>Deploying a commit</h2>

<p>The steps I use to deploy an arbitrary commit of an octopress blog to S3 are:</p>

<ul>
<li>extract a snapshot of that commit to a temporary directory using <code>git archive</code></li>
<li>run the rake task which compiles the Octopress source into the static site files</li>
<li>push the static files up to an S3 bucket using <code>s3cmd</code></li>
</ul>


<p>I encapsulated this in a Deployer class which is bundled with my blog&#8217;s source <a href="https://github.com/moredip/blog.thepete.net/blob/fea96051bf4dbaaf46b1d5ef203353edbf7ef36b/scripts/deployer.rb">here</a>.</p>

<h2>Done</h2>

<p>That&#8217;s pretty much it. It&#8217;s a simple lightweight system that give me just enough release management with very little overhead. I am able to deploy any arbitrary version of my blog to a pre-prod environment which is basically an exact replica of prod. I can then promote what&#8217;s in pre-prod to prod with a single command. I was pleasantly surprised at how easy this was to accomplish. It&#8217;s literally just an evening&#8217;s work to set up a simple delivery pipeline.</p>

<h2>TODO</h2>

<p>Ideally I&#8217;d like to have my pre-prod environment use a slightly different Octopress configuration than my prod environment. For example I&#8217;d like to turn off disqus commenting in pre-prod since I don&#8217;t want peoples comments to be lost.  I&#8217;d also like to add a little banner so people know they&#8217;re viewing a preview copy of my blog.  I&#8217;m not quite sure at the moment on the best way to approach this, so I&#8217;m leaving it be for now.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Running Frank as part of iOS CI]]></title>
    <link href="http://blog.thepete.net/blog/2012/07/22/running-frank-as-part-of-ios-ci/"/>
    <updated>2012-07-22T09:44:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/07/22/running-frank-as-part-of-ios-ci</id>
    <content type="html"><![CDATA[<p><a href="http://testingwithfrank.com">Frank</a> is a tool that allows you to run automated acceptance tests against your native iOS application. A major reason for creating <em>automated</em> acceptance tests is so that you can run them as part of your <a href="http://martinfowler.com/articles/continuousIntegration.html">Continuous Integration</a> (CI) process. Doing this enables a rapid feedback loop where a developer checking in code is informed very quickly if that change caused a defect in your app.</p>

<p>In this post I&#8217;ll show how to configure a basic CI setup using <a href="http://jenkinsci.org">Jenkins</a> which will build your app and run Frank tests against it every time you check in code. CI for iOS projects don&#8217;t seem to be a common practice. This is a shame because the CI can bring just as many benefits for iOS applications as for other technologies. I suspect part of the reason CI is less popular is that Apple doesn&#8217;t make it particularly easy. It&#8217;s not a trivial task to automate things like building your application and running unit tests. Things are moving in the right direction though, with both Apple and open-source developers making it simpler to integrate a dev toolchain into a CI setup.</p>

<h2>Our plan of attack</h2>

<p>I needed a simple app to demonstrate a CI setup. I&#8217;ll be using the same <a href="https://github.com/Frahaan/2012-Olympics-iOS--iPad-and-iPhone--source-code">open source &#8216;2012 Olympics&#8217; app</a> that I&#8217;ve used as a pedagogical example in previous posts. To keep the CI setup distinct from the application I created a small <a href="https://github.com/moredip/iOS-CI">master repo</a> which contains just the CI setup for the Olympics app, along with including the app source code via a git submodule. I&#8217;ve also had to <a href="https://github.com/moredip/2012-Olympics-iOS--iPad-and-iPhone--source-code">fork the Olympics app</a> because I needed to set it up for Frank testing, as well as make small changes to the app&#8217;s project settings which allow CI to be easily set up. When setting up your own app for CI you&#8217;d likely already have these changes in place.</p>

<p>So, let&#8217;s walk through what&#8217;s involved in getting a basic CI set up for our iOS application. Our overall strategy will be:</p>

<ul>
<li>set up a build script which can build our app from the command line</li>
<li>set up CI so that we can run that build whenever we check in code</li>
<li>add Frank testing to our build script</li>
<li>set up CI to enable Frank tests</li>
</ul>


<p>Let&#8217;s get started by creating a build script.</p>

<h2>Scripting the build</h2>

<p>Before we start setting up CI itself we need to automate the build process. This will involve stepping outside the safe environs of XCode and entering the powerful and intimidating world of the command line. Have no fear, it&#8217;s not as scary as it sounds.</p>

<p>We&#8217;re going to use a ruby tool called <strong>Rake</strong> to create our build script. Rake is similar to tools like Make and Ant - it makes it easy for us to succinctly express the different tasks we want our build script to perform, and allows us to chain those tasks together. We&#8217;ll also be using a ruby gem called <strong>xcodebuild-rb</strong> from Luke Redpath (one of the most industrious open-source developers I know of). This gem makes it trivially easy to drive xcodebuild (the command line interface for XCode) from inside a Rake file.</p>

<p>Before we get started on the build script itself we need to create a <strong>Gemfile</strong> which declares our ruby dependencies. This file can be used by another tool called <a href="http://gembundler.com/">Bundler</a> to ensure that developer machines and CI systems have everything they need.</p>

<figure class='code'><figcaption><span>Gemfile</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">source</span> <span class="s2">&quot;https://rubygems.org&quot;</span>
</span><span class='line'>
</span><span class='line'><span class="n">gem</span> <span class="s2">&quot;rake&quot;</span>
</span><span class='line'><span class="n">gem</span> <span class="s2">&quot;xcodebuild-rb&quot;</span><span class="p">,</span> <span class="s2">&quot;~&gt; 0.3.0&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Those are all the dependencies we have for now. If you run <code>bundle install</code> bundler should now set up those gems. Next we&#8217;ll create our initial Rakefile - the file which defines our app&#8217;s build tasks:</p>

<figure class='code'><figcaption><span>Rakefile</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="nb">require</span> <span class="s1">&#39;rubygems&#39;</span>
</span><span class='line'><span class="nb">require</span> <span class="s1">&#39;xcodebuild&#39;</span>
</span><span class='line'>
</span><span class='line'><span class="n">namespace</span> <span class="ss">:xcode</span> <span class="k">do</span>
</span><span class='line'>  <span class="no">XcodeBuild</span><span class="o">::</span><span class="no">Tasks</span><span class="o">::</span><span class="no">BuildTask</span><span class="o">.</span><span class="n">new</span> <span class="ss">:debug_simulator</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
</span><span class='line'>    <span class="n">t</span><span class="o">.</span><span class="n">invoke_from_within</span> <span class="o">=</span> <span class="s1">&#39;./app&#39;</span>
</span><span class='line'>    <span class="n">t</span><span class="o">.</span><span class="n">configuration</span> <span class="o">=</span> <span class="s2">&quot;Debug&quot;</span>
</span><span class='line'>    <span class="n">t</span><span class="o">.</span><span class="n">sdk</span> <span class="o">=</span> <span class="s2">&quot;iphonesimulator&quot;</span>
</span><span class='line'>    <span class="n">t</span><span class="o">.</span><span class="n">formatter</span> <span class="o">=</span> <span class="no">XcodeBuild</span><span class="o">::</span><span class="no">Formatters</span><span class="o">::</span><span class="no">ProgressFormatter</span><span class="o">.</span><span class="n">new</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="n">task</span> <span class="ss">:default</span> <span class="o">=&gt;</span> <span class="o">[</span><span class="s2">&quot;xcode:debug_simulator:cleanbuild&quot;</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>This Rakefile does a few things. First it loads the libraries we need. Then it defines an <code>xcode</code> namespace (a namespace is just a way of logically grouping a set of tasks). Inside that xcode namespace it uses an xcodebuild-rb helper to create a set of Rake tasks for automating a debug iphone simulator build of the project contained inside the <code>app</code> directory. Finally a <code>default</code> task is defined. This task doesn&#8217;t do anything itself, but declares a dependency on the <code>xcode:debug_simulator:cleanbuild</code> task. That means that whenever the default task is run it will run that dependent task, causing a clean build of the debug simulator version of the app to be generated.</p>

<p>If you were to try that out now by running <code>rake</code> from the command line you should see xcodebuild creating a clean build of the app. You could also run <code>rake -T</code> to get a list of all interesting rake tasks. If you did so you&#8217;d notice that xcodebuild-rb has created a few different Rake tasks, not just for building the app but also tasks for cleaning build output and archiving the build. For the purposes of this blog post we&#8217;ll just be using the cleanbuild task.</p>

<p>At this point we have an automated way to generate a clean build of the application. Now we want to make sure that our build script leaves that built application in a common &#8216;artifact&#8217; directory so that our CI system can archive it. There&#8217;s no point building the app if you don&#8217;t save it for use later on. I&#8217;ll follow a convention of putting everything which I want my CI system to save inside a &#8216;ci_artifact&#8217; directory. I add the following to my Rakefile:</p>

<figure class='code'><figcaption><span>Rakefile additions</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">namespace</span> <span class="ss">:ci</span> <span class="k">do</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">move_into_artifacts</span><span class="p">(</span> <span class="n">src</span> <span class="p">)</span>
</span><span class='line'>    <span class="no">FileUtils</span><span class="o">.</span><span class="n">mkdir_p</span><span class="p">(</span> <span class="s1">&#39;ci_artifacts&#39;</span> <span class="p">)</span>
</span><span class='line'>    <span class="no">FileUtils</span><span class="o">.</span><span class="n">mv</span><span class="p">(</span> <span class="n">src</span><span class="p">,</span> <span class="s2">&quot;ci_artifacts/&quot;</span> <span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">task</span> <span class="ss">:clear_artifacts</span> <span class="k">do</span>
</span><span class='line'>    <span class="no">FileUtils</span><span class="o">.</span><span class="n">rm_rf</span><span class="p">(</span> <span class="s1">&#39;ci_artifacts&#39;</span> <span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">task</span> <span class="ss">:build</span> <span class="o">=&gt;</span> <span class="o">[</span><span class="s2">&quot;xcode:debug_simulator:cleanbuild&quot;</span><span class="o">]</span> <span class="k">do</span>
</span><span class='line'>    <span class="n">move_into_artifacts</span><span class="p">(</span> <span class="no">Dir</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s2">&quot;app/build/Debug-iphonesimulator/*.app&quot;</span><span class="p">)</span> <span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="n">task</span> <span class="ss">:ci</span> <span class="o">=&gt;</span> <span class="o">[</span><span class="s2">&quot;ci:clear_artifacts&quot;</span><span class="p">,</span><span class="s2">&quot;ci:build&quot;</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here I&#8217;ve created a <code>ci</code> namespace. Inside that I&#8217;ve added a <code>clear_artifacts</code> task and a <code>build</code> task. In addition I&#8217;ve also created a <code>ci</code> <em>task</em> in the root namespace. That task depends on the <code>clear_artifacts</code> and <code>build</code> tasks, meaning that whenever I run <code>rake ci</code> Rake will run <code>ci:clear_artifacts</code> and then <code>ci:build</code>.</p>

<p><code>ci:clear_artifacts</code> simply deletes any existing ci_artifact directory. <code>ci:build</code> depends on the existing xcode build task to actually create a build of the app, and then it copies the built app into the ci_artifacts directory, creating the directory if necessary. I didn&#8217;t want to hard-code the app name into my Rakefile so I cheated a bit and used a glob to select any directory with a .app extension.</p>

<p>If I now run <code>rake ci</code> I should end up with a freshly-built copy of the application in a ci_artifacts directory.</p>

<h2>Setting up Jenkins</h2>

<p>Now we have an automated build script we need to get our CI system set up. I&#8217;m going to use Jenkins in this post because it&#8217;s probably the most commonly used CI server. Pretty much the exact same approach would be used for other tools such as <a href="http://www.jetbrains.com/teamcity/">TeamCity</a> or <a href="http://www.thoughtworks-studios.com/go-agile-release-management">Go</a>.</p>

<p>I installed a sandbox copy of Jenkins on my laptop with a simple <code>brew install jenkins</code>, courtesy of <a href="http://mxcl.github.com/homebrew/">homebrew</a>. If you&#8217;re a developer using a mac then I highly recommend homebrew. I followed the instructions provided with the homebrew recipe to launch the Jenkins server and then went to <a href="http://localhost:8080/">http://localhost:8080/</a>.</p>

<p>In the Jenkins UI I created a new &#8216;free-style&#8217; job and configured it to point to my main git repo. Next I needed to tell Jenkins how to build our app. A good practice is to keep as much of your configuration as possible inside version control. As part of that I usually create a simple CI script inside the root directory of my app, and then have the CI system call that script. In this example that script is called <code>go.sh</code> and lives in the root of my main repo, under source control like everything else. The only thing I need to configure in Jenkins itself is a single line &#8216;Execute Shell&#8217; build step which calls go.sh. Another nice benefit of this approach is that you can test tweaks you&#8217;re making to your CI setup by calling <code>./go.sh</code> directly on your dev box, rather than having to kick off a new CI build.</p>

<p>Here&#8217;s what my initial go.sh looks like:</p>

<figure class='code'><figcaption><span>go.sh</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'><span class="c">#!/bin/sh</span>
</span><span class='line'>bundle install --deployment
</span><span class='line'>bundle <span class="nb">exec </span>rake ci
</span></code></pre></td></tr></table></div></figure>


<p>Pretty simple. It uses bundler to make sure all my ruby dependencies are installed and then runs the <code>ci</code> rake task.</p>

<p>The last thing I need to do is tell Jenkins to archive all the artifacts it finds inside the ci_artifacts directory by checking the &#8216;Archive the artifacts&#8217; checkbox and then specifying <code>ci_artifacts/**/*</code> as the files to archive.</p>

<p>That&#8217;s it, we&#8217;re done with our Jenkins set up. If all has been done correctly when you kick off that Jenkins job it should build the app and save the resulting <code>2012 Olympics.app</code> inside Jenkin&#8217;s <em>Build Artifacts</em> for that build.</p>

<h2>Setting up Frank tests</h2>

<p>We now have a very basic CI setup for our iOS app. Next I&#8217;ll describe how to integrate Frank into this CI system. I&#8217;m going to assume that your app itself has already been set up for Frank. If not, check out <a href="http://blog.thepete.net/blog/2012/06/24/writing-your-first-frank-test/">a previous post of mine</a> for all the details. It&#8217;s a painless process.</p>

<p>First we need to declare our dependency on the frank-cucumber gem which we&#8217;ll use to actually run our Frank tests. We do that by updating our Gemfile:</p>

<figure class='code'><figcaption><span>Gemfile</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">source</span> <span class="s2">&quot;https://rubygems.org&quot;</span>
</span><span class='line'>
</span><span class='line'><span class="n">gem</span> <span class="s2">&quot;rake&quot;</span>
</span><span class='line'><span class="n">gem</span> <span class="s2">&quot;xcodebuild-rb&quot;</span><span class="p">,</span> <span class="s2">&quot;~&gt; 0.3.0&quot;</span>
</span><span class='line'>
</span><span class='line'><span class="n">gem</span> <span class="s2">&quot;frank-cucumber&quot;</span><span class="p">,</span> <span class="s2">&quot;~&gt; 0.9.4&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The next step is to create a Rake task which will generate a Frankified build of your app. I&#8217;ll add that to the ci namespace in my Rakefile as follows:</p>

<figure class='code'><figcaption><span>Rakefile additions</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">namespace</span> <span class="ss">:ci</span> <span class="k">do</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># ... existing ci tasks don&#39;t change </span>
</span><span class='line'>
</span><span class='line'>  <span class="n">task</span> <span class="ss">:frank_build</span> <span class="k">do</span>
</span><span class='line'>    <span class="n">sh</span> <span class="s1">&#39;(cd app &amp;&amp; frank build)&#39;</span>
</span><span class='line'>    <span class="n">move_into_artifacts</span><span class="p">(</span> <span class="s2">&quot;app/Frank/frankified_build/Frankified.app&quot;</span> <span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>This task shells out to the <code>frank build</code> command, and then copies the app bundle that it builds into our ci_artifacts directory.</p>

<p>Now that we have a Frankified build we want to run frank tests against it. Our Frank tests have been written using <a href="http://cukes.info">Cucumber</a>, which happily comes with great Rake integration. We just need to use that to create a rake task which runs our cucumber features against our Frankified build:</p>

<figure class='code'><figcaption><span>Rakefile additions</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="c1"># ... near the top of our Rakefile</span>
</span><span class='line'><span class="nb">require</span> <span class="s1">&#39;cucumber/rake/task&#39;</span>
</span><span class='line'>
</span><span class='line'><span class="no">HERE</span> <span class="o">=</span> <span class="no">File</span><span class="o">.</span><span class="n">expand_path</span><span class="p">(</span> <span class="s1">&#39;..&#39;</span><span class="p">,</span><span class="bp">__FILE__</span> <span class="p">)</span>
</span><span class='line'><span class="no">ENV</span><span class="o">[</span><span class="s1">&#39;APP_BUNDLE_PATH&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="no">File</span><span class="o">.</span><span class="n">join</span><span class="p">(</span> <span class="no">HERE</span><span class="p">,</span> <span class="s1">&#39;ci_artifacts/Frankified.app&#39;</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="c1"># ... existing Rakefile code still here</span>
</span><span class='line'>
</span><span class='line'><span class="n">namespace</span> <span class="ss">:ci</span> <span class="k">do</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># ... existing ci namespace code here</span>
</span><span class='line'>
</span><span class='line'>  <span class="no">Cucumber</span><span class="o">::</span><span class="no">Rake</span><span class="o">::</span><span class="no">Task</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="ss">:frank_test</span><span class="p">,</span> <span class="s1">&#39;Run Frank acceptance tests, generating HTML report as a CI artifact&#39;</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
</span><span class='line'>    <span class="n">t</span><span class="o">.</span><span class="n">cucumber_opts</span> <span class="o">=</span> <span class="s2">&quot;app/Frank/features --format pretty --format html --out ci_artifacts/frank_results.html&quot;</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="c1"># ... redefine our ci task here</span>
</span><span class='line'><span class="n">task</span> <span class="ss">:ci</span> <span class="o">=&gt;</span> <span class="o">[</span><span class="s2">&quot;ci:clear_artifacts&quot;</span><span class="p">,</span><span class="s2">&quot;ci:build&quot;</span><span class="p">,</span><span class="s2">&quot;ci:frank_build&quot;</span><span class="p">,</span><span class="s2">&quot;ci:frank_test&quot;</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>There are a few things going on here. We require in Cucumber&#8217;s rake helper code. Next we set the <code>APP_BUNDLE_PATH</code> environment variable to point to the location of the Frankified build inside our ci_artifacts directory. Frank uses that environment variable to know which app to launch in the simulator at the start of your Frank tests. We then use a Cucumber helper to generate a rake task called <code>ci:frank_test</code>. We configure that task to run the Cucumber tests inside <code>app/Frank/features</code>. We also ask Cucumber to generate a nice HTML test report for each test run, saving it into the ci_artifacts directory so that it can be accessed by the CI system. Finally we extend our main <code>ci</code> task to depend on those new tasks.</p>

<p>This means that when you run the <code>rake ci</code> command rake will now generate a Frankified build and then run tests against it, in addition to generating the debug simulator build as it did previously.  So if you ran <code>./go.sh</code> at this point to simulate a full CI run you would see a debug build of your app generated, followed by a frankified build, and finally a Frank test run would run. You&#8217;d also see the Frankified app plus a nice HTML test run report in the ci_artifacts directory. We&#8217;re almost done!</p>

<h2>Launching apps in the Simulator from a CI build</h2>

<p>However, there&#8217;s one final hurdle. If you now kicked off a Jenkins run you&#8217;d likely see the Frank tests fail to launch your app, even though Jenkins is using the exact same go.sh script we just ran successfully by hand. Not good.</p>

<p>The reason for this is a bit subtle. Apple doesn&#8217;t provide an offical way to automate launching an app in the simulator, so Frank uses an open source tool called SimLauncher which reverse-engineers the way XCode launches apps. However this approach appears to only work if the process launching the app is attached to the OS X windowing system. In the case of Jenkins the process running a CI build is not always attached to the windowing system. To work around this fact SimLauncher has a client-server mode. You launch a SimLauncher server on your CI build box by hand so that it is attached to the windowing system. You then tell Frank to use SimLauncher in client-server mode when running CI. Frank will now ask that SimLauncher server to launch the app, rather than trying to launch it directly. Because the SimLauncher server process is attached to the windowing system it is able to launch the simulator even though the CI process itself isn&#8217;t attached.</p>

<p>That was a rather complex sidebar, but fortunately the actual setup is straight forward. First open a new terminal window and run the <code>simlauncher</code> command. That will start up a simlauncher server in your terminal.</p>

<p>Next, update your go.sh script to look like this:</p>

<figure class='code'><figcaption><span>go.sh</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'><span class="c">#!/bin/sh</span>
</span><span class='line'><span class="nb">export </span><span class="nv">USE_SIM_LAUNCHER_SERVER</span><span class="o">=</span>YES
</span><span class='line'>bundle install --deployment
</span><span class='line'>bundle <span class="nb">exec </span>rake ci
</span></code></pre></td></tr></table></div></figure>


<p>The only change we made was exporting that <code>USE_SIMLAUNCHER_SERVER</code> environment variable. This tells Frank to launch the Frankified app using SimLauncher in client-server mode rather than trying to launch it directly.</p>

<p>Next, test out your change by running <code>go.sh</code>. You should see the same CI run as before (including a successful Frank test run), but you should also notice that the terminal window running the SimLauncher contains some output showing that the server was responding to launch requests from Frank during the test run. At this point you should also be able to perform a complete CI run via Jenkins (as long as you have the SimLauncher server running of course).</p>

<p>Starting the <code>simlauncher</code> server by hand in a terminal is a bit of a hassle, but in practice it turns out to not be a big deal. You have to do it once every time you reboot your build box, which with OS X is a fairly infrequent event.</p>

<h2>Next steps</h2>

<p>We now have a working CI setup. However this basic configuration should only be the start of the journey. Because of the value they provide CI systems tend to grow over time. I&#8217;ll briefly describe some directions in which you might grow this system.</p>

<p>The first thing I&#8217;d want to add is an <strong>automated unit testing</strong> run (before the Frank run). After that one could start adding <strong>internal quality metrics</strong> (code duplication, unit- and acceptance test coverage, cyclometric complexity reports, etc.). You might want builds which have passed your acceptance test suite to be <strong>automatically deployed</strong> to QA devices via <a href="http://hockeyapp.net">HockeyApp</a> or <a href="http://testflightapp.com">TestFlight</a>. At that point you&#8217;re starting to move towards a <a href="http://martinfowler.com/delivery.html">Continuous Delivery</a> system where features and bug fixes move through one or more <strong>delivery pipelines</strong> from checkin through automated testing to QA deployment and eventual production deployment. As you add more functionality your builds will start to take longer to run, which means slower feedback and more time waiting for a build to pass initial quality checks. At that point you&#8217;ll probably want to look at <strong>parallelizing your build</strong>, most likely by standing up multiple build agents.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using the UIAutomation private framework]]></title>
    <link href="http://blog.thepete.net/blog/2012/07/11/using-the-uiautomation-private-framework/"/>
    <updated>2012-07-11T07:43:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/07/11/using-the-uiautomation-private-framework</id>
    <content type="html"><![CDATA[<p>I&#8217;ve recently spent a few hours investigating how feasible it would be to use Apple&#8217;s private UIAutomation framework to simulate user interactions in iOS apps. The motivation for this is of course being able to use this for <a href="http://testingwithfrank.com">Frank</a>, the UI testing tool I maintain. This post will summarize my progress to date. You can also check out my work-in-progress <a href="https://github.com/moredip/Frank/tree/uiautomation">uiautomation branch</a> for Frank. Note that that branch is <em>very</em> rough and ready at the moment. I pushed it up to my github repo just so anyone who wants to see progress so far can do so.</p>

<h2>Credit</h2>

<p>First off, credit where credit&#8217;s due. This whole approach was suggested by <a href="https://twitter.com/haxie1">Kam Dahlin</a>, who has been quietly advocating for it every now and then on the Frank mailing lists. He is also the guy who told me that the ARM build of UIAutomation.framework is embedded inside a disk image which is mounted on the device by XCode.</p>

<p>Also credit goes to <a href="https://twitter.com/alloy">Eloy Durán</a> who started investigating the same approach described here in order to add some UI automation features to the macbacon framework used by <a href="http://rubymotion.com">RubyMotion</a> projects. He gave me some good pointers. From reading <a href="https://github.com/HipByte/RubyMotion/blob/master/lib/motion/spec/helpers/ui.rb">his implementation</a>, we ended up in pretty similar places.</p>

<h2>Finding the framework</h2>

<p>The UIAutomation private framework comes with XCode, but at first glance it seems that framework only contains a library built for the Simulator, not the device:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>⋙ mdfind -name UIAutomation.framework
</span><span class='line'>/Users/Thoughtworks/Library/Developer/Xcode/iOS DeviceSupport/5.1.1 (9B206)/Symbols/Developer/Library/PrivateFrameworks/UIAutomation.framework
</span><span class='line'>/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/Developer/Library/PrivateFrameworks/UIAutomation.framework</span></code></pre></td></tr></table></div></figure>




<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>⋙ file /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/Developer/Library/PrivateFrameworks/UIAutomation.framework/UIAutomation 
</span><span class='line'>/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/Developer/Library/PrivateFrameworks/UIAutomation.framework/UIAutomation: Mach-O dynamically linked shared library i386</span></code></pre></td></tr></table></div></figure>


<p>But (thanks to a tip from Kam), you can see that it&#8217;s also available inside the DeveloperDiskImage.dmg which comes with XCode. After enabling a device for development using XCode this disk image will be mounted <em>on your device</em> by XCode whenever you connect your device to your development machine. More info on that <a href="http://code.google.com/p/chronicdev/wiki/DeveloperDiskImage">here</a>.</p>

<p>The long and the short of this is that you can dynamically load the framework at runtime when running on the device, but only if you have mounted the developer disk image on the device. The easy way to do that is to simple connect the device to XCode.</p>

<p>Note that <strong>you can subsequently disconnect your device</strong> and it appears that the disk image stays mounted although I&#8217;m not sure how long for.</p>

<h2>Linking in the framework</h2>

<p>If you&#8217;re building for the simulator you can just tell the linker to link in the simulator version of the private framework. Something like <code>-framework /path/to/UIAutomation.framework</code> should do the trick.</p>

<p>To link the framework on the device you&#8217;ll need to ensure the Developer Disk Image is mounted (as discussed above). Assuming that&#8217;s the case then this one-liner while your app is booting should work fine:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='objective-c'><span class='line'><span class="n">dlopen</span><span class="p">([</span><span class="s">@&quot;/Developer/Library/PrivateFrameworks/UIAutomation.framework/UIAutomation&quot;</span> <span class="n">fileSystemRepresentation</span><span class="p">],</span> <span class="n">RTLD_LOCAL</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Accessing the framework</h2>

<p>Because it&#8217;s a private framework UIAutomation doesn&#8217;t come with any header files. <a href="http://www.codethecode.com/projects/class-dump/">class-dump</a> to the rescue! This is a really handy utility when working with private frameworks. It will analyse a framework and generate a header file based on what it finds. You can install it with homebrew - <code>brew install class-dump</code> and then generate a header file with something like <code>class-dump /path/to/UIAutomation.framework &gt; UIAutomation.h</code>.</p>

<p>The file class-dump produces may need a little bit of massaging - the ordering of classes might not work first of all because of dependencies between them. Once it&#8217;s in good shape you can include it in your project.</p>

<p>Now that you have that header file you can access UIAutomation just as you would any other framework. To test this out, try something like:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='objective-c'><span class='line'><span class="n">UIASyntheticEvents</span> <span class="o">*</span><span class="n">events</span> <span class="o">=</span> <span class="p">[</span><span class="n">UIASyntheticEvents</span> <span class="n">sharedEventGenerator</span><span class="p">];</span>
</span><span class='line'><span class="p">[</span><span class="n">events</span> <span class="n">lockDevice</span><span class="p">];</span>
</span></code></pre></td></tr></table></div></figure>


<p>You should see the device lock as soon as your app executes this code.</p>

<h2>Limitations</h2>

<p>The main limitation with programatically driving UIAutomation seems to be that the high-level automation API doesn&#8217;t work when executing from the foreground app. According to Eloy Durán it seems that it may work if executed by a background app. The high-level API is things like UIATarget, UIATableView, etc. However the lower-level UIASyntheticEvents API does seem to work, at least for the bits I&#8217;ve tried to use.</p>

<p>I have confirmed that the high-level API does not always work when called from the app under test. I haven&#8217;t tried running it from a backgrounded app. However, I have also found that <strong>some of the high level API will work</strong>, but sometimes will lock up. It looks like it&#8217;s locking up while waiting for events to be processed by a run loop. For example, using <code>UIAKeyboard#typeString</code> <em>will</em> work if all the characters you want to type are currently visible on the keyboard, but will lock up if you try to type characters not in the current keyplane. This makes me think that internally UIAKeyboard is switching the keyboard&#8217;s plane (e.g. to the symbol plane) and then waiting for it to be ready in that new plane. If UIAKeyboard is waiting for the app to update while the app itself is waiting for UIAKeyboard to finish up then we&#8217;d have a livelock, which is what this looks like. Anyway, this is all just conjecture at this point; needs more investigation.</p>

<h2>The good news</h2>

<p>All that said, the low-level API exposed by UIASyntheticEvents seems to work wonderfully. It appears to allow automation of the full range of taps, swipes, and multi-touch gestures. This basically replaces Frank&#8217;s need for KIF or UISpec as an interaction synthesis library. The one exception here is driving the keyboard - KIF has some really impressive code which will do that based only on low-level touch events. That implementation might need to be ported over to use UIASyntheticEvents instead. I&#8217;m also quite hopeful that some clever hackery will allow the high-level UIAutomation API to be used.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[writing your first Frank test]]></title>
    <link href="http://blog.thepete.net/blog/2012/06/24/writing-your-first-frank-test/"/>
    <updated>2012-06-24T19:28:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/06/24/writing-your-first-frank-test</id>
    <content type="html"><![CDATA[<p>You&#8217;ve heard about how awesome <a href="http://www.testingwithfrank.com">Frank</a> is and you&#8217;re all fired up about getting some automated functional testing set up for your iOS app. Now you&#8217;re ready to start writing your first test. In this article I&#8217;ll cover the fundamentals of writing Frank tests, using an open source iOS application written for the 2012 Olympic Games as an example.</p>

<h2>get the code for your app</h2>

<p>I&#8217;m guessing you&#8217;ll already have the code for your own app, but if you&#8217;d like to follow along with the examples in this post you&#8217;ll want to download the sample app I&#8217;m using. You&#8217;ll find it on github <a href="https://github.com/Frahaan/2012-Olympics-iOS--iPad-and-iPhone--source-code">here</a>. Create a local clone of that repo with <code>git clone https://github.com/Frahaan/2012-Olympics-iOS--iPad-and-iPhone--source-code.git</code></p>

<p>Now open up the app in XCode and make sure you can run it in the simulator.</p>

<h2>Frankify your app</h2>

<p>Open up a terminal, and cd into the project&#8217;s root directory (the one with the app&#8217;s <code>.xcodeproj</code> file in it). Now we can Frankify the app as follows:</p>

<ul>
<li>install the frank-cucumber gem if you haven&#8217;t already by running <code>sudo gem install frank-cucumber</code>. That sudo part won&#8217;t be necessary if you&#8217;re using <a href="http://rvm.beginrescueend.com/">rvm</a> to manage your ruby setup (which I&#8217;d recommend).</li>
<li>run <code>frank setup</code> to create a Frank subdirectory which contains everything necessary to Frankify your app.</li>
<li>run <code>frank build</code> to create a Frankified version of your app.</li>
<li>run <code>frank launch</code> to launch the Frankified app in the simulator.</li>
<li>check that you are indeed running a Frankified version of the app by running <code>frank inspect</code>. This will open up Symbiote in your web browser.</li>
</ul>


<h2>Symbiote</h2>

<p>Symbiote is a little web app which is embedded into your Frankified app. It allows you to inspect the current state of your app as it&#8217;s running. It also lets you experiment with <em>view selectors</em>. View selectors are how you specify which views in your app you want to interact with or inspect the value of. If you&#8217;re familiar with CSS selectors or XPath expressions the concept is the same.</p>

<p>Let&#8217;s learn a bit more about selectors by experimenting with our example Olympics app. I&#8217;ve followed the steps above, and am looking at the home screen of the app in Symbiote.</p>

<p><img src="http://blog.thepete.net/images/post_images/2012-06-24_A.png"></img></p>

<p>Note that I have the actual iOS Simulator side-by-side with my web browser. That&#8217;s useful when testing view selectors in Symbiote, because the main way of testing selectors is to flash the views in the simulator which match a selector. Let&#8217;s try that now. Type <code>view marked:'Events'</code> into the selector field at the top left of Symbiote in the web browser, and then hit the <strong>Flash</strong> button. You should see the Events button in the simulator flash. Congratulations, you are using Frank to manipulate specific parts of your iOS app.</p>

<h2>running our first cucumber test</h2>

<p>Our goal is to use Frank and cucumber to run automated tests against our app. The <code>frank setup</code> command provides an initial cucumber test for you so that you can verify that cucumber is working correctly in your system. First off we need to tell cucumber where our Frankified app is located so that cucumber can launch the app at the start of each test scenario. To do this, open up <code>Frank/features/support/env.rb</code>. At the bottom of that file you&#8217;ll see a TODO comment about setting the <code>APP_BUNDLE_PATH</code>. Replace that section of the file with something like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="no">APP_BUNDLE_PATH</span> <span class="o">=</span> <span class="no">File</span><span class="o">.</span><span class="n">expand_path</span><span class="p">(</span> <span class="s1">&#39;../../../frankified_build/Frankified.app&#39;</span><span class="p">,</span> <span class="bp">__FILE__</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>This tells Frank the location of your Frankified app, relative to that env.rb file. Now that we have done that we can run the initial cucumber test that was provided as part of <code>frank setup</code>. To do that simple run <code>cucumber</code> in a terminal from the Frank subdirectory. When you do that you should see the Frankified app launch in the simulator, and then perform some rotations. You&#8217;ll also see some output in the terminal from cucumber describing the test steps it has performed and eventually declaring the test scenario passed.</p>

<h2>writing our own cucumber test</h2>

<p>All right, now that we know how to run cucumber tests we should write our own. We&#8217;re going to write a cuke test which verifies that the tab navigation buttons in our example Olympics app work correctly. We&#8217;ll write these tests in a new <em>feature file</em> called <code>Frank/features/navigation.feature</code>. Create that file with the following content:</p>

<figure class='code'><figcaption><span>navigation.feature</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='cucumber'><span class='line'><span class="k">Feature:</span><span class="nf"> Navigating between screens</span>
</span><span class='line'>
</span><span class='line'><span class="k">Scenario:</span><span class="nf"> Moving from the &#39;Home&#39; screen to the &#39;Events&#39; screen</span>
</span><span class='line'><span class="k">Given </span><span class="nf">I launch the app</span>
</span><span class='line'><span class="k">Then </span><span class="nf">I should be on the Home screen</span>
</span><span class='line'>
</span><span class='line'><span class="k">When </span><span class="nf">I navigate to &quot;</span><span class="s">Events</span><span class="nf">&quot;</span>
</span><span class='line'><span class="k">Then </span><span class="nf">I should be on the Events screen</span>
</span></code></pre></td></tr></table></div></figure>


<p>This expresses a test scenario. Now let&#8217;s ask cucumber to test just this feature by running <code>cucumber features/navigation.feature</code>. You should see the app launch, but then cucumber will complain because it doesn&#8217;t know how to execute any of the steps we&#8217;ve described after launching the app. That&#8217;s fair enough; we haven&#8217;t defined them anywhere yet! Let&#8217;s do that now.</p>

<p>Create a <em>step definition</em> file called <code>features/step_definitions/navigation_steps.rb</code>. When cucumber encountered the undefined steps just now it outputted a bunch of boilerplate code for defining those steps. We&#8217;ll cut and paste that code into our new step definition file. You should end up with this:</p>

<figure class='code'><figcaption><span>navigation_steps.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="no">Then</span><span class="sr"> /^I should be on the Home screen$/</span> <span class="k">do</span>
</span><span class='line'>  <span class="n">pending</span> <span class="c1"># express the regexp above with the code you wish you had</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="no">When</span><span class="sr"> /^I navigate to &quot;(.*?)&quot;$/</span> <span class="k">do</span> <span class="o">|</span><span class="n">arg1</span><span class="o">|</span>
</span><span class='line'>  <span class="n">pending</span> <span class="c1"># express the regexp above with the code you wish you had</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="no">Then</span><span class="sr"> /^I should be on the Events screen$/</span> <span class="k">do</span>
</span><span class='line'>  <span class="n">pending</span> <span class="c1"># express the regexp above with the code you wish you had</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we&#8217;re going to implement these step definitions one at a time. Let&#8217;s start with the first one. We need to check that we are on the home screen. Looking at the home screen in Symbiote it consists of a big UIView with a UIImageView inside of it called <code>Icon512x512.png</code>. Our test can verify that the app is displaying the home screen by checking whether that UIImageView is in the view heirarchy. If it is then presumably we&#8217;re on the home screen. If we don&#8217;t see that view then we&#8217;re not on the home screen. This isn&#8217;t an <em>ideal</em> way of verifying where we are - for a start that image view should have a better accessibility label which would make our tests less brittle and coincidentally also make the VoiceOver experience better - but it will do for now.</p>

<p>To test whether a view exists we create a view selector which selects a UIImageView with the correct accessibility label and then we ask frank to verify that that selector matches at least one view. The entire step definition will look like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="no">Then</span><span class="sr"> /^I should be on the Home screen$/</span> <span class="k">do</span>
</span><span class='line'>  <span class="n">check_element_exists</span> <span class="s2">&quot;view view:&#39;UIImageView&#39; marked:&#39;Icon512x512.png&#39;&quot;</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now when we run the cucumber feature again with <code>cucumber features/navigation.feature</code> we should see that step show up as green and passing in cucumber&#8217;s output. We are indeed at the Home screen at launch, and our test has verified that. One step down, two to go!</p>

<p>Next we need to define the step which navigates to a specific tab. To do that we&#8217;ll ask frank to touch the appropriate tab button in the UI. Looking in Symbiote it appears that those buttons are implemented as views of class <code>UITabBarButton</code>. We can also see that UIKit is giving them nice acccessibility labels. This means all we need to do to implement this step is something like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="no">When</span><span class="sr"> /^I navigate to &quot;(.*?)&quot;$/</span> <span class="k">do</span> <span class="o">|</span><span class="n">tab_name</span><span class="o">|</span>
</span><span class='line'>  <span class="n">touch</span> <span class="s2">&quot;view:&#39;UITabBarButton&#39; marked:&#39;</span><span class="si">#{</span><span class="n">tab_name</span><span class="si">}</span><span class="s2">&#39;&quot;</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>If I run the feature again with cucumber I should see that step executing and taking us to the Events screen in the UI.</p>

<p>Now we&#8217;ll write our final step definition. We need to check that we are on the Events screen. Back in Symbiote if we inspect the view heirarchy for that screen we see a UIScrollView which contains a bunch of different buttons for the different Olympic events. I suppose a reasonable check for whether we&#8217;re on this screen would be to look for a few of those buttons. Again, this isn&#8217;t ideal but it should work pretty well. Here&#8217;s our step definition for that:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="no">Then</span><span class="sr"> /^I should be on the Events screen$/</span> <span class="k">do</span>
</span><span class='line'>  <span class="n">check_element_exists</span> <span class="s2">&quot;view:&#39;UIScrollView&#39; view:&#39;UIButton&#39; marked:&#39;archery&#39;&quot;</span>
</span><span class='line'>  <span class="n">check_element_exists</span> <span class="s2">&quot;view:&#39;UIScrollView&#39; view:&#39;UIButton&#39; marked:&#39;badminton&#39;&quot;</span>
</span><span class='line'>  <span class="n">check_element_exists</span> <span class="s2">&quot;view:&#39;UIScrollView&#39; view:&#39;UIButton&#39; marked:&#39;boxing&#39;&quot;</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>And with that we are done. Running our feature again should result in a green, passing cucumber test. Hurray, we have written our first Frank test!</p>

<h2>Don&#8217;t forget to refactor</h2>

<p>Hang on, before we rush out to celebrate let&#8217;s clean up a bit. That last step has loads of duplication in it. Let&#8217;s refactor it a bit to this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="no">Then</span><span class="sr"> /^I should be on the Events screen$/</span> <span class="k">do</span>
</span><span class='line'>  <span class="sx">%w{archery badminton boxing}</span><span class="o">.</span><span class="n">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">expected_label</span><span class="o">|</span>
</span><span class='line'>    <span class="n">check_element_exists</span> <span class="s2">&quot;view:&#39;UIScrollView&#39; view:&#39;UIButton&#39; marked:&#39;</span><span class="si">#{</span><span class="n">expected_label</span><span class="si">}</span><span class="s2">&#39;&quot;</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>That seems a bit cleaner to me. We run our tests again to make sure we&#8217;re still green.</p>

<p><strong>Now</strong> we can go out and celebrate our first Frank test!</p>

<h2>Where to turn for help</h2>

<p>Frank is a pretty powerful tool, and it does take time to learn the nooks and crannies of Frank. This is particularly true if you are also new to ruby and/or cucumber.</p>

<p><a href="http://www.testingwithfrank.com">testingwithfrank.com</a> has documentation, screencasts, and links to more resources.</p>

<p>The <a href="http://groups.google.com/group/frank-discuss">frank mailing list</a> is a particularly great resource. Lots of folks there have gone through the same learning process you will go through, and are happy to help.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Lowering Frank's barrier to entry]]></title>
    <link href="http://blog.thepete.net/blog/2012/06/16/lowering-franks-barrier-to-entry/"/>
    <updated>2012-06-16T23:34:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/06/16/lowering-franks-barrier-to-entry</id>
    <content type="html"><![CDATA[<p>I&#8217;ve always known that it&#8217;s really important new users of <a href="http://www.testingwithfrank.com">Frank</a> to easily get started by creating a Frankified version of their app - a build which has been enhanced with the embedded server which lets Frank do its magic.</p>

<p>When the project was first started it was really quite complex to setup. You had to add a bunch of source code to your app, and then modify a few bits of your app&#8217;s startup code.</p>

<p>After a while, with the help of some Objective C big-brains like <a href="http://www.stewgleadow.com/">Stew Gleadow</a>, the steps need to Frankify your app were simplified. You &#8216;just&#8217; needed to duplicate your app&#8217;s main target, link in a static library and a resource bundle and add a few linker flags. Note that I put &#8216;just&#8217; in quotes there. While this definitely helped make it less intimidating I still thought that there were many potential users of Frank who were missing out because they hit some snag or other while getting started.</p>

<p>While I was at WWDC this year I took the opportunity to investigate ways to make Frank even easier to get started with. I asked some questions in the labs and got some great advice from some of the Xcode team. I was also stoked to meet a bunch of other non-Apple Objective C big-brains, once again courtesy of Stew.</p>

<h2>Zero-config Frank</h2>

<p>A couple of days of post-WWDC hacking later, and I&#8217;m pleased to announce a new <strong>zero-configuration</strong> Frank setup. You can now create a Frankified version of your application <em>without touching your Xcode project at all</em>, using a simple <code>frank build</code> command. Here&#8217;s a screencast showing how it works.</p>

<iframe src="http://player.vimeo.com/video/44224224" width="500" height="290" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>


<h2>Benefits</h2>

<p>To my mind the biggest benefit is that this will help grow the community of Frank users by reducing the barrier to entry. It also means you no longer need to maintain a duplicate Xcode target, and therefore no longer need to make sure that .m files included in one target are also included in the other.</p>

<h2>How does it work</h2>

<p>There&#8217;s actually not much magic going on here. The concept is to leave the Xcode project as-is and instead just use xcodebuild to build a customized version of the app. That essentially just means adding a few linker flags and linking in a few static libraries and frameworks. This is all specified in a frankify.xcconfig file. We also specify a few other xcodebuild flags so that the app is built into a known location inside of the Frank subdirectory. This is much nicer than having to hunt around for it in the DerivedData dirs that Xcode 4 introduced.</p>

<p>Aside from the xcodebuild bits the main chunk of work was in creating a <a href="https://github.com/wycats/thor">Thor</a>-based command line tool with the cunningly original name <code>frank</code>. This is installed as part of the <code>frank-cucumber</code> gem, just like the (now deprecated) frank-skeleton script was. This command line tool provides commands for setting up a Frank directory inside your app project and building the Frankified app using the custom xcodebuild approach I just described. There are also commands for updating the frank server code, launching your frankified app in the simulator, opening Symbiote in the browser, and for launching a frank console. You can run <code>frank help</code> for more details.</p>

<h2>The frank console</h2>

<p>Another thing I added as part of this goal of making Frank easier to use is <code>frank console</code>. This is some very minimal code which uses <a href="http://pry.github.com/">Pry</a> to bring up a simple ruby REPL that has the Frank helper code already mixed in. This will hopefully give more technical users a nice way to quickly prototype ruby test code against a running instance of their app. I demonstrate the basic functionality in the screencast above.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Birth Of a Domain Object In Ruby]]></title>
    <link href="http://blog.thepete.net/blog/2012/06/09/the-birth-of-a-domain-object-in-ruby/"/>
    <updated>2012-06-09T00:58:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/06/09/the-birth-of-a-domain-object-in-ruby</id>
    <content type="html"><![CDATA[<p>Software designs don&#8217;t pop into existance fully formed. They evolve over time. In this post I&#8217;m going to show how a concept can grow from a simple method parameter to an all-growed-up Domain Object.</p>

<h2>Initial requirements</h2>

<p>Imagine we&#8217;re building some code that will take bug reports from a user and submit them to a third-party bug tracking service. We expose an HTTP endpoint in a sinatra app to allow this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">(</span> <span class="n">bug_description</span> <span class="p">)</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>So far so good. We&#8217;ll assume that <code>BugFiler</code> is some service code that takes a bug description string and makes the appropriate service call to create a bug with that description in our bug tracking system. We won&#8217;t be focussing on the implementation of that class here, we&#8217;ll just be a client of it.</p>

<p>So a concept that&#8217;s starting to surface here is that of a <strong>Bug</strong>. So far it is represented by a string primitive and that&#8217;s OK because that&#8217;s all we need right now. Some java programmers would leap to their IDE keyboard shortcuts at this point and fix this Primitive Obsession code smell by refactoring this string primitive into a Bug type. But we&#8217;re ruby programmers, so we won&#8217;t do that. We&#8217;re pragmatic. YAGNI.</p>

<h2>New requirements</h2>

<p>Now our product guys have realized that it&#8217;d be nice to know who is submitting these bug reports. They&#8217;d like us to record the name of the person filing the report. OK, we can do that.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">(</span> <span class="n">bug_description</span><span class="p">,</span> <span class="n">bug_reporter</span> <span class="p">)</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can assume that we also modified <code>BugFiler#report_bug</code> to take that second arg.</p>

<p>So now we&#8217;re good. New requirements are satisfied and we can move on to our next task.</p>

<h2>More new requirements</h2>

<p>Oh actually, the product folks have realized we should really be tracking severity too. OK.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>   <span class="n">severity</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:severity</span><span class="o">]</span>
</span><span class='line'>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">(</span> <span class="n">bug_description</span><span class="p">,</span> <span class="n">bug_reporter</span><span class="p">,</span> <span class="n">severity</span> <span class="p">)</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>So this works, but now alarm bells are ringing for me. 3 params is about my limit for maintainable code. Let&#8217;s change <code>BugFiler#report_bug</code> to take a hash instead.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>   <span class="n">severity</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:severity</span><span class="o">]</span>
</span><span class='line'>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">({</span>
</span><span class='line'>     <span class="ss">:description</span> <span class="o">=&gt;</span> <span class="n">bug_description</span><span class="p">,</span>
</span><span class='line'>     <span class="ss">:reporter</span> <span class="o">=&gt;</span> <span class="n">bug_reporter</span><span class="p">,</span>
</span><span class='line'>     <span class="ss">:severity</span> <span class="o">=&gt;</span> <span class="n">severity</span>
</span><span class='line'>     <span class="p">})</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>A bit more verbose, but I&#8217;d say more readable too.</p>

<h2>Default severity</h2>

<p>Turns out that sometimes a user doesn&#8217;t bother to explicitly specify a bug severity, so we should set that to a default of &#8216;medium&#8217; by default.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>   <span class="n">severity</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:severity</span><span class="o">]</span> <span class="o">||</span> <span class="s1">&#39;medium&#39;</span>
</span><span class='line'>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">({</span>
</span><span class='line'>     <span class="ss">:description</span> <span class="o">=&gt;</span> <span class="n">bug_description</span><span class="p">,</span>
</span><span class='line'>     <span class="ss">:reporter</span> <span class="o">=&gt;</span> <span class="n">bug_reporter</span><span class="p">,</span>
</span><span class='line'>     <span class="ss">:severity</span> <span class="o">=&gt;</span> <span class="n">severity</span>
</span><span class='line'>     <span class="p">})</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Deriving a bug summary</h2>

<p>Our product friends are back. Turns out that our third party bug tracker allows us to specify a summary line describing the bug, but we don&#8217;t currently have any UI exposed which lets users specify that summary. We&#8217;d like to work around this by just clipping the first line of text from the bug description and using that as the bug summary. OK, I think we can do that.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>   <span class="n">severity</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:severity</span><span class="o">]</span> <span class="o">||</span> <span class="s1">&#39;medium&#39;</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">bug_summary</span> <span class="o">=</span> <span class="n">bug_description</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">first</span>
</span><span class='line'>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">({</span>
</span><span class='line'>     <span class="ss">:description</span> <span class="o">=&gt;</span> <span class="n">bug_description</span><span class="p">,</span>
</span><span class='line'>     <span class="ss">:reporter</span> <span class="o">=&gt;</span> <span class="n">bug_reporter</span><span class="p">,</span>
</span><span class='line'>     <span class="ss">:severity</span> <span class="o">=&gt;</span> <span class="n">severity</span><span class="p">,</span>
</span><span class='line'>     <span class="ss">:summary</span> <span class="o">=&gt;</span> <span class="n">bug_summary</span>
</span><span class='line'>     <span class="p">})</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Replacing Primitive Obsession with a Struct</h2>

<p>Now at this point I think we have too much logic in our controller code. It feels like we have the beginnings of a domain object here. We don&#8217;t want to disturb too much code as we initially introduce this new object, so we&#8217;ll just replace the primitive hash we currently have with a Struct.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="c1"># elsewhere in the codez</span>
</span><span class='line'><span class="no">Bug</span> <span class="o">=</span> <span class="no">Struct</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="ss">:description</span><span class="p">,</span><span class="ss">:reporter</span><span class="p">,</span><span class="ss">:severity</span><span class="p">,</span><span class="ss">:summary</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>   <span class="n">severity</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:severity</span><span class="o">]</span> <span class="o">||</span> <span class="s1">&#39;medium&#39;</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">bug_summary</span> <span class="o">=</span> <span class="n">bug_description</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">first</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">bug</span> <span class="o">=</span> <span class="no">Bug</span><span class="o">.</span><span class="n">new</span><span class="p">(</span> <span class="n">bug_description</span><span class="p">,</span> <span class="n">bug_reporter</span><span class="p">,</span> <span class="n">severity</span><span class="p">,</span> <span class="n">bug_summary</span> <span class="p">)</span>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">(</span> <span class="n">bug</span> <span class="p">)</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;ve used ruby&#8217;s built in Struct facility to dynamically generate a <code>Bug</code> class which takes some parameters at construction and then exposes them as attributes. This type of class is variously referred to as a DTO or Value Object.</p>

<p>Note here that we would have also modified <code>BugFiler#report_bug</code> to expect a <code>Bug</code> instance rather than a raw hash.</p>

<h2>Introducing a Domain Object</h2>

<p>We now have a Bug class, but it&#8217;s just a boring old Value Object with no behaviour attached. Let&#8217;s move the logic which is cluttering up our controller code into our Bug class.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="c1"># elsewhere in the codez</span>
</span><span class='line'><span class="k">class</span> <span class="nc">Bug</span> <span class="o">&lt;</span> <span class="no">Struct</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="ss">:description</span><span class="p">,</span><span class="ss">:reporter</span><span class="p">,</span><span class="ss">:severity</span><span class="p">)</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">summary</span>
</span><span class='line'>    <span class="n">description</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">first</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">severity</span>
</span><span class='line'>    <span class="k">super</span> <span class="o">||</span> <span class="s1">&#39;medium&#39;</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>   <span class="n">severity</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:severity</span><span class="o">]</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">bug</span> <span class="o">=</span> <span class="no">Bug</span><span class="o">.</span><span class="n">new</span><span class="p">(</span> <span class="n">bug_description</span><span class="p">,</span> <span class="n">bug_reporter</span><span class="p">,</span> <span class="n">severity</span> <span class="p">)</span>
</span><span class='line'>   <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">(</span> <span class="n">bug</span> <span class="p">)</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is one of my favorite ruby tricks. We define the class <code>Bug</code> which inherits from a dynamically created Struct class, and then we add in some extra behavior. This way we don&#8217;t have to write boring initialize methods or attr_accessor code in our class definition, and our intent is clearly captured by the use of Struct.</p>

<h2>Solidifying our Domain Object</h2>

<p>Now that we have a <code>Bug</code>, why don&#8217;t we allow it to file itself?</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">class</span> <span class="nc">Bug</span> <span class="o">&lt;</span> <span class="no">Struct</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="ss">:description</span><span class="p">,</span><span class="ss">:reporter</span><span class="p">,</span><span class="ss">:severity</span><span class="p">)</span>
</span><span class='line'>  <span class="k">def</span> <span class="nf">summary</span>
</span><span class='line'>    <span class="n">description</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">first</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">severity</span>
</span><span class='line'>    <span class="k">super</span> <span class="o">||</span> <span class="s1">&#39;medium&#39;</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">def</span> <span class="nf">file_report!</span>
</span><span class='line'>    <span class="no">BugFiler</span><span class="o">.</span><span class="n">report_bug</span><span class="p">(</span><span class="nb">self</span><span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="n">post</span> <span class="s1">&#39;/bug_report&#39;</span> <span class="k">do</span>
</span><span class='line'>   <span class="n">bug_description</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:bug_description</span><span class="o">]</span>
</span><span class='line'>   <span class="n">bug_reporter</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:reporter</span><span class="o">]</span>
</span><span class='line'>   <span class="n">severity</span> <span class="o">=</span> <span class="n">params</span><span class="o">[</span><span class="ss">:severity</span><span class="o">]</span>
</span><span class='line'>
</span><span class='line'>   <span class="n">bug</span> <span class="o">=</span> <span class="no">Bug</span><span class="o">.</span><span class="n">new</span><span class="p">(</span> <span class="n">bug_description</span><span class="p">,</span> <span class="n">bug_reporter</span><span class="p">,</span> <span class="n">severity</span> <span class="p">)</span>
</span><span class='line'>   <span class="n">bug</span><span class="o">.</span><span class="n">file_report!</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>That seems quite nice. We have some controller logic which doesn&#8217;t do much apart from transform params into an object and then call methods on that object.</p>

<h1>Our end state</h1>

<p>At this point we have the beginnings of a real Domain Object in our <code>Bug</code> class. In the future we could add the ability to serialize a Bug instance to a flat file or a database, and not really need to touch our controller code. We can also test all of the business logic without needing to thing about HTTP mocking, <code>Rack::Test</code>, or anything like that.</p>

<p>I&#8217;ve noticed that domain concepts follow evolutionary paths like this quite frequently. In this case our path was:</p>

<ul>
<li>a single parameter</li>
<li>a group of parameters</li>
<li>a hash object</li>
<li>a hash object plus some unattached logic</li>
<li>a value object plus some unattached logic</li>
<li>a domain object with attached logic</li>
</ul>


<h1>YAGNI!</h1>

<p>Something I tried to get across as we worked through this scenario was the importance of taking YAGNI approach to software design. It is very tempting to start introducing domain objects as soon as you see a potential for them, and it&#8217;s fun to do so. But a lot of the time you don&#8217;t ever need to go this far down the path towards a real domain object. If you don&#8217;t need to attach any behaviour then a lot of times a simple hash is just fine.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Feature Flags in JavaScript]]></title>
    <link href="http://blog.thepete.net/blog/2012/05/09/javascript-feature-flags/"/>
    <updated>2012-05-09T14:50:00-07:00</updated>
    <id>http://blog.thepete.net/blog/2012/05/09/javascript-feature-flags</id>
    <content type="html"><![CDATA[<p>On a recent project we were applying Continous Delivery practices and were releasing to production reasonably frequently - sometimes multiple times a week. We didn&#8217;t want to expose features which were under active development in our production environment but we also wanted to avoid feature branches. I&#8217;m going to describe the simple approach we used to solve this problem using <em>feature flagging</em> with javascript and CSS.</p>

<h1>What are feature flags?</h1>

<p>Features flags (aka feature bits, feature toggles) are a very useful technique for managing latent functionality within your application. You expose switches in your application which configure whether certain behavior is enabled or disabled. Typically your would use this pattern for functionality which is under active development and is not &#8216;fully baked&#8217;.</p>

<p>There are various classes of behavior which you might expose toggles for. Common use cases include hiding user-facing features which are still in development, or switching whether your code uses a new version of a third-party service. This allows you to do branch-by-abstraction and therefore avoid long-lived feature branches which can often be the source of considerable pain to a development team.</p>

<h2>Further reading</h2>

<p>For a more in-depth discussion on this pattern, Martin Fowler has a <a href="http://martinfowler.com/bliki/FeatureToggle.html">nice writeup</a>. My former colleague Erik Sowa also has <a href="http://www.infoq.com/presentations/Feature-Bits">a nice presentation</a> describing how we applied &#8216;feature bits&#8217; at a previous company I worked in. Derek Hammer has a <a href="http://www.derekhammer.com/2012/03/24/patterns-to-isolate-code-in-continuous-delivery.html">really nice write up</a> on the broader range of patterns available for isolating code when practicing Continous Delivery.</p>

<h1>Feature flagging using query strings, javascript and css</h1>

<p>As mentioned above, I&#8217;ll be describing a simple but effective feature flagging technique we used on a recent project.  Our team decided to use feature-flagging to hide new features at the UI level using CSS. The mechanism to toggle the features on and off involved query strings and some simple javascript.</p>

<h2>step 1: extracting feature flags from the query string</h2>

<p>First we needed some way to specify whether a feature flag was on or off. We used query params to do this. These query params were totally ignored by the server-side code. There were just there so that javascript on the client side could inspect them at page load.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">parseQueryParamPart</span><span class="p">(</span><span class="nx">part</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">keyAndValue</span> <span class="o">=</span> <span class="nx">part</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s2">&quot;=&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="k">return</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">key</span><span class="o">:</span> <span class="nx">unescape</span><span class="p">(</span><span class="nx">keyAndValue</span><span class="p">[</span><span class="mi">0</span><span class="p">]),</span>
</span><span class='line'>    <span class="nx">value</span><span class="o">:</span> <span class="nx">unescape</span><span class="p">(</span><span class="nx">keyAndValue</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// returns an array of {key:&quot;&quot;,value:&quot;&quot;} objects</span>
</span><span class='line'><span class="kd">function</span> <span class="nx">getQueryParamKeyValuePairs</span><span class="p">(</span><span class="nx">searchSection</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">params</span> <span class="o">=</span> <span class="nx">searchSection</span><span class="p">.</span><span class="nx">slice</span><span class="p">(</span><span class="mi">1</span><span class="p">).</span><span class="nx">split</span><span class="p">(</span><span class="s2">&quot;&amp;&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">_</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span> <span class="nx">params</span><span class="p">,</span> <span class="nx">parseQueryParamPart</span> <span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">getFeatureFlags</span><span class="p">(){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">queryParamKeyValuePairs</span> <span class="o">=</span> <span class="nx">getQueryParamKeyValuePairs</span><span class="p">(</span> <span class="nb">window</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">search</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">return</span> <span class="nx">_</span><span class="p">.</span><span class="nx">compact</span><span class="p">(</span> <span class="nx">_</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span> <span class="nx">queryParamKeyValuePairs</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">pair</span><span class="p">){</span>
</span><span class='line'>    <span class="k">if</span><span class="p">(</span> <span class="nx">pair</span><span class="p">.</span><span class="nx">key</span> <span class="o">===</span> <span class="s1">&#39;ff&#39;</span> <span class="p">)</span>
</span><span class='line'>      <span class="k">return</span> <span class="nx">pair</span><span class="p">.</span><span class="nx">value</span><span class="p">;</span>
</span><span class='line'>    <span class="k">else</span>
</span><span class='line'>      <span class="k">return</span> <span class="kc">undefined</span><span class="p">;</span>
</span><span class='line'>    <span class="nx">end</span>
</span><span class='line'>  <span class="p">}));</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here we do some simple parsing of <code>window.location.search</code> with the help of underscore.js (my favorite javascript library of all time). We find all query params that have a key of &#8216;ff&#8217; and return the values in an array. Note that query params may have multiple identical keys; we handle that by representing the parsed key-value pairs as an array of key-value pairs, rather than the simplistic approach of creating a hash table directly from the query string.</p>

<h2>step 2: expose feature flags as classes in the DOM</h2>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">$</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="nx">_</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span> <span class="nx">getFeatureFlags</span><span class="p">(),</span> <span class="kd">function</span><span class="p">(</span><span class="nx">featureFlag</span><span class="p">){</span>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;html&#39;</span><span class="p">).</span><span class="nx">addClass</span><span class="p">(</span> <span class="s2">&quot;ff-&quot;</span> <span class="o">+</span> <span class="nx">featureFlag</span> <span class="p">);</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here we use jQuery to register a function on document ready. This function will grab all the feature flags specified in the query params and then add a class to the doc&#8217;s <code>&lt;html&gt;</code> element for each flag, prepended with &#8216;ff-&#8217; to avoid any naming collisions with other CSS classes.</p>

<h2>step 4: show or hide UI elements with CSS</h2>

<p>Our goal here is to control whether or not a feature is exposed to an end user. A lot of the time we can hide a feature by simply applying a <code>display:none</code> the right DOM element. Because we added our feature flag classes to the root <code>&lt;html&gt;</code> element we can apply simple CSS rules like the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="nc">.search-wrapper</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">display</span><span class="o">:</span> <span class="k">none</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nc">.ff-search</span> <span class="nc">.search-wrapper</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">display</span><span class="o">:</span> <span class="k">block</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This will hide the <code>search-wrapper</code> element (and anything inside of it) by default, but will show it if there is a parent with a class of <code>ff-search</code>. Combined with the javascript above this has the effect that search functionality will be hidden unless you pass in a query params of <code>ff=search</code> when loading the page. There we have it, a simple feature-flag.</p>

<h2>Further refinements</h2>

<p>This simple approach works quite nicely for a single-page app (which is what our team was developing), but it does have some issues in other cases. The main problem is that any feature flag you specify in a query param will be lost whenever you leave the current page. This could be remedied by storing feature flags in a cookie or in HTML5 local storage. You&#8217;d then check for flags in that store in addition to in the query param during page load. Presumably a flag specified in a query param would override anything in the store.</p>

<p>I&#8217;ve only covered using a feature flag to drive CSS changes, but you could easily expose a simple javascript API which would allow developers to plug in different code based on whether a flag was off or on. In sophisticated use cases you would probably use feature flags to drive the initial wiring up of your code&#8217;s dependencies during boot.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Moving from Blogger to Octopress]]></title>
    <link href="http://blog.thepete.net/blog/2012/02/08/blogger-to-octopress/"/>
    <updated>2012-02-08T18:25:00-08:00</updated>
    <id>http://blog.thepete.net/blog/2012/02/08/blogger-to-octopress</id>
    <content type="html"><![CDATA[<p>Yes, like many other dork bloggers I&#8217;ve jumped onto the <a href="http://octopress.org">Octopress</a> bandwagon.</p>

<p>A big concern I had with switching blogging platforms (I was previously on Blogger) was breaking links to my existing content. Part of my concern was in losing Google Juice (yes, I&#8217;m that vain), but I&#8217;m also aware that a couple of my posts about Frank have become sources of documentation which are linked to from a few different places on the web. I definitely did not want to break those links.</p>

<p>That said, my worries appear to have been groundless. I&#8217;ve been very plesantly surprised at how easy it has been to import my old posts into Octopress, maintaining the same urls. The first step was to export my existing content from Blogger. I went to the Settings section in my blog&#8217;s admin pages and chose Other > Blog Tools > Export blog). Then I pulled down a copy of <a href="https://gist.github.com/1578928">this ruby script</a> I found via a quick google search, and ran it against that exported file from Blogger. It very quickly generated a bunch of static posts from the exported Blogger data. It even used the same path format that Blogger uses, so no problem with broken links. Neat.</p>

<p>All in all, I&#8217;d say it took about 20 minutes to go from cloning the octopress repo to browsing all my old Blogger content in my shiny new Octopress blog. Really a very smooth experience.</p>
]]></content>
  </entry>
  
</feed>
