Talking testing, agility and automation... and anything else.

Mar 14

Screencast: Creating Your First Test In Geb

In this screencast, I walk you through writing your first test using Geb and Spock. We’ll create a page object and a spec (test), and then run our new test on multiple browsers.

If you’re just getting started, you might want to take a peek at my Geb Quick Start and Project Overview screencasts.

Jan 14

Spock: Test Framework With Creamy BDD Center

spock[1]Two things I’m willing to admit:

  1. I think it’s a bad idea to dismiss tools prematurely
  2. I think most BDD tools are crap

Delicious hyperbolic contradiction aside, it would probably be more accurate (and PC) to say I’ve yet to work in a situation where using tools like Cucumber or JBehave would make sense. I.e. these tools just don’t compliment my, or my team’s, workflow.

Enter Spock. Spock is a testing framework for Java/Groovy, that is very similar to JUnit, but also adds BDD-friendly specification, baked right in. With Spock, there’s no need to maintain a separate feature or spec file; no weird broken-English language to learn. Your code is the spec and the end result is clean, readable and maintainable.

Case in point: the following is a Geb test, written in Groovy and using Spock. This is working code from my geb-example project on GitHub.

This test, from my CLSearchTest class, which tests searching on Craigslist (had to use something :) ). With that in mind, the code above is probably very readable to just about anyone. I’ll break down what’s going on a bit…

We start by defining our test: 'searches with few results offer nearby results', which is also our method name. Method names are string literals (can have spaces).

Next we have Spock’s built-in code blocks, labeled given:, when: and then:. These three blocks represent the different phases of a test. Each block can also include an optional description to help with readability. A bit about each block:

  1. given: (optional): Think of this block as a setup. It gives you the optional ability to specify state.
  2. when: (required): This is where the meat of your test code will go. You can have multiple Whens and Thens but they must be used in pairs.
  3. then: (required): This block is for asserts. All code in this section must return true or your test will fail. This gives your reader an easy way to see what the test is actually testing!

This just scratches the surface of Spock’s offerings. You of course get a full boat of annotations (including my favorite, @IgnoreRest) and fixture methods, additional blocks, etc… Plus it runs anywhere JUnit runs.

Don’t get me wrong, the principals of BDD are sound but I want tools that work the way I do, not the other way around. When using Spock along with Geb’s page object pattern and selectors, and Groovy’s fabulous syntax, the resulting code is both elegant and readable. YMMV…