<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Engine Yard Blog &#187; Dave Astels</title>
	<atom:link href="http://www.engineyard.com/blog/author/daveastels/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.engineyard.com/blog</link>
	<description></description>
	<lastBuildDate>Tue, 07 Feb 2012 19:36:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Ready, Set, Go!</title>
		<link>http://www.engineyard.com/blog/2009/ready-set-go/</link>
		<comments>http://www.engineyard.com/blog/2009/ready-set-go/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 17:00:56 +0000</pubDate>
		<dc:creator>Dave Astels</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://www.engineyard.com/blog/?p=2975</guid>
		<description><![CDATA[<p>Google recently publicly released their new programming language, Go. I've known about this for some time, having worked for the big G while it was in development, although not directly involved.</p>
<p>Google has plenty of special purpose languages, but this is the first general purpose language to come out of Mountain View. That fact alone makes it quite interesting.  Add to it that some of the original C and UNIX people are involved, and it becomes something that requires investigation.</p>
<h2>What's it for?</h2>
<p>Go is a systems programming language.  Think of it as a modern C.  It's meant for the same types of programming: operating systems, compilers, infrastructure pieces.</p>
<h2>What's it all about?</h2>
<p>To summarize the main golang.org page, Go is: simple, fast, safe, concurrent, open source, and fun.</p>
<table border="0" cellspacing="2">
<tbody>
<tr valign="top">
<td><strong>Simple</strong></td>
<td>Go is designed to be easy to work with, requiring minimal overhead and boilerplate.  This is reminiscent of dynamic languages such as Python and Ruby.</td>
</tr>
<tr valign="top">
<td><strong>Fast</strong></td>
<td>Go's syntax is designed well, being regular and relatively simple. In addition to its dependency management features, this leads to fast compile times.  Go provides the runtime efficiency of a statically typed, compiled language such as C or Java without the bloated syntax of those languages.</td>
</tr>
<tr valign="top">
<td><strong>Safe</strong></td>
<td>Go also provides the type safety of a statically typed, compiled language, without the syntax bloat usually associated with a statically typed language.  In addition to type safety, Go is memory safe: you should never get a null pointer error when you use an invalid memory address.  Additionally, it is a garbage collected language, which eliminates even more overhead code and memory related errors.</td>
</tr>
<tr valign="top">
<td><strong>Concurrent</strong></td>
<td>Go is modern language, designed for use in multi-core environments.  Concurrency is built into the language, as is inter process communication (via channels).</td>
</tr>
<tr valign="top">
<td><strong>Open Source</strong></td>
<td>Go is released under a BSD style license.</td>
</tr>
<tr valign="top">
<td><strong>Fun</strong></td>
<td>You'll have to decide that for yourself... but we're enjoying it here at least.</td>
</tr>
</tbody>
</table>
<h2>What's so different about it?</h2>
<p>Go is an object-oriented language, but not in the style that most programmers these days think of OO.  Go doesn't have implementation inheritance (more on that later). Also, you don't define methods inside a class as in many OO languages.  Instead, you add methods to types in a way somewhat reminiscent of <a href="http://www.apl.jhu.edu/~hall/lisp.html#Section4">CLOS </a>.  For example:</p>
<blockquote>
<pre>func (file *File) Read(b []byte) (number_bytes_read int, err os.Error) { ... }
  if file == nil {
    return -1, os.EINVAL
  }
  r, e := syscall.Read(file.fd, b);
  if e != 0 {
    err = os.Errno(e);
  }
  return int(r), err
}</pre>
</blockquote>
<p>Here we have a function <code>Read</code> that's being attached to the type <code>*File</code>. <code>Read</code> takes a single parameter, <code>b</code>, which is an array of <code>byte</code> and it returns an <code>int</code> named <code>number_bytes_read</code> and an <code>Error</code> named <code>err</code>.  There are three things to note here. <code>Read</code>, is (1) being attached to an existing type (a pointer type at that), and (2) returns multiple values which (3) are named.  Even if the return value names aren't used, they are superb for documenting what the returned values mean.</p>
<h2>Points of Note</h2>
<h3>Fast compilation</h3>
<p>Go compiles fast. <em>Really</em> fast. This means no long waits for builds. More importantly, it means a tighter test-code development cycle.</p>
<p><span id="more-2975"></span></p>
<h3>Less typing... and less typing</h3>
<p>Here's the basic way to declare a variable (a string in this case):</p>
<blockquote><p><code><br />
var s string = "";<br />
</code></p></blockquote>
<p>If the type can unambiguously be inferred, you can do:</p>
<blockquote><p><code><br />
var s = "";<br />
</code></p></blockquote>
<p>and using the initializing declaration operator, you can simplify even more:</p>
<blockquote><p><code><br />
s := "";<br />
</code></p></blockquote>
<p>I say <em>shiny</em>: this is pretty sweet.  Minimal boilerplate <strong>and</strong> type inference.</p>
<h3>Arrays and Slices</h3>
<p>Arrays are, of course, built-in to the syntax.  Arrays are fixed size linear collections of data.  They work pretty much as expected except that they don't support the pointer arithmetic tricks that C programmers take for granted.  So, you get an actual pointer to an array, not just a pointer to something that happens to be the first thing in the array.</p>
<p>Slices are the idiomatic way to work with sequences of data in Go.  They wrap arrays to give a more powerful way to work.  Slices are too big of a topic to explore in this post, but basically they provide a dynamic window onto an array.</p>
<p>Arrays have a size as an integral aspect of the type, thus <code>[3]int</code> is a different type than <code>[5]int</code>. Slices have a size as part of their data.</p>
<p>You create a slice of an array by specifying the initial and one past the final index.  For example:</p>
<blockquote>
<pre>a := [4]int{1, 2, 3, 4};
s := a[1:3];

s[0] == 2
s[1] == 3</pre>
</blockquote>
<p>Here <code>s</code> has a size of 2 <em>(3 - 1)</em> and type <code>[]int</code>.</p>
<p>Here's a function that takes a slice as its parameter:</p>
<blockquote>
<pre>func F(buf []byte)</pre>
</blockquote>
<p>You can tell this is a slice because there is no size inside the brackets.You could call the above function with an explicit slice:</p>
<blockquote>
<pre>var a [5]byte;
F(a[2:4]);</pre>
</blockquote>
<p>but you can also implicitly pass a slice that covers a complete array:</p>
<blockquote>
<pre>var a [5]byte;
F(a);</pre>
</blockquote>
<h3>Strings and Maps are built-in</h3>
<p>Something that's nice to see is that strings are built into the language and standard library as in C (but unlike C++).  The proliferation of string libraries in C++ caused great confusion and frustration in C++'s early days.</p>
<p>What's even nicer to see is that hashes are built-in. Having the basic and extremely useful types built-in to the language make it possibly to optimize them quite aggressively. This way. programmers don't have to worry about choosing a slow string or hash library.</p>
<p>Maps are very flexible, here's an example from <a href="http://golang.org/doc/effective_go.html">Effective Go</a>:</p>
<blockquote>
<pre>var timeZone = map[string] int {
  "UTC":  0*60*60,
  "EST": -5*60*60,
  "CST": -6*60*60,
  "MST": -7*60*60,
  "PST": -8*60*60,
}

func offset(tz string) int {
  if seconds, ok := timeZone[tz]; ok {
    return seconds
  }
  log.Stderr("unknown time zone", tz);
  return 0;
}</pre>
</blockquote>
<p>Note the multiple return values where the second is an indicator as to whether a valid value was found.</p>
<h3>Interfaces</h3>
<p>Interfaces are just a collection of function signatures. Here's an example of interface use taken from the IO library:</p>
<blockquote>
<pre>type Reader interface {
  Read(p []byte) (n int, err os.Error);&gt;
}

type Writer interface {
  Write(p []byte) (n int, err os.Error);
}</pre>
</blockquote>
<p>This is nothing too earth shattering if you're familiar with Java.  If you're used to Ruby, this <strong>is</strong> something a little different: actually having to codify the protocols to which your objects conform (see <a href="//github.com/jimweirich/presentation_solid_ruby.git">Jim Weirich's RubyConf 2009 talk</a> for a discussion of this).</p>
<p>Making the connection between interfaces and the types that implement them is just the opposite. It's implicit—as it is in Ruby et.al.— not explicit, as it is in Java.  For example here is something that can be used whenever a <code>Reader</code> is expected:</p>
<blockquote>
<pre>type limitedReader struct {
  r Reader;
  n int64;
}

func (l *limitedReader) Read(p []byte) (n int, err os.Error) { ... }</pre>
</blockquote>
<p>This example also shows declaring a variable (a struct member in this case) of an interface type.</p>
<p>One nice thing about the way interfaces are done in Go is that if you define an interface that declares some methods of an existing type, you have implicitly performed an <strong>Extract Interface</strong> refactoring.  None of the types implementing those methods have to be touched: they can now be implicitly and automatically used wherever you use the new interface.</p>
<p>One nice feature is the ability to make composite interfaces:</p>
<blockquote>
<pre>type ReadSeeker interface {
  Reader;
  Seeker;
}</pre>
</blockquote>
<p>Here, the <code>ReadSeeker</code> interface encompasses everything in both the <code>Reader</code> and <code>Seeker</code> interfaces.  Anything that implements the methods declared in <code>Reader</code> and <code>Seeker</code> can be used wherever <code>Reader</code>, <code>Seeker</code>, or <code>ReadSeeker</code> is used.</p>
<h2>No Implementation Inheritance</h2>
<p>It is the lack of implementation inheritance that seems odd.  Most of us are used to considering it as a necessary part of an OO language.  In his 1996 talk "<a href="http://www2.research.att.com/~bs/whatis.pdf">What is Object-Oriented Programming?</a>" Bjarne Stroustrup (creator of C++) went so far as to say:</p>
<blockquote><p><em>Consider a language having some form of method lookup without having an inheritance mechanism. Could that language be said to support object-oriented programming? I think not.</em></p></blockquote>
<p>It's interesting to note, however, that Alan Kay (arguably the father and namer of OO) didn't <em>originally</em> consider inheritance necessary as part of the language (in "<a href="http://gagne.homedns.org/~tgagne/contrib/EarlyHistoryST.html">The Early History of Smalltalk</a>"):</p>
<blockquote><p><em>I just decided to leave inheritance out as a feature in Smalltalk-72, knowing that we could simulate it back using Smalltalk's LISPlike flexibility. The biggest contributor to these AI ideas was Larry Tesler who used what is now called "slot inheritance" extensively in his various versions of early desktop publishing systems. Nowadays, this would be called a "delegation-style" inheritance scheme.</em></p></blockquote>
<p>Inheritance was jumped on when OO hit the scene back in the 80s.  We saw it used far too much and too freely.  Over the years the thinking shifted to a more sensible approach of composition rather than inheritance.  This is what Kay was referring to back in '72.</p>
<h3>Garbage Collection</h3>
<p>Go has a rudimentary mark-sweep garbage collector, but there are plans to improve that. One of the boons of having garbage collection is that you completely sidestep entire classes of memory related bugs. It also means you don't have to write the code to deal with memory management. In the context of Go being a language that embraces parallelism, garbage collection means that you can avoid worrying about cleaning up allocated memory.</p>
<h3>Concurrency</h3>
<p>In today's world of multi-core processors, concurrent programming is becoming increasingly relevant. The Go authors recognized this and designed Go for use in writing concurrent programs. Go embodies a different philosophy of concurrency than most systems languages:</p>
<blockquote><p><em>Do not communicate by sharing memory; instead, share memory by communicating.</em></p></blockquote>
<p>Go offers two primitives to accomplish this sharing by communication: <em>goroutines</em> and <em>channels</em>.</p>
<h4>Goroutines</h4>
<p>Goroutines are functions executing in parallel with other goroutines. The Go runtime manages parallelizing all of the goroutines using operating system primitives. They are light-weight and easy to use.</p>
<blockquote>
<pre>go doSomething(); // Do something, but do not wait for it to complete</pre>
</blockquote>
<p>You can even pass an anonymous function literal:</p>
<blockquote>
<pre>go func() {
  time.Sleep(5);
  fmt.Prinln("Hello World");
}();</pre>
</blockquote>
<h4>Channels</h4>
<p>With goroutines, executing functions in parallel is easy. However we still need a mechanism for communicating between them. That's what channels are for. Channels provide a synchronized, type-safe way to communicate values from one goroutine to another.</p>
<blockquote>
<pre>ch := make(chan int); // unbuffered channel of integers

go func() {
  result := 0;
  for i := 0; i &lt; 1000000; i++ {
    result += i;
  }
  ch &lt;- result;
}();

/* Do something else for a while */

sum := &lt;-ch;
fmt.Println(sum);</pre>
</blockquote>
<p>The above example shows how channels can be used to communicate between two goroutines, and it also shows how they can be synchronized. The binary send operation will block until another goroutine receives the value, and the unary receive operation will block until another goroutine sends a value. So a channel can be used as a simple way to synchronize a goroutine.</p>
<blockquote>
<pre>ch := make(chan bool);
go func() {
  /* do some stuff */
  ch &lt;- true;
}();
&lt;-ch; // strobe the channel to synchronize</pre>
</blockquote>
<h2>What's not there?</h2>
<p>Some things are absent from Go (at least for now), including generics, exceptions, and assertions. Generics and exceptions might be added in the future, when an acceptably clean and efficient design is devised.  Keep in mind that Go is meant for system programming.  Efficiency is important, and language features such as generics and exceptions have non-trivial runtime performance implications.  Go is not a kitchen sink language—it is designed for a fairly specific use.</p>
<h2>Conclusions</h2>
<p>Go is extremely easy to dive into. There are a minimal number of fundamental language concepts and the syntax is clean and designed to be clear and unambiguous.</p>
<p>Go <strong>is</strong> still experimental and still a little rough around the edges. For example, if a function has a return value, and it returns from every branch of execution, it will still complain if it doesn't return from the end of the function.</p>
<p>That said, Go allows you to do Pascal style return values where you give the result a name, assign to it, and use it in computation. However, you still have to put the return keyword at the end.</p>
<p>The only typing is duck typing. To Rubyists, this is a great thing.</p>
<p>As Carl Lerche comments, "It's not production quality yet, but there's enough that it's interesting to explore."</p>
<hr /><em>This post was co-authored by Sam Tesla.</em>
<p><a href="http://www.engineyard.com/blog"><img height="98" width="61" title="logo-engineyard" alt="" class="attachment-post-thumbnail wp-post-image" src="http://www.engineyard.com/blog/wp-content/uploads/logo-engineyard.png"/></a></p>
]]></description>
		<wfw:commentRss>http://www.engineyard.com/blog/2009/ready-set-go/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>15 Expert Tips for Using Cucumber</title>
		<link>http://www.engineyard.com/blog/2009/15-expert-tips-for-using-cucumber/</link>
		<comments>http://www.engineyard.com/blog/2009/15-expert-tips-for-using-cucumber/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 18:00:55 +0000</pubDate>
		<dc:creator>Dave Astels</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Webrat]]></category>

		<guid isPermaLink="false">http://www.engineyard.com/blog/?p=1460</guid>
		<description><![CDATA[<p>Here we are: the 3rd and final post in my series on Cucumber. Check out the LazyWeb in action:  I put out calls for 'Cucumber Best Practices' and received an assortment of responses—thanks to everyone who contributed! After collecting and reviewing all the responses, I've come up with a list of 15 expert tips you want to keep in mind when working with Cucumber.</p>
<p>In retrospect, I don't really like the term <em>Best Practice</em>—the value of most practices is very much context dependent.  That said, some ways of doing things are just generally better than others, so here are some of those good things to keep in mind.  I'll comment briefly on each one.</p>
<p><span id="more-1460"></span></p>
<h2>1. Feature Files Should Actually be <em>Features</em>, Not Entire Portions of an App</h2>
<p>One feature per well named file, please, and keep the features focused.</p>
<h2>2. Avoid Inconsistencies with Domain Language</h2>
<p>You'll get the most benefit out of using Cucumber when your customers are involved.  To that end, make sure you use their domain language when you write stories.  The best course of action is to have them involved in writing the stories.</p>
<h2>3. Organize Your Features and Scenarios with the Same Thought You Give to Organizing Your Code</h2>
<p>One useful way to organize things is by how fast they run. Use 2-3 levels of granularity for this:</p>
<ul>
<li><strong>Fast</strong>: scenarios that run very fast, e.g. under 1/10 of a second</li>
<li><strong>Slow</strong>: scenarios that are slower but not painfully so, maybe under one second each</li>
<li><strong>Glacial</strong>: scenarios that take a really long time to run</li>
</ul>
<p>You can do this separation several different ways (and even some combination):</p>
<ul>
<li>Put them in separate features</li>
<li>Put them in separate subdirectories</li>
<li>Tag them</li>
</ul>
<h2>4. Use Tags</h2>
<p>Tags are a great way to organize your features and scenarios in non functional ways.  You could use @small, @medium and @large, or maybe @hare, @tortoise, and @sloth.  Using tags let you keep a feature's scenarios together structurally, but run them separately. It also makes it easy to move features/scenarios between groups, and to have a given feature's scenarios split between groups.</p>
<p>The advantage of separating them this way is that you can selectively run scenarios at different times and/or frequencies, i.e. run faster scenarios more often, or run really big/slow scenarios overnight on a schedule.</p>
<p>Tagging has uses beyond separating scenarios into groups based on how fast they are:</p>
<ul>
<li>When they should be run: on @checkin, @hourly, @daily</li>
<li>What external dependencies they have: @local, @database, @network</li>
<li>Level: @functional, @system, @smoke</li>
<li>Etc.</li>
</ul>
<h2>5. Use Rake Tasks to Run Features</h2>
<p>This provides a consistent environment for running features: this way each run uses the same set of options and parameters.  This goes a long way toward maintaining deterministic results.</p>
<p>Another benefit is that this makes for easy integration with continuous integration tools.  There is a single point of entry into the spec run, with all options/parameters encapsulated.<!--more--></p>
<h2>6. Don't Get Carried Away with Backgrounds (Stick to Givens)</h2>
<p>The larger the background, the greater the load of understanding for each scenario.  Scenarios that contain all the details are self-contained and as such, can be more understandable at a glance.</p>
<h2>7. Make Scenarios Independent and Deterministic</h2>
<p>There shouldn't be any sort of coupling between scenarios.  The main source of such coupling is state that persists between scenarios.  This can be accidental, or worse, by design. For example one scenario could step through adding a record to a database, and subsequent scenarios depend on the existence of that record.</p>
<p>This may work, but will create a problem if the order in which scenarios run changes, or they are run in parallel.  Scenarios need to be completely independent.</p>
<p>Each time a scenario runs, it should run the same, giving identical results. The purpose of a scenario is to describe how your system works.  If you don't have confidence that this is always the case, then it isn't doing its job.  If you have non-deterministic scenarios, find out why and fix them.</p>
<h2>8. Write Scenarios for the Non-Happy-Path Cases As Well</h2>
<p>Happy path tests are easy; edge cases and failure scenarios take more thought and work.  Here's where having some good (and yet pathological) testers on the team can reap rewards.</p>
<p>Use rcov with your full Cucumber runs to find holes in coverage. Definitely check out <a href="http://wiki.github.com/aslakhellesoy/cucumber/using-rcov-with-cucumber-and-rails">Aslak Hellesoy's</a> thoughts on the matter for more details.</p>
<h2>9. Be DRY: Refactor and Reuse Step Definitions</h2>
<p>Especially look for the opportunity to make reusable step definitions that are not feature specific.  As a project proceeds, you should be accumulating a library of step definitions.  Ideally, you will end up with step definitions that can be used across projects.</p>
<h2>10. Use a Library (Such as Chronic) for Parsing Time in Your Step Definitions</h2>
<p>This allows you to use time in scenarios in a natural way.  This is especially useful for relative times.</p>
<pre>Background:
  Given a user signs up for a 30 day account

Scenario: access before expiry
  When they login in 29 days
  Then they will be let in

Scenario: access after expiry
  When they login in 31 days
  Then they will be asked to renew</pre>
<h2>11. Revisit, Refactor, and Improve Your Scenarios and Steps</h2>
<p>Look for opportunities to generalize your steps and reuse them.  You want to accumulate a reusable library of steps so that writing additional features takes less and less effort over time.</p>
<h2>12. Refactor Language and Steps to Reflect Better Understanding of Domain</h2>
<p>This is an extension of the previous point; as your understanding of the domain and your customer's language/terminology improves, update the language used in your scenarios.</p>
<h2>13. Use Compound Steps to Build Up Your Language</h2>
<p>Compound steps (calling steps from steps) can help make your features more concise while still keeping your steps general—just don't get too carried away. For example:</p>
<pre>Given /^the user (.*) exists$/ do |name|
  # ...
end

Given /^I log in as (.*)$/ do |name|
  # ...
end

Given /^(.*) is logged in$/ do |name|
  Given "the user #{name} exists"
  Given "I log in as #{name}"
end</pre>
<h2>14. Use Parallel Step Definitions to Support Different Implementations for Features</h2>
<p>For example, running features against Webrat and Selenium.  Put these step definitions somewhere where they won't be auto-loaded, and require them from the command line or rake task.</p>
<h2>15. Avoid Using Conjunctive Steps</h2>
<p>Each step should do <em>one</em> thing.  You should not generally have step patterns containing "and."  For example:</p>
<pre>Given A and B</pre>
<p>should be split into two steps:</p>
<pre>Given A
And B</pre>
<h2>In Closing...</h2>
<p>When I put out a call on Twitter, along with some of the above, I got the following:</p>
<ul>
<li>Sliced, w/tomatoes, red onion, balsamic vinegar, olive oil, salt and pepper.</li>
<li>Get the kind without seeds, they stay good longer, and mix with a bit of rice vinegar to play the "flavors that mix well" game</li>
<li>slice. add humus. add bread.  eat.</li>
<li>Eat them freshly picked out of an organic garden!</li>
</ul>
<p>There are numerous ways to best utilize Cucumber and to improve your general Cucumber practices; the above list is by no means all inclusive. If you've got a great tip I missed, leave a comment—I'm always looking to learn and improve :)
<p><a href="http://www.engineyard.com/blog"><img height="98" width="61" title="logo-engineyard" alt="" class="attachment-post-thumbnail wp-post-image" src="http://www.engineyard.com/blog/wp-content/uploads/logo-engineyard.png"/></a></p>
]]></description>
		<wfw:commentRss>http://www.engineyard.com/blog/2009/15-expert-tips-for-using-cucumber/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Cucumber: More Advanced</title>
		<link>http://www.engineyard.com/blog/2009/cucumber-more-advanced/</link>
		<comments>http://www.engineyard.com/blog/2009/cucumber-more-advanced/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 13:31:23 +0000</pubDate>
		<dc:creator>Dave Astels</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.engineyard.com/blog/?p=1353</guid>
		<description><![CDATA[<p>In a <a href="http://www.engineyard.com/blog/2009/cucumber-introduction/" target="_blank">previous post</a>, I gave you some introductory information on Cucumber, a great framework for writing and executing high level descriptions of your software’s functionality. In this post, I'll take a deeper dive and talk about a few more advanced Cucumber topics: project structures, multiple language support, scenario tables, free-form stories, tags, hooks and backgrounds. As always, for more detailed information see the <a href="http://wiki.github.com/aslakhellesoy/cucumber">documentation</a> and/or <a href="http://www.pragprog.com/titles/achbd/the-rspec-book" target="blank">The RSpec Book</a>.</p>
<h2>Project Structure</h2>
<p>Let's start by taking a look at your project structure: the usual advice is to have a <code>features</code> directory as the root of your Cucumber work. In that directory, you place all of your <code>.feature</code> files which contain your features (as you would expect) as well as <code>support</code> and <code>step_definitions</code> directories.</p>
<p>The <code>support</code> directory should contain whatever support code your features need, and an <code>env.rb</code> file which is responsible for loading any required code that lives outside the <code>feature</code> directory tree.</p>
<p>In the <code>step_definitions</code> directory, you place the files (with <code>.rb</code> extensions) that contain your step definitions.  These will all get loaded when your features run.</p>
<p>You can have multiple subdirectories in the <code>features</code> directory for grouping features.  This allows you to run the features in a particular directory.  While this can be useful, it can be awkward in practice.  That's because (as of this writing) <code>cucumber</code> loads each ruby file (ending in <code>.rb</code>) it finds in the directory you tell it to run and, recursively, all subdirectories.  For example, consider the following tree (each <code>.rb</code> files simply has a <code>puts "x"</code> where <code>x</code> is the name of the file):</p>
<pre>features
   +- 1.rb
   +- 2.rb
   +- sub1
      +- 3.rb
   +- sub2
      +- 4.rb
      +- sub3
         +- 5.rb
         +- sub4
            +- 6.rb</pre>
<p>So when you run <code>cucumber features</code>, you get:</p>
<pre>1
2
3
4
5
6
0 scenarios
0 steps
0m0.000s</pre>
<p>but, if you run <code>cucumber features/sub2</code> you get:</p>
<pre>4
5
6
0 scenarios
0 steps
0m0.000s</pre>
<p>The issue is that features don't inherit support code or steps from parent directories unless that parent is <em>also</em> visited by Cucumber.  So if you want to run subdirectories separately and they share setup code or steps, you have to somehow duplicate that code (possibly by explicitly requiring files from up the tree).  This isn't significant, but it is a bit messy.  A better approach might be to use tags (described below).  If your features groups don't share much, then using subdirectories can work fine.</p>
<p><span id="more-1353"></span></p>
<h2>Languages</h2>
<p>In the referenced previous post I talked briefly about Cucumber's multiple language support; here's I'll show you how it's done, and how you can add your own if required.</p>
<p>The file <code>cucumber/lib/cucumber/languages.yml</code> defines the 'natural language' support of Cucumber.  This is a yaml file that provides multi-lingual aliases for Gherkin keywords.  As an example, here's the entries for English, LOLZ, and Japanese:</p>
<pre>"en":
  name: English
  native: English
  encoding: UTF-8
  feature: Feature
  background: Background
  scenario: Scenario
  scenario_outline: Scenario Outline
  examples: Examples|Scenarios
  given: Given
  when: When
  then: Then
  and: And
  but: But
  space_after_keyword: true
"en-lol":
  name: LOLCAT
  native: LOLCAT
  encoding: UTF-8
  feature: OH HAI
  background: B4
  scenario: MISHUN
  scenario_outline: MISHUN SRSLY
  examples: EXAMPLZ
  given: I CAN HAZ
  when: WEN
  then: DEN
  and: AN
  but: BUT
  space_after_keyword: true
"ja":
  name: Japanese
  native: 日本語
  encoding: UTF-8
  feature: フィーチャ|機能
  background: 背景
  scenario: シナリオ
  scenario_outline: シナリオアウトライン|シナリオテンプレート|テンプレ|シナリオテンプレ
  examples: 例|サンプル
  given: 前提
  when: もし
  then: ならば
  and: かつ
  but: しかし|但し
  space_after_keyword: false</pre>
<p>To see what languages are available in the version of Cucumber you have, issue the following command:</p>
<pre>cucumber --language help</pre>
<p>If your desired language isn't supported, clone aslakhellesoy/cucumber and add it.  If you do, please send aslakhellesoy a pull request to have it considered for inclusion.</p>
<p>To run features written in a specific language, use the <code>--language</code> flag followed by the 2 (or so) letter abbreviation of the desired language. For example:</p>
<pre>cucumber --language ja</pre>
<p>Whenever I'm talking about Gherkin keywords, I'll use the English form. Everything said applies to any language version.</p>
<h2>Free-form Story/Text</h2>
<p>As mentioned in the intro post, following the feature header, you can have any amount of free-form text.  This is generally used to give further background or explanation of the feature.  Here's an example from The RSpec Book:</p>
<pre>Feature: code-breaker submits guess
  The code-breaker submits a guess of four colored
  pegs. The mastermind game marks the guess with black
  and white "marker" pegs.
  For each peg in the guess that matches color
  and position of a peg in the secret code, the
  mark includes one black peg. For each additional
  peg in the guess that matches the color but not
  the position of a color in the secret code, a
  white peg is added to the mark.
  Scenario Outline: submit guess
  ...</pre>
<h2>Scenario Outlines and Example Tables</h2>
<p>Sometimes you will have a collection of scenarios that are structurally all the same, differing only in some set of values.  It might be nice to represent these as a table. In fact, the FIT project is aimed at doing just this.  However, it can be nice to use a single tool to solve a given class of problem, and so Cucumber supports this style of testing.</p>
<p>There are two pieces to this capability.  First is the definition of the scenario outline.  This is a skeleton of the scenario, written with placeholders for the actual values.  Continuing on from the previous feature:</p>
<pre>Scenario Outline: submit guess
  Given the secret code is &lt;code&gt;
  When I guess &lt;guess&gt;
  Then the mark should be &lt;mark&gt;</pre>
<p>This is very similar to a regular scenario definition, with two exceptions.  First, you use <code>Scenario Outline:</code> instead of <code>Scenario:</code>.  This is what informs the system that you want to do a tabular style scenario. The second difference is the use of placeholders, e.g. <code>&lt;guess&gt;</code>.</p>
<p>The second piece is a data table (or tables).  These start with the <code>Scenarios:</code> or <code>Examples:</code> keyword. Following the keyword is a textual description of the data in the table. Then we have a table header that serves to map the columns to the placeholders in the scenario. Following that is the data for each case the scenario should be applied to, one per line. Table cells are bracketed by vertical bars (i.e <code>|</code>):</p>
<pre>Scenarios: all colors correct
| code    | guess   | mark |
| r g y c | r g y c | bbbb |
| r g y c | r g c y | bbww |
| r g y c | y r g c | bwww |
| r g y c | c r g y | wwww |
Scenarios: 3 colors correct
| code    | guess   | mark |
| r g y c | w g y c | bbb  |
| r g y c | w r y c | bbw  |
| r g y c | w r g c | bww  |
| r g y c | w r g y | www  |
Scenarios: 2 colors correct
| code    | guess   | mark |
| r g y c | w g w c | bb   |
| r g y c | w r w c | bw   |
| r g y c | g w c w | ww   |
Scenarios: 1 color correct
| code    | guess   | mark |
| r g y c | r w w w | b    |
| r g y c | w w r w | w    |</pre>
<p>Any number of scenario tables can be used, and all apply to the most recent scenario outline.  This results in far less copy/paste and the associated potential for error, as well as being a far more concise format.</p>
<h2>Tags</h2>
<p>In the simplest case, Cucumber runs all the scenarios in all the features that you point it at.  By using tags you can be more specific about what is run.  In my opinion, this is a killer feature.  You tag features or scenarios by prefixing them with one or more tags, separated by spaces.  A tag is simply an identifier prefixed by <code>@</code>. For example:</p>
<pre>@billing @annoy
Feature: Verify billing
  @important
  Scenario: Missing product description
  Scenario: Several products</pre>
<p>To run features and/or scenarios with specific tags you use the <code>--tags</code> command line flag and provide a comma separated list of tags.  Specifying a feature with a tag runs all scenarios in the feature.  Here's a couple of examples based on the above code:</p>
<pre>cucumber --tags @billing            # Runs both scenarios
cucumber --tags @important          # Runs the first scenario</pre>
<p>You can also specify tags <strong>not</strong> to run, like so:</p>
<pre>cucumber --tags ~@important         # Runs the second scenario (Scenarios without @important)
cucumber --tags ~@important,~@other # Won't run tasks tagged @important or @other.</pre>
<h2>Hooks</h2>
<p>Cucumber provides the ability to supply hooks to modify the behavior of executing features. Hooks can be used at the various levels of granularity, generally before and after, and are often defined in your env.rb file.  Hooks are executed whenever the event they are defined for occurs.</p>
<h3>Global Hooks</h3>
<p>Global hooks run when Cucumber begins and exits.  Begin hooks are informal: simply put the desired code in a file in the <code>features/support</code> directory (possibly <code>env.rb</code>, but I'd advise keeping it separate).</p>
<p>An exit hook is more formal, using <code>at_exit</code>.  Here's an example of a pair of global hooks:</p>
<pre>#the begin 'hook'
my_heavy_object = HeavyObject.new
my_heavy_object.do_it
at_exit do
  my_heavy_object.undo_it
end</pre>
<h3>Scenario Hooks</h3>
<p>You can add blocks that will run before and after each scenario:</p>
<pre>Before do
  # Do something before each scenario.
end
After do |scenario|
  # Do something after each scenario.
end</pre>
<p>The After block will be passed the scenario that just ran.  You can use this to inspect its result status by using the <code>failed?</code>, <code>passed?</code> and <code>exception</code> methods. For example:</p>
<pre>After do |scenario|
 if(scenario.failed?)
    subject = "[Project X] #{scenario.exception.message}"
    send_failure_email(subject)
  end
end</pre>
<h3>Step Hooks</h3>
<p>Cucumber gives you the ability to define a block that will be executed after each (and every) step:</p>
<pre>AfterStep |scenario| do
  # Do something after each step.
end</pre>
<h3>Tagged Hooks</h3>
<p>If you've tagged some of your scenarios, you can also tag scenario and step hooks. You simply pass the tags as arguments to the hook methods). These tagged hooks will only be executed before/after scenarios that are tagged the same and after steps in scenarios tagged the same.  Here's an example where the hooks will only be run before scenarios tagged with <code>@cucumis</code> or <code>@sativus</code>.</p>
<pre>Before('@cucumis', '@sativus') do
  # Do something before scenarios tagged @cucmis or @sativus
end
AfterStep('@cucumis', '@sativus') do
  # Do something after steps tagged @cucmis or @sativus
end</pre>
<h2>Background</h2>
<p>A <code>Background</code> is very much like a scenario in that it consists of a series of steps.  The difference is that its steps are executed before the steps of each scenario in the feature. It's basically a factoring out of a set of common lead-in steps for the features scenarios.  One thing to remember is that a <code>Background</code> is run <strong>after</strong> any <code>Before</code> hooks.</p>
<p>You'll generally only have <em>given</em> Backgrounds.  Here's an example:</p>
<pre>Feature: User Login
  Background:
    Given account 'A123' for 'Dave' with password '123'
    And account 'B456' for 'Joe' with password 'abc'
  Scenario: Dave logs in and sees his account
    When I log in as 'Dave' using password '123'
    Then I am in account 'A123'
  Scenario: Jow logs in and sees his account
    When I log in as 'Joe' using password 'abc'
    Then I am in account 'B456'</pre>
<h2>Summary</h2>
<p>So that's a quick look at some of the more advanced features of Cucumber.  It's a great tool, with a growing community behind and around it.  I'll be posting on Cucumber Best Practices next time, so keep an eye out. Enjoy, and comment with any questions!
<p><a href="http://www.engineyard.com/blog"><img height="98" width="61" title="logo-engineyard" alt="" class="attachment-post-thumbnail wp-post-image" src="http://www.engineyard.com/blog/wp-content/uploads/logo-engineyard.png"/></a></p>
]]></description>
		<wfw:commentRss>http://www.engineyard.com/blog/2009/cucumber-more-advanced/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Introduction to BDD with Cucumber</title>
		<link>http://www.engineyard.com/blog/2009/cucumber-introduction/</link>
		<comments>http://www.engineyard.com/blog/2009/cucumber-introduction/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 14:00:38 +0000</pubDate>
		<dc:creator>Dave Astels</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[Lolcode]]></category>
		<category><![CDATA[LOLZ]]></category>
		<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://www.engineyard.com/blog/?p=1324</guid>
		<description><![CDATA[<p><a rel="nofollow" href="http://cukes.info/">Cucumber</a> is a framework for writing and executing high level descriptions of your software’s functionality.  Call these tests, examples, specifications, whatever... it doesn’t matter too much. What I'm talking about has traditionally been called functional, integration, and/or system tests.  In XP terms this includes tests called Story Tests, Customer Tests, and/or Acceptance Tests.</p>
<p>One of Cucumber's most compelling features is that it provides the ability to write these descriptions using plain text in your native language.  Cucumber’s language, Gherkin, is usable in a growing variety of human languages, including <a rel="nofollow" href="http://lolcode.com/">LOLZ</a>. The advantage of this is that these feature descriptions can be written and/or understood by non-technical people involved in the project.</p>
<p>One important thing to keep in mind is that Cucumber is NOT a replacement for RSpec, test/unit, etc.  It is not a low level testing/specification framework.</p>
<p>Cucumber plays a central role in a development approach called <a rel="nofollow" href="http://behaviour-driven.org/">Behaviour Driven Development</a> (BDD).</p>
<h4>A Bit About BDD</h4>
<p>Dan North describes BDD as “writing software that matters” [in <a rel="nofollow" href="http://www.pragprog.com/titles/achbd/the-rspec-book">The RSpec Book</a>] and outlines 3 principles:</p>
<ol>
<li><strong>Enough is enough</strong>: do as much planning, analysis, and design as you need, but no more.</li>
<li><strong>Deliver stakeholder value</strong>: everything you do should deliver value or increase your ability to do so.</li>
<li><strong>It’s a behavior</strong>: everyone involved should have the same way of talking about the system and what it <em>does</em>.</li>
</ol>
<p>BDD in its grandest sense is about communication and viewing your software as a system with behaviour.  BDD tools such as RSpec and Cucumber strive to enable you to describe the behavior of your software in a very understandable way:  understandable to everyone involved.<span id="more-1324"></span></p>
<h4>Features</h4>
<p>A feature is something that your software does (or should do), and generally corresponds to a user story and a way to tell when it’s finished and that it works.</p>
<p>The general format of a feature is:</p>
<blockquote>
<pre>Feature: &lt;short description&gt;
  &lt;story&gt;
  &lt;scenario 1&gt;
  ...
  &lt;scenario n&gt;</pre>
</blockquote>
<p>Within the definition of a feature you can provide a plain text description of the story.  You can use any format for this, but having some sort of template makes it easier to see the important bits of information with a quick glance.  Once of the more common template is discussed by Mike Cohn [in <a rel="nofollow" href="http://www.mountaingoatsoftware.com/books/2-user-stories-applied">User Stories Applied</a>]:</p>
<blockquote>
<pre>As a &lt;role&gt;
I want &lt;feature&gt;
so that &lt;business value&gt;</pre>
</blockquote>
<p>This format focuses us on three important questions:</p>
<ul>
<li> Who’s using the system?</li>
<li> What are they doing?</li>
<li> Why do they care?</li>
</ul>
<p>Here’s a sample story:</p>
<blockquote>
<pre>As a code-breaker
I want to start a game
So that I can break the code</pre>
</blockquote>
<p>That defines who the user is <em>(a code-breaker)</em>, what they want to do <em>(start a game)</em> and why <em>(be able to break the code)</em>.<!--more--></p>
<h4>Scenarios</h4>
<p>A feature is defined by one or more scenarios.  A scenario is a sequence of steps through the feature that exercises one path.  Cucumber uses the BDD style that Dan North put forth with his jBehave project: <em>given</em>-<em>when</em>-<em>then</em>.</p>
<p>A scenario is made up of 3 sections related to the 3 types of steps:</p>
<ol>
<li> <strong><em>Given</em></strong>: This sets up preconditions, or context, for the scenario.  It works much like the <code>setup</code> in xUnit and <code>before</code> blocks in RSpec.</li>
<li> <strong><em>When</em></strong>: This is what the feature is talking about, the action, the behaviour that we’re focused on.</li>
<li> <strong><em>Then</em></strong>: This checks postconditions… it verifies that the right thing happen in the <em>When</em> stage.</li>
</ol>
<p>The general form of a scenario is:</p>
<blockquote>
<pre>Scenario: &lt;description&gt;
  &lt;step 1&gt;
  …
  &lt;step n&gt;</pre>
</blockquote>
<p>Following our example, here’s a scenario:</p>
<blockquote>
<pre>Scenario: start game
  Given I am not yet playing
  When I start a new game
  Then the game should say “Welcome to CodeBreaker”
  And the game should say “Enter guess:”</pre>
</blockquote>
<p>One thing to note is the last line.  Notice the <em>And</em>.  <em>And</em> can be used in any of the three sections.  It serves as a nice shorthand for repeating the <em>Given</em>, <em>When</em>, or <em>Then</em>. And stands in for whatever the most recent explicitly named step was: <em>Given</em>, <em>When</em>, or <em>Then</em>. The last two lines above could have been:</p>
<blockquote>
<pre>Then the game should say “Welcome to CodeBreaker”
Then the game should say “Enter guess:”</pre>
</blockquote>
<p>That doesn’t read nearly as well, though.  Similarly, if you want to state a negative <em>Then</em> step, you can use <em>But</em> in place of <em>Then</em>, for example:</p>
<blockquote>
<pre>Then the game should say “Welcome to CodeBreaker”
But the game should not say “Save the cheerleader, save the world”</pre>
</blockquote>
<p>While there are no constraints on the number or order of steps, it is generally best to keep scenarios as simple as possible and have multiple simple scenarios.  The closer your scenarios conform to the <em>given</em>-<em>when</em>-<em>then</em> format, the better.</p>
<h4>Implementing Steps</h4>
<p>So here's our feature:</p>
<blockquote>
<pre>Feature: code-breaker starts game
  As a code-breaker
  I want to start a game
  So that I can break the code
  Scenario: start game
    Given I am not yet playing
    When I start a new game
    Then the game should say “Welcome to CodeBreaker”
    And the game should say “Enter guess:”</pre>
</blockquote>
<p>If you run that you’ll see an echo of the feature followed by (using Cucumber 0.3.11):</p>
<blockquote>
<pre>1 scenario (1 undefined)
4 steps (4 undefined)
0m0.001s
You can implement step definitions for undefined steps with these snippets:
Given /^I am not yet playing$/ do
  pending
end
When /^I start a new game$/ do
  pending
end
Then /^the game should say “Welcome to CodeBreaker”$/ do
  pending
end
Then /^the game should say “Enter guess:”$/ do
  pending
end</pre>
</blockquote>
<p>The next step (pardon the pun) is to define what each of our steps mean.  When we executed our feature with no steps defined, Cucumber gave us skeletons for the undefined steps (see above). If we put those in the file features/step_definitions/codebreaker.rb and run it again, we get:</p>
<blockquote>
<pre>1 scenario (1 pending)
4 steps (3 skipped, 1 pending)</pre>
</blockquote>
<p>As you can see from above, the basic structure of a step definition is the keyword (i.e. <em>Given</em>, <em>When</em>, or <em>Then</em>) followed by a regular expression and a block of Ruby code.  The regular expression is used to identify the desired step implementation.  The step text in scenarios is matched against the regular expressions of appropriate (i.e. <em>given</em>, <em>when</em>, or <em>then</em>) step implementations to find the one to use. When a match is found, the substrings matching any groups in the regular expression are used as arguments to the block which is then evaluated.  The result of that evaluation is discarded.  Note that these arguments are <strong>always</strong> strings.  If you need them converted to other types, it's up to you to do that conversion in the block.  These groups and parameters have knowledge of position (i.e.. group 1 is used as the first parameter, group 2 as the second, and so on).</p>
<p>Notice that the suggested steps are completely concrete.  While that is fine some of the time, you will generally want to refactor steps and make them more generic and reusable. Notice that there are two <em>then</em> step definitions that are much the same:</p>
<blockquote>
<pre>Then /^the game should say “Welcome to CodeBreaker”$/ do
end
Then /^the game should say “Enter guess:”$/ do
end</pre>
</blockquote>
<p>The difference is the string inside quotes <em>(using quotes or similar delimiters is very handy for matching the groups)</em>.  We can factor that out into a regex group:</p>
<blockquote>
<pre>Then /^the game should say “(.*)”$/ do |message|
end</pre>
</blockquote>
<p>Our <em>given</em> step could be:</p>
<blockquote>
<pre>Given /^I am not yet playing$/ do
  @game = Codebreaker::Game.new
end</pre>
</blockquote>
<p>Next is the <em>when</em> step:</p>
<blockquote>
<pre>When /^I start a new game$/ do
end</pre>
</blockquote>
<p>This might be implemented as:</p>
<blockquote>
<pre>When /^I start a new game$/ do
    @messages = @game.start
end</pre>
</blockquote>
<p>Now we have the variable <code>@messages</code> that can be used in subsequent steps.</p>
<p>Recall how we left our <em>then</em> step definition:</p>
<blockquote>
<pre>Then /^the game should say “(.*)”$/ do |message|
end</pre>
</blockquote>
<p>We can now fill this in:</p>
<blockquote>
<pre>Then /^the game should say “(.*)”$/ do |message|
  @messages.should include(message)
end</pre>
</blockquote>
<p>You can use whatever method of verification you want in the <em>then</em> steps: rspec, test/unit, shoulda, etc.  I happen to prefer RSpec.</p>
<p>Earlier I mentioned that Cucumber supports various languages including LOLZ.  Here’s a feature in LOLZ:</p>
<blockquote>
<pre>OH HAI: STUFFING
 MISHUN: CUCUMBR
    I CAN HAZ IN TEH BEGINNIN 3 CUCUMBRZ
    WEN I EAT 2 CUCUMBRZ
    DEN I HAZ 2 CUCUMBERZ IN MAH BELLY
    AN IN TEH END 1 CUCUMBRZ KTHXBAI</pre>
</blockquote>
<p>And the step implementations:</p>
<blockquote>
<pre>ICANHAZ /^IN TEH BEGINNIN (d+) CUCUMBRZ$/ do |n|
  @basket = Basket.new(n.to_i)
end
WEN /^I EAT (d+) CUCUMBRZ$/ do |n|
  @belly = Belly.new
  @belly.eat(@basket.take(n.to_i))
end
DEN /^I HAZ (d+) CUCUMBERZ IN MAH BELLY$/ do |n|
  @belly.cukes.should == n.to_i
end
DEN /^IN TEH END (d+) CUCUMBRZ KTHXBAI$/ do |n|
  @basket.cukes.should == n.to_i
end</pre>
</blockquote>
<p>And that's all there is to understanding the basics of Cucumber.
<p><a href="http://www.engineyard.com/blog"><img height="98" width="61" title="logo-engineyard" alt="" class="attachment-post-thumbnail wp-post-image" src="http://www.engineyard.com/blog/wp-content/uploads/logo-engineyard.png"/></a></p>
]]></description>
		<wfw:commentRss>http://www.engineyard.com/blog/2009/cucumber-introduction/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

