Tag based logic in Cucumber

Sometimes cucumber’s Before hook just doesn’t cut it. Here’s a nice hack that allows you to perform some logic during execution of cucumber scenarios when a tag is first come across:

It’s a cucumber formatter that detects when a tag is first come across. When a new tag is found, the perform_logic_for method is called, passing the tag to it. Once you’re in the perform_logic_for method, you can do what you like. I’m doing stuff like checking to see if a directory matches the tag name; if I find one, I load the data into an environment (a great example of when the Before tag isn’t enough). You have free reign in here to do what you like with the tag.

To use it, save the file to features/support/tag_logic.rb, add your own tag logic, and then execute it with:

#cucumber -f pretty -f TestManagement::TagLogic -o /dev/null

I hope that helps!

Small print:
Use the Before hook instead of this if you possibly can.

Precision Failure

When tests fail it’s nice to know why. The more precise a failure message is and the less time required to investigate why the test failed, the better.

When trying to find out what broke the test, this…

Failure/Error: search_field.should_not be_visible
       expected visible? to return false, got true

…is infinitely preferable to this…

Failure/Error: search_field.visible?.should == false
       expected: false
            got: true (using ==)

The first failure tells you that the test expected the search field to be invisible, the second that it expected true to equal false – not very helpful. I’d rather have the first error message than the second, and unless you’re a masochist you probably would like the same (though having reviewed a lot of test code, I’m not so sure…).

Cucumber and rspec make “precision failure” easy through the use of matchers. Instead of checking whether “.visible?” returns true or false, you can use rspec matchers to write the following code:

search_field.should_not be_visible
...or...
search_field.should be_visible

…instead of this:

search_field.visible?.should == false
...or...
search_field.visible?.should == true

Your test code will be more understandable, and when tests fail you’ll have a high chance of knowing exactly what went wrong.

So, go and learn about RSpec Matchers!

Step-by-step example of BDD’ing a WPF app with Cucumber, RSpec, IronRuby and Bewildr

In this tutorial, we’ll go through the BDD cycle step-by-step and develop a small Microsoft WPF app to solve a contrived problem. We’ll go through how to specify the desired features in cucumber, how to implement the steps in ironruby using bewildr to automate the UI, how to use rspec from ironruby to do the unit testing, we’ll write the C# code to pass the unit tests, and the WPF to create a UI to pass the cucumber scenarios! Get comfortable – this may take some time…

Things I’m going to assume

  • You know enough C# to write a simple WPF GUI
  • You know enough ruby, rspec and cucumber to automate some basic tests
  • You have a reasonable grasp of the concepts behind BDD and TDD
  • The following code will all be done in c:\wpfbdd

Ingredients

You will need the following installed…

With that, we are ready to BDD some WPF!

Introducing the Problem
Software exists to solve problems. What’s the problem that our contrived little app needs to solve? It’s time to jump into tutorial-scenario-land where everything is nice’n'easy and problems are well defined…

Farmer Giles has a flock of sheep that he moves from field to field. If any of the flock get left behind, they’ll get eaten by the Big Bad Wolf, which Farmer Giles would find sad and costly. What he wants is some way to keep track of his sheep as he moves them all from one field to the next to make sure that he hasn’t left any stragglers behind.

It’s time for a cucumber feature file
Hmmm… that’s enough material to start with. It’s time to begin writing our feature file. Here it is:

Save that to features\sheep_counter.feature. We have a conversation with Farmer Giles and he’s happy that we seem to have a general idea of what he wants. Next, we need to add some scenarios to our feature file. After a bit more chatting with Giles we decide that what he wants is a sheep counter, and these are the scenarios we come up with:

OK, now we’re getting somewhere. Giles is happy for us to build a sheep counter and we’ve got a few scenarios of how he’d like to use it… it’s time to start writing the step definitions!

Filling in the Step Definitions
Before we fill in the step definitions, we’ll quickly create the features\support\env.rb file with the following contents:

Now that bewildr has been added to the project, we can go ahead and create the features\step_definitions\sheep_counter_steps.rb file with the following contents:

If you’re struggling to keep up, those are the code blocks that will get called when you run the icucumber command (NB: that’s icucumber, not cucumber). Before you run icucumber, take the time to bask in the beauty that is the bewildr API displayed in the above steps… Enjoyed that? Good. Bask a bit more. And again. Hmmm… that’ll probably do. Back to work. Run the icucumber command, and take a look at the output:

Ugly. There’s a theme in the ugliness though. Here is the problem that’s causing the scenarios to fail:

Can't find: c:\wpfbdd\SheepCounter\SheepCounter\bin\Debug\SheepCounter.exe (RuntimeError)

That’s an error from bewildr telling us that it can’t find SheepCounter.exe. Well, that’s no big surprise given that it doesn’t exist! We now need to start writing some code to make these scenarios go green.

Our first bit of production ‘stuff’!
It’s time to break open Visual Studio and create a new project of type “WPF Application”. Name the project “SheepCounter” and save it to c:\wpfbdd. You’ll be greeted with a window something like this:

We’ll get to the code in a minute, just “Start Debugging” the new WPF project. That should be enough to compile it and get a blank WPF window displayed. Close the WPF window and go back to your command prompt and give icucumber another go. This time, you’ll see that the scenarios are opening the app, but then fail with ElementDoesntExist errors. Here’s the console output you should be getting now:

So, the scenarios are still all failing, but at least our new SheepCounter.exe is opening. But… it’s opening one instance per test and leaving them around. We need to change things so that the app gets closed at the end of the test. We need to update our features\support\env.rb file to include an After block:

If you run icucumber again you’ll notice that though the scenarios still fail, at least the SheepCounter app is being tidied up at the end of each test.

We’ll do a final bit of tidying up ourselves and rename our WPF window from “MainWindow” to “Sheep Counter” (it’s the window’s “Title” property that you need to change). When you’ve done that, run the WPF app again to verify that the window name has changed.

Now that the WPF app’s window has the correct title, the first of our step definitions should pass. Run icucumber again and you should see the following console output:

Better! The first step of each scenario is now passing.

This is where BDD/TDD really shine. You decide what you want your app to do, you express the desired behaviour in scenarios and then implement just enough production stuff to make the scenarios pass. When they do, you can stop coding in the knowledge that your software behaves the way you wanted it to!

First attempt at implementing the UI
From executing our scenarios we know that the app is starting up. But as soon as it starts, the scenarios fail because they can’t find the various UI elements that are mentioned in the step definitions. We need to go through the step definitions and add any UI elements they mention to the WPF UI.

As a minimum you need to add a label whose name is ‘sheep_count’ and a button whose name is ‘increment_sheep’. Here’s what I’ve got at this point (note, I’ve given the button some content and I’ve got an extra label with the contents “Sheep Count:”, just to make the app a litte more pretty and little less utilitarian):

Run the WPF app again (in debug mode) to make sure that all the elements are there (this will also compile the app so that the scenarios are dealing with the latest changes). Now kill the app and run icucumber again…

… the first two scenarios will run (and fail) but on the third test, it’ll get stuck in an infinite loop – the step is expecting the sheep count to increment every time the increment button is clicked, but we haven’t implemented that yet. Simply close the WPF window and the scenario will end. Your console output should now be something like:

Progress! We are now getting logic errors rather than UI errors, eg: the scenarios are complaining that they were expecting the label to contain “0″, but it got “Label” instead. When you get to this sort of point, it’s usually time to start writing some unit tests…

A Rake intermission…
Just before we get started with unit testing, we’ll add a Rakefile to our project. Rake is a great tool for managing project tasks, and since we’re going to be adding another one when we add unit tests, we may as well involve rake right now. Add a file called ‘Rakefile’ in your project root with the following contents:

All done. Now, instead of running icucumber to run our acceptance tests, we run irake cucumber. The task we’ll use to run our unit tests is irake spec.

Some unit tests…
It’s time to break out rspec and use it to design an object that can keep track of sheep for us – we of course don’t want this logic in the UI code, we need to separate it out. We need to create a c:\wpfbdd\spec directory to contain our unit tests. Once done, add a file named spec\counter_spec.rb. Now go ahead and run irake spec and you should get the following output:

It’s just telling us that we have no tests.

So what are we designing with our unit tests? The class that will manage the count of sheep as they move from field to field. Since we’re in tutorial-scenario-land, this is nice and easy. We need a class that basically keeps track of a count. It needs to start at 0, it needs to increment. That’s pretty much it for now. So we’ll start by adding a few pending tests to our spec file:

When you run that, you’ll see mentions of pending tests:

Next, we’ll write the first test:

…and when we run that with irake spec we get the following output:

So we’re finally at the stage where the test is failing for a proper reason – the dll that we want to test doesn’t yet exist. To get things working, we need to…

Add a Counter project in VS
We now need to fire up Visual Studio, and add a new ‘Class Library’ project to the solution; we’ll call the project ‘Counter’. The pre-defined class in the new Counter project is called ‘Class1.cs’. Rename that to ‘Counter.cs’. You should see something like this:

If you debug the project (to compile our new class) and then run the tests, you should now get the following obtuse error:

The key bit of info from that fail is the following: undefined method `count' for Counter.Counter:Counter::Counter. The class that we’re testing needs a count() method. So let’s add one:

Now, after debugging (to compile the new code), run the tests, and you should get:

That’s our first test passing! The C# code we added now returns the count, and starts the count at 0 when the Counter.cs class is initialized.

It’s time to move on to our next test. We now need to be able to increment the count, so we’ll add the following test code:

…and if we run that, we get the following:

…which tells us that we need an increment method. We’ll update the Counter.cs with the following:

…and after debugging the code, the tests will produce the following output:

See those 2 dots? Both our tests are passing!!! We now have the confidence that our Counter.cs class does enough to power the SheepCounter UI!

Wiring up the Counter class to the WPF UI
Before dealing with the UI, we need to add a project reference from the ‘SheepCounter’ WPF project to the ‘Counter’ Class Library project. Your Solution Explorer should look something like this:

Now that the UI project knows about the Counter class, we can update the ‘MainWindow.xaml.cs’ file with the following:

If you Debug the WPF app now, you should see that when it starts, the initial count is 0. If you run the cucumber acceptance tests (irake cucumber), you’ll find that the first test now passes! (Don’t forget about that last test that get stuck in an infinite loop – when it starts, kill it).

The test output will be something like:

The first test is now passing. We’ll move onto the second test; the one that tests the increment behaviour. To do that, first go to the WPF window layout, and double click the ‘Increment’ button you added to the UI. You should now see that the MainWindow.xaml.cs file has had an ‘increment_sheep_Click()’ method added to it. Save the project and then update the ‘MainWindow.xaml.cs’ file with the following:

Debug the project to compile it, and then run the acceptance tests (irake cucumber). You should see that all of the acceptance tests now pass!!!

The customer rejoices!!!
We find Farmer Giles, and show him our shiny new SheepCounter app. He’s very pleased, and tells us that he’ll go and use it for a few days and see how it works in the real world.

Feature request…
Farmer Giles comes back from the fields and tells us, “It’s great, this sheep counter, but there’s one annoying thing about it… Once I’ve moved all my sheep from one field to another, I have to restart the app to get the count back to 0. Could you add a feature that resets the count somehow?” “Hmmm… no problem… give us a few minutes…”

We need to add a new scenario to the feature file, update the UI to include a ‘Reset’ button, add a ‘reset()’ method to our Counter class and wire up the UI. Here goes:

Expanding the feature file
We add the following scenario to our existing ‘sheep_counter.feature’ file…

…and the following to the ‘sheep_counter_steps.rb’ file…

…and run our tests, we get the following:

Our old tests pass, but the new one fails telling us that there isn’t a reset button. So let’s add one!

Adding a Reset button
Back in VS, add a button named ‘reset’ to the UI:

After debugging the app, the new acceptance test should fail, but this time with a different problem:

… it got the wrong result. Though this time the button was found and clicked, the number didn’t get reset. We need to update our Counter class to be able to reset.

Updating the Counter class
Before updating the class, we need to add a unit test. Update the counter_spec.rb file with the following test:

Running the unit tests will give us the following result:

So there’s no ‘reset()’ method on our Counter class. Let’s add the following method to the Counter class…

…run the debugger and then run our unit tests again:

Good. All out unit tests are passing, including the new one for the reset() function.

Wiring up the reset button on the UI
The final thing we need to do is to wire up the Reset button on our WPF UI to the reset() method on the Counter class. To do this, double click on the reset button in the UI. You should see that a reset_Click() method has been added to the MainWindow.xaml.cs file. Save the project and then change the reset_Click() method to look like the following:

After debugging the update WPF app, run the acceptance tests again. You should see the following output:

Nice! Our new feature is working, and we haven’t broken anything – we know that because our other tests passed!

One happy customer!
And with that, we got Farmer Giles to spend a few days in the field with his updated SheepCounter app. He loved it – he could count his sheep as they moved from field to field, he could reset the count when he was done, and the big bad wolf died from hunger. Success!

Conclusion
I hope the above worked example, though contrived, has shown that BDD’ing a WPF app is not a big deal. The tools are easy-to-use, stable, popular and free (ironruby/cucumber/rspec/bewildr). The BDD process, though a source of contention around the interwebs, is at its core quite simple – it’s about conversations, specifying expected behaviour, writing tests first and short feedback loops. If you’re not doing it already, give BDD a go.

  • It takes a lot of the uncertainty out of coding – blind alleys are rarely ventured down because the customer is forced, by being involved in the development process – to think carefully about their requirements
  • You will make peace with your QA people – if you’re interested in the quality of your code then you’re on the same side
  • Your customer will love you – they’re getting what they need rather than what they thought they wanted
  • Maintenance will no longer be a terrifying ordeal – you’ll be happy to change code because your tests will tell you if you’ve broken anything
  • I could go on, but this isn’t the place really…

Anyway, I hope that helps!

Download the project
Click here to download the project.

Cucumber formatter for unused steps

As time goes on in a project using cucumber you’ll end up with some steps which no longer get called, and you probably want to delete them. Annoyingly, there isn’t a built-in formatter you can use to find out where they are. Sure, the ‘usage’ formatter prints off unused steps, but it prints off all the other steps too! What’s needed is a formatter that will hunt down all steps that are not being used and then print off each step’s name and its location (file location and line number).

What follows is a very basic cucumber formatter that will do just that. To use it, copy the code into a file called ‘unused.rb‘ in your ‘features/support‘ folder and then use the formatter when you run cucumber:

cucumber -d -f Cucumber::Formatter::Unused

or

cucumber -d -f Unused

Is Cucumber adding value to your project? The Chicken Test!

Don’t get me wrong – I love cucumber. I’ve been on projects where it has been used successfully and I’d partly attribute the success of those projects to the use of cucumber. It is a fantastic tool for BDD. When used right:

  • its scenarios provide a definitive specification of app functionality
  • its output provides one of the most useful metrics of progress: running passing tests
  • it gets everyone talking the same language
  • it provides a layer of abstraction between the required behavior and the app implementation (if you keep your steps declarative)
  • it helps to keep the focus on what code really needs to be written

All of this from one tool! Pretty good, huh? Well, like anything good, it comes with costs – those’ll be covered in a later post.

Whether the costs are outweighed by the benefits that cucumber can provide is dependent on how closely the customers, devs and testers are working together. The more blurred the roles of dev and test are and the more involved the customer is, the more value you’ll get from using cucumber. The further the devs are from the testers and the less involved the customer is, the less value cucumber will give you.

There comes a point where the costs of using cucumber outweigh the benefits – and that point comes along pretty quick IMHO. Most of the projects that I’ve seen using cucumber really shouldn’t be. Yes, it’s the flavor of the month. Yes, it’s what all the cool kidz are using. But it’s not a panacea. Using cucumber will not shower your project with pink unicorns or make your team collaborative. Too often I’ve seen cucumber used for CVDD/RDD instead of BDD – almost always a bad move…

Having been on quite a few projects that have used cucumber, I’ve come up with an unscientific and clumsy acid test that will show you if you should stop using cucumber and move to something with lower maintenance costs (eg: rspec/testunit/whatever). Here, in all its glory, is The Chicken Test™:

Instead of your usual feature description, try putting the following at the top of your next feature file:

Feature: [whatever feature is being written]
  As a chicken
  I want to cross the road
  In order to get to the other side

Possible results of The Chicken Test:

  • You get caught while typing - Pass. To have got caught this early you must be writing your scenarios collaboratively. Continue using cucumber.
  • You manage to get it checked in - I have a bad feeling about this… Get people talking again.
  • No one notices for a couple of days even though the scenarios are being run - Fail. If people aren’t even reading the scenarios, they’re not serving their purpose. Use rspec.
  • No one notices for a couple of months – Epic fail. Wipe that smug look off your face – you’ve made your point. The devs don’t want you testers “in the way”, so you may as well make life easier for yourself – move to rspec.

All too often, projects I’ve seen fail the chicken test. Does yours?

IronRuby vs. Gherkin – a temporary fix

IronRuby doesn’t currently work with the latest versions of cucumber. This is a known bug and is a real pain. There is a work around, and it’s kinda rubbish: don’t use any versions of cucumber > 0.6.3. After that version, Gherkin became a .c extension – and IronRuby doesn’t like .c extensions.

Keith Burnell (the .Net Dev Dude) has blogged about getting Cucumber working with IronRuby – you may want to take a look if you’re getting stuck.

Netbeans ‘Cucumber Features’ plugin in Beta!

The best ruby IDE, Netbeans, now has a Cucumber plugin in beta! It’s the old “QuBiT” plugin that I’ve been using for a while though it looks like it’s been rebranded as the “Cucumber Features” plugin. Here it is:

As well as syntax highlighting and pretty icons, the new version has the following new (to me) features:

  • right-click “Run Feature” in the editor window and the file browser window
  • Better formatting (plugin now in line with latest cucumber changes)
  • Formatting of Examples tables (killer feature for me!)

Nice! Now, if only it would provide right-click-run-scenario…

Remove junk from IronRuby cucumber output

When running cucumber tests under IronRuby, your output will be full of junk like the following:


Feature: example feature

Scenario: a scenario←[90m     # features\testoutput.feature:3←[0m
←[32mGiven some test setup←[90m  # features/step_definitions/output_steps.rb:1←[0m←[0m
←[32mWhen I do something←[90m    # features/step_definitions/output_steps.rb:5←[0m←[0m
←[32mThen something happens←[90m # features/step_definitions/output_steps.rb:9←[0m←[0m

1 scenario (←[32m1 passed←[0m)
3 steps (←[32m3 passed←[0m)
0m0.160s

This is not great. All those “[32m” things make the output difficult to read and cause (me at least) some serious distraction. Thankfully, it’s easily fixed… if you add the –no-color option when you call the icucumber command, ie:

icucumber --no-color

…the output will change to be:


Feature: example feature

Scenario: a scenario     # features\testoutput.feature:3
Given some test setup  # features/step_definitions/output_steps.rb:1
When I do something    # features/step_definitions/output_steps.rb:5
Then something happens # features/step_definitions/output_steps.rb:9

1 scenario (1 passed)
3 steps (3 passed)
0m0.260s

Much better, and easily solved!