Skip to content
This repository was archived by the owner on Nov 16, 2018. It is now read-only.

Cucumber Backgrounder

byrnejb edited this page Nov 9, 2010 · 551 revisions

Or: How I Learned to Stop Worrying and Love Testing Start Behaving

Introduction

This document deals principally with initial set up and first use of the Cucumber-Rails and Cucumber gems. It takes as its background the Ruby on Rails (RoR) web application framework. Discussion of Behaviour Driven (BDD), Test Driven (TDD), and Panic Driven Development (SNAFU aka Cowboy Coding) can be found elsewhere. Details regarding installing the Cucumber gem and its recommended support tools for RoR are found on this wiki under the heading Ruby on Rails. The article Getting Started with Rails is a useful introductory tutorial dealing with Rails and Cucumber.

Since the original version of this article appeared, Cucumber has undergone repeated revisions and re-factorings. Among these was the sensible decision to move portions of the implementation specific to particular frameworks into their own gems. Consequently, installing Cucumber for a framework now frequently starts with installing the specific framework Cucumber gem, which in turn pulls in the core Cucumber gem as a dependency. Cucumber now provides support for a wide range of Ruby VMs such as JRuby, alternative application frameworks such as Sinatra, other programming languages such as Python, test environments such as Capybara, and provides i18n language support for feature and step files. Obtaining these features may require the installation of other gems such as cucumber-sinatra.

Readers should always consider that the information contained herein may be out of date and therefore incomplete or erroneous in some respects. However, any such defects will usually be confined to specific implementation details and should not detract from the validity of the overall presentation.

Note that in this document I often use the terms testing and test where BDD practitioners prefer the terms behaviour and expectation. When I use the word test in a BDD context I am in fact discussing expressing and verifying expected behaviour.

Where to Start?


Feature: Design and Build a Ruby on Rails web app using Behaviour Driven Development (BDD)
In order to reduce rework and produce a web app at low cost and high speed
A developer 
Should employ a BDD methodology and agile tools

Scenario: Cucumber should be installed and configured
Given I have installed the gem named "rails"
  And I have installed the gem named "cucumber-rails"
  And I have generated a RoR project named "my_project"
  And the present working directory is the Rails root directory of "my_project"
  And I have the file cucumber.yml in the config directory of "my_project"
  And the file cucumber.yml contains a valid default profile

When I run "rails g cucumber"

Then I should create the directory ./features
  And I should create the file ./features/features.feature
  And I should create the directory ./features/step_definitions
  And I should create the file ./features/step_definitions/web_steps.rb
  And I should create the directory ./features/support
  And I should create the file ./features/support/env.rb
  And I should create the file ./features/support/paths.rb
  And I should create the file ./lib/tasks/cucumber.rake
  And I should create the file ./config/environments/environment cucumber.rb
  And I should create the file ./config/cucumber.yml
  And I should modify ./config/database.yml
  .  .  .

The foregoing gives a sample of the form that feature files often take, sadly. The statements, called feature steps or feature statements, make up the user interface to Cucumber testing. Those given above are written in the Imperative Style simply for illustrative purposes. Never put statements that look anything like these in a feature filebut you will ). In practice, all those Then/And statements should be subsumed into one simple Declarative Style statement. For example: I should create the Cucumber environment. The messy details of just what comprises a Cucumber environment are placed in the step definition files. Instead, a feature should look more like this:


Feature: Design and Build a Ruby on Rails web app using Behaviour Driven Development (BDD)
In order to produce a web app at low cost and high speed
A developer 
Should employ Ruby on Rails with Cucumber BDD tools

Scenario: Cucumber-Rails should be installed and configured
  Given I am in a rails project root
    And I have installed cucumber-rails
    And I do not have a cucumber environment
  When I run the cucumber-rails generator
  Then I should have a cucumber environment

We will return to how to write features and steps later. For the moment we deal with the logical arrangement of Cucumber files within the context of an RoR project. The root level of the archetypal RoR project directory tree looks like this:

MyProject
|-- README
|-- Rakefile
|-- app
|-- config
|-- db
|-- doc
|-- lib
|-- log
|-- public
|-- script
|-- test
|-- tmp
`-- vendor

Depending upon the version of Rails, running rails g cucumber or script/generate cucumber adds this layout to the existing structure:


|-- features
|   |-- step_definitions
`   |   `-- web_steps.rb
    `-- support
        |-- env.rb
        |-- hll_cuke_sample_helpers.rb
        `-- paths.rb

If you are not using Rails and Cucumber-Rails in your project then you can accomplish much the same thing by creating the directory tree from the command line (mkdir -p features/step_definitions) and simply ignoring the support directory and all of the (Rails specific) files . Once the features directory structure is in place then we are ready to begin testing with Cucumber.

Where do I put Tests?

Cucumber divides testing into two parts, the outward facing feature steps and the inward facing step definitions. Features are descriptions of desired outcomes (Then) following upon specific events (When) under predefined conditions (Given). They are typically used in conjunction with end-user input and, in some cases, may be entirely under end-user (in the form of a domain expert) control. Feature files are given the extension .feature.

Step definitions, keyed by their snippets of text from the feature scenario statements, invoke blocks of Ruby and Rails code that usually contain api methods and assertion statements from whatever test system you have installed (TestUnit, RSpec, Shoulda, etc.). Given that Cucumber evolved out of RSpec stories it is unsurprising that the Cucumber generator once assumed that RSpec was available. This has long since ceased to be the case. What Cucumber does now is detect if the RSpec gems are installed. If so then the rails generator builds the environment files to suit and if not then it ignores RSpec and configures for test-unit instead. In fact, the availability of Cucumber generator options is increasing over time. To see what is available in the version of Cucumber-Rails that you have installed use the command: rails g cucumber --help or script/generate cucumber --help.

A source of potential confusion is that the term steps, when used loosely, has two, closely related but vitally distinct, meanings depending on context. Inside feature.feature files, steps are the textual descriptions which form the body of a scenario. These are prefaced with the keywords Given, When, Then, And or But (note as well that the capitalization of these five names is significant). Inside a step_definitions.rb file, steps (which strictly speaking should always be called step definitions) refers to the matcher methods, which may be given any of the same names (Given, When, Then, And or But), each provided with a matcher regexp that corresponds to one or more feature steps. Note that the method name does NOT form part of the matcher. A Given feature clause can match a When step definition matcher. Over time, clauses from features have come to be referred to simply as features while steps now refers almost exclusively to step definitions.

As shown above, the default features directory tree is fairly shallow. One can put every feature into a single file in the features directory and every step in a single file in the steps_definition directory (or even in the features directory itself) if one so chooses. Alternatively, one can choose to have one or more feature files for each feature, together with one or more step files for each feature file, or any combination thereof. However, Cucumber is programmed with the flexibility to support a much more expressive directory structure. For instance:

|-- features
|   |-- entities
|   |   |-- entity.feature
|   |   `-- step_definitions
|   |       |-- anything.rb
|   |       `-- entity_steps.rb
|   |-- locations
|   |   |-- location.feature
|   |   `-- step_definitions
|   |       `-- location_steps.rb
|   |-- sites
|   |   `-- step_definitions
|   |-- step_definitions
|   |   |-- local_assert_steps.rb
|   |   |-- local_crud_response_steps.rb
|   |   |-- local_email_steps.rb
|   |   |-- local_file_steps.rb
|   |   |-- local_script_steps.rb
|   |   |-- local_steps.rb
|   |   |-- local_web_steps.rb
|   |   |-- local_xml_file_steps.rb
`   |   `-- web_steps.rb
    `-- support
        |-- env.rb
        |-- hll_cuke_sample_helpers.rb
        |-- local_env.rb
        `-- paths.rb

In this case the bland initial set-up has been divided into sub-directories informed by model-centric testing. This could equally well have been broken up in to model/controller/view hierarchies:

|-- features
|   |-- models
|   |   |-- entities
|   |       |-- entity.feature
|   |       `-- step_definitions
|   |           |-- anything.rb
|   |           `-- entity_steps.rb
|   |-- views
|   |   |-- entity_new
|   |   `-- step_definitions
|   |       `-- entity_new_steps.rb
|   |-- step_definitions
|   |   |-- local_steps.rb
`   |   `-- web_steps.rb
    `-- support
        |-- env.rb
        |-- hll_cuke_sample_helpers.rb
        |-- local_env.rb
        `-- paths.rb

Consider, however, that the Cucumber feature scaffold generator will generate the files it produces in conformance with the default layout, with the manage_frooble.feature file placed in ./features and the frooble_steps.rb file in ./features/step_definitions. Further, despite the behaviour of the Cucumber-Rails generator, it is considered an anti-pattern to relate step_definition files to specific feature files. As is the case for many programming suggestions there are exceptions and contrary opinions respecting this advice. Nonetheless, it is probably best to follow this recommendation at the outset and depart from it only when you are experienced enough to evaluate the trade-offs between approaches.

Also be aware that, regardless of the directory structure employed, Cucumber effectively flattens the features directory tree when running tests. By this I mean that anything ending in .rb under the start point for a Cucumber feature run is searched for feature matches. Thus, a step contained in features/models/entities/step_definitions/anything.rb can be used in a feature file contained in features/views/entity_new, providing that cucumber is invoked on a root directory common to both, ./features in this case; or explicitly required on the command line, $ cucumber -r ./features features/views/entity_new. It is also worth noting that step files can be called anything so long as they end in .rb.

How do I Write Tests?

Constructing ones first tests, or features as BDD purists prefer, is often accompanied by what can only be described as writer’s block. While detailed discussion of feature writing and step construction are provided elsewhere (see Given-When-Then and Telling a Good Story), perhaps the easiest thing to do for the first time tester/behaviourist is to use Cucumber’s built-in generator to create a feature scaffold and then modify it.

script/generate feature Frooble name color description
      exists  features/step_definitions
      create  features/manage_froobles.feature
      create  features/step_definitions/frooble_steps.rb

This might be the easiest thing to do, but not necessarily the best thing to do. Generating scaffolds provides a comforting illusion of progress through voluminous production of boilerplate code. Said code being, for all intents and purposes, worthless save only as an example of proper syntax and even the syntax is sometimes dubious. By all means take a look at the generated code to obtain some idea of how things should look when you write your own features, but do not expect your project to design itself.

Instead of simply modifying boilerplate, it proves important to write each test/feature step one at a time and in plain language. The use of plain language in the feature file is crucial to successful use of Cucumber. What does plain language mean? Basically, it comes down to stating the result that you wish to obtain while avoiding specifying how you expect to get it. For example, for an authentication scenario you should write:

When "Bob" logs in

and not:


  Given I visit "/login"
  When I enter "Bob" in the "user name" field
    And I enter "tester" in the "password" field
    And I press the "login" button
  Then I should see the "welcome" page

What is important about the difference in styles? The first example, When “Bob” logs in, is a functional requirement. The second, much longer, example is a procedural reference. Procedures belong in the implementation details.

What you and your client should concern yourselves with in your feature files is that which has to happen and not how you expect it to happen. That way, when somebody later decides that challenge and response authentication schemes are passé then you simply need change the authentication process steps behind the scenes. Your outward facing feature files, the ones that your clients get to see, need not change at all. In fact, a good question to ask yourself when writing a feature clause is: Will this wording need to change if the implementation does? If the answer is yes then the clause is poorly written and you should rework it avoiding implementation specific details. As a side benefit, in consequence your scenarios will be a lot shorter and much easier to follow and understand.

After each new feature statement is added to its scenario then you should immediately create the corresponding step definition method. This is where the implementation details are put because, in the normal course of events, your users will never see them. Once your new step definition is written then you must prove to yourself that it fails by running it against the, as yet, non-existent application code. Then, and only then, should you write the least application code that gets your test/step definition to pass. Now that you have a passing step, without changing the step definition’s logic change the test criteria within it to something that cannot be and prove to yourself that it fails again. Once you have assured yourself that your test is passing for the right reason then reset the criteria so that the test passes again. Once this cycle is complete then move on to the next feature clause. For example:


Scenario: Users can enter an invoice item
   .  .  .
   Then I enter a product quantity of 5

Now, immediately go to your step_definition file and do this:


When /enter a product quantity of (\d+)/ do |quantity|
  pending "TODO: Do we need to have a product code passed as well?"
end

Think about how you are going to express this behaviour in your application and how you can detect that it occurs. Go back and rework your feature and step until you are satisfied that it will indeed produce some testable result and that the test fails. Now, go write the code to implement this requirement in your application.

It is tempting, sometimes irresistibly so, to just skip ahead with the analysis stage alone and to complete as many features, scenarios and scenario statements as one can imagine. In some cases limited access to domain experts and end users may require that many features have their scenario details completed long before coding the associated step definitions is undertaken. When this is avoidable it should be and when it is not avoidable then every effort should be made to avoid it nonetheless. In the long run, the best results are achieved when you write feature statements and step definitions incrementally, using the absolute minimum of code, and then immediately implement the new step requirement in the application, also using the absolute minimum code that will satisfy it.

This is a hard discipline to accept but, the value with this approach is that you will rarely ( never ) have untested code anywhere in your application. More importantly, if you rigorously adhere to this methodology then your application will only contain code that satisfies required features. This is an often overlooked or undervalued consideration that contributes greatly to the efficiency of coding and the robustness of the resulting code. Avoiding diversions into technically interesting and financially pointless coding adventures concentrates resources on the tasks that count and reduces the overall complexity of the project. For if the user is not asking for it then why are we writing it?

Sticking with this approach you can face significant design changes ( and gem updates ) with complete equanimity, secure in the knowledge that if unanticipated changes break anything anywhere in your project then you will know of this immediately upon running your test suite. More importantly, you will know exactly what is broken and where it is broken. Like any skilled tradesman, most of the value programmers provide lies in discovering what piece of code to change and not simply how to change it. Finding the the spots that need attention in a application is usually the biggest maintenance problem. Strictly coding to features simplifies that task to the point of triviality.

If it happens that, on occasion, you do anticipate feature steps ( and we all do this however much we try not to ) then omitting any matcher for them in the step definitions files causes these steps to be reported as missing by Cucumber. Not only does Cucumber report them, it helpfully provides a suggested step matcher and argument to implement. If you end up writing stub step matchers then you have an explicit pending method available to designate defined but pending/unspecified/stub step definitions, together with an optional message. These step definitions will display as defined but pending in your Cucumber runs.


  Given /this step is not implemented yet/ do
    pending "your message goes here"
  end

What are Features and Scenarios?

A feature can be conceptualized as an indivisible unit of functionality embedded in the project to which it belongs. For example, an authentication challenge and response user interface is usually considered a feature while an entire authentication system necessarily comprises many features. A single Feature is typically contained in its own file (ending in .feature). Each Feature usually consists of multiple Scenarios.

A Scenario is a block of statements that describe some behaviour desired or deprecated in the feature to which it belongs. A scenario might check that the login interface provides input fields for the requisite responses, that failures are logged or otherwise reported, that user ids are locked out after a given number of failed attempts, and so forth. Each scenario exercises the implementation code to prove that for each anticipated condition the expected behaviour is indeed produced. Recall that scenarios specify What and should avoid answering the question: How?

Each Scenario consists of three classes of statements, Given, When and Then which effectively divide each scenario into three stages. Each stage of a scenario consists of one or more statements that are used to match to test step definitions. The conventional arrangement is:

Feature: Some terse yet descriptive text of what is desired
In order that some business value is realized
An actor with some explicit system role
Should obtain some beneficial outcome which furthers the goal
To Increase Revenue | Reduce Costs | Protect Revenue  (pick one)

  Scenario:   Some determinable business situation
      Given some condition to meet
         And some other condition to meet
       When some action by the actor
         And some other action
         And yet another action
       Then some testable outcome is achieved
         And something else we can check happens too

  Scenario:  A different situation
      ...

For Cucumber features the key words used here are Feature, Scenario, Given, When, Then, and And. Feature is used to provide identification of the test group when results are reported.

At the present time the Feature statement and its descriptive text block are not used by Cucumber other than as an identifier and documentation. However, the Feature statement is actually the central piece of information contained in a feature file. It is here that you answer the question of just why this work is being done. And, if you do not have a very good, defensible, reason that can be clearly elucidated in a few sentences then you probably should not be expending any effort on this at all. First and foremost, BDD absolutely MUST have some concrete business value whose realization can be measured before you write a single line of code.

As with Feature, Scenario is used only to identify and document a piece of the work. The clauses that make up a Scenario begin with one of: Given, When, Then, And and But. These are all Gherkin keywords / Cucumber methods that take as their argument the string that follows. These are the steps that Cucumber will report as passing, failing or pending based on the results of the corresponding step matchers in the step_definitions.rb files. The five keywords are all equivalent to one another and completely interchangeable.

The string following the keyword is compared against all the matchers contained in all of the loaded step_definitions.rb files. A step definitions matcher looks much like this:

Given /there are (\d+) froobles/ do |n|
  Frooble.transaction do
    Frooble.destroy_all
    n.to_i.times do |n|
      Frooble.create! :name => "Frooble #{n}"
    end
  end
end

The significant thing here is that the method (Given) takes as its argument a regexp bounded by /. Among other things, that means that all the arguments are received as string values. Thus n.to_i.times and not simply n.times. It also means that step matchers can be followed by the special regexp modifiers, like i if you want to avoid issues involving capitalization.

In the feature provided above we had the scenario statement: And some other action. This could be matched by any of the following step definition matchers if present in any step_definitions.rb file found under the features root directory.

Given /some other action/ do
When /some (.*) action/ do |match|
Then /(.*) other action/ do |match|
Given /(.*) other (.*)/ do |first,second|
But /(.*) other (.*)/ do |first,second|
And /(.*) other (.*)/ do |first,second|

The step definition match depends only upon the pattern following the Given/When/Then method and not upon the step method itself. I have therefore adopted the practice of only using When /I have a match/ do in my step definitions files as When has a more natural appearance, to me, for a matcher.

If Cucumber finds more than one matcher in all of the step definitions files matches a scenario statement then it complains that it has found multiple step definition matches for that step and forces you to distinguish them. You can instruct Cucumber to just choose one of the candidates instead by passing it the --guess option on the command line.

It is considered better form by some to surround with double quotation marks, " ", all of the elements in the feature step clauses that are meant to be taken as values for variables passed to the step definition. This is just a convention. However, if you choose to follow this road then you must adjust your step definition matchers accordingly. For example:

Given Some determinable "business" situation

Given /determinable "(.*)" situation/ do |s|

Finally, you can have step definitions call other step definitions, including those contained in other step definitions files. This is where you can specify the procedural details by combining other steps. For example:

When /some "(.*)" action/  do |act|
   .  .  .
end

When /in an invoiced non-shipped situation/ do
  Given "some \"invoiced\" action" 
  Then "some \"non-shipped\" action"
  .  .  .
end

If one step definition calls another step definition then the matcher argument to the called Given/When/Then method must be enclosed with string delimiters. Because of this, if you have adopted the practice of demarcating parameter values present in feature steps with double quotation marks, you must escape these quotation marks when calling another definition_steps.rb matcher from inside a step_definitions.rb file. You must take care not to include the quote marks in the step_definitions parameter matchers, for "(.*)" is not the same as (.*) or (".*"). If you use quote delimited values in the .feature file steps and do not account for them in the corresponding step_definition.rb matcher regexp then you will obtain variables that contain leading and trailing quotes as part of their value.


Scenario: Quotes surround value elements
  Given some "required" action

# step_definitions
When /some (.*) action/ do |a|
  a => "required"

When /some "(.*)" action/ do |a|
  a => required

In a manner similar to my convention of using only using the When method for step definition matchers, as When, Given, and Then are all equivalent inside the step definitions file, I have adopted the convention of calling other step definitions within matchers using the Then method, thus:

When /my matcher named (.*)/ do |match|
  Then "my other matcher named \"#{match}\""
end

The choice of matcher method has no impact on the result but, When and Then used in this fashion seem to me to read more naturally. You should also realize that the argument passed to the Then method is a string and that the string may be constructed in any manner. For example the above Then statement could be passed as:

When /my matcher named (.*)/ do |match|
  Then %Q(my other matcher named "#{match}")
end

This latter format removes the necessity to escape (\) the embedded quotation characters ("). Multiple steps may be called using the steps method which itself takes a string argument:

When /my matcher named (.*)/ do |match|
  steps %Q{
    Then my other matcher named "#{match}"
     And the next matcher with value "{match}"
  }
end

Keep in mind that Cucumber is simply a DSL wrapper around the Ruby language, whose full expressiveness remains available to you in the step definition files. On the other hand, do not lose sight that every step is parsed by Gherkin and therefore must conform to the syntax used in the feature files.

Returning to “Bob” the user, one could define things in the step_definitions file like this:

When /"Bob" logs in/ do |user|
  steps( %Q(
    Then I visit "/login"
      And I enter "#{user}" in the "user name" field
      And I enter "#{user}-test-passwd" in the "password" field
      And I press the "login" button
  ) )

That is acceptable ( barely ) usage in your step_definitions because your users are never going to see how ugly it looks. Instead, given that the necessary classes and methods exist, “Bob” could, and should, be authenticated without recourse to the user interface thus:


When /"Bob" logs in/ do |user|
  @current_user = User.find_by_username!(user) # ! method raises exception on failure
  @current_session = UserSession.create!(@current_user)  # ! method raises exception on failure
  .  .  .
end

Of course, when you are testing the login user interface the ugly approach is unavoidable.

Having just shown you how to call steps from within other steps take heed that you do not write many step definitions that are only called from other steps and are never found in feature files. Sometimes this will seem like the quickest solution to a troublesome bit of environment building. However, for anything extensive in nature it is nearly always better to implement a custom method using the api provided by Cucumber ( or by any other libraries you have installed ) and then call that method directly from your step. You can stick these custom methods in any convenient file ending in .rb that is located in the support directory ( well, anywhere that cucumber can find it really ) and which encloses your methods with the following block:


Cucumber::Rails::World.class_eval do
  def your_method(parm)
    .  .  .
  end
end

My rule of thumb is that if a step definition requires more than eight to ten lines of code, and it is called from any other step definition, then its contents probably should be refactored out into a custom method.

If all your feature’s scenarios share the same ‘setup’ feature steps then Cucumber provides the Background section. Steps contained within a Background section are run before each of the scenarios.

Feature: .  .  .
  Background: .  .  .
  Scenario: .  .  .

Step definitions files have corresponding method available in the before(condition) do . . . method, which has however a matching after(condition) do . . . method as well. Recall that we are working in Ruby and therefore the condition which enables the before/after block is anything that is not false or nil, like a tag for instance. Also be aware that all eligible before methods are run before any scenario statements are processed, and that they are run in the order encountered. Likewise, every eligible after block will run at the completion of every scenario, again in the order that it is encountered. These two methods are powerful tools, but be aware that if you use them excessively then you will hang yourself eventually.

What are “tags”?

Cucumber provides a simple method to organize features and scenarios by user determined classifications. This is implemented using the convention that any space delimited string found in a feature file that is prefaced with the commercial at (@) symbol is considered a tag. As distributed, Cucumber-Rails builds a Rake task that recognizes the @wip tag. However, any string may used as a tag and any scenario or entire feature can have multiple tags associated with it. For example:

  @init
  Feature:  .  .  .
  .  .  .
  @wip @authent
  Scenario:  A user should authenticate before accessing any resource.
     Given I do have a user named "testuser"
      When the user visits the login page
         And the user named "testuser" authenticates successfully
     Then I should see .  .  .
         .   .  .

Given that the forgoing is contained in a file called features/login/login.feature and that the cucumber-rails gem is installed and configured then you can exercise this scenario, along with any others that are similarly tagged, in any of the following ways:

$ rake cucumber:wip
$ cucumber --profile=my_profile --tags=@wip features
$ cucumber --profile=my_profile --tags=@authent features/login
$ cucumber --profile=my_profile --tags=@init 

However, the following will not work, unless you build a custom rake task for it:

$ rake cucumber:authent

There is an obscure gotcha with this particular combination of tags. The default profile contained in the distributed config/cucumber.yml contains these lines:

<%
.  .  .
std_opts = "--format #{ENV['CUCUMBER_FORMAT'] || 'progress'} --strict --tags ~@wip"
%>
default: <%= std_opts %> features
.  .  .

Note the trailing option --tags ~@wip. Cucumber provides for negating tags by prefacing the --tags argument with a tilde character(~). This tells Cucumber to not process features and scenarios so tagged. If you do not specify a different profile ( cucumber -p profilename )then the default profile will be used. If the default profile is used then the --tags ~@wip will cause Cucumber to skip any scenario that is so tagged. This will override the --tags=@authen option passed in the command line and so you will see this:

$ cucumber --tags=@authent
Using the default profile...

0 scenarios
0 steps
0m0.000s

You can overcome this by adding the --tags=@wip to the Cucumber argument list on the command line. This overrides the default setting in the configuration file. Note however that @wip tags are a special case. If any scenario tagged as @wip passes all of its steps without error then Cucumber reports this as a Scenario failure. Work in progress is not supposed to pass.

The number of occurrences of a particular tag in your feature set may be controlled by appending a colon followed by a number to the end of the tag name passed to the tags option, as in $ cucumber --tags=@wip:3 features/log*. The existence of more than the specified number of occurrences of that tag in all the features that are exercised during a particular cucumber run will produce a warning message. If the --strict option is passed as well, as is the case with the default profile, then instead of a warning the run will fail.

Limiting the number of occurrences is commonly used in conjunction with the @wip tag to restrict the number of unspecified scenarios to manageable levels. Those following Kanban or Lean Software Development based methodologies will find this facility invaluable.

As outlined above, tags may be negated by prefacing the tag with the tilde (~) symbol. In other words, you can exclude all scenarios that have a particular tag. For example, the following will only exercise all scenarios found in the directory tree rooted at features/wip that do not have the tag @ignore:

$ cucumber --require=features --tag=~@ignore features/wip

What Way do I Run the Tests?

Unless you are knowledgeable enough that you can use mocks and stubs with flair then I consider it best to begin with creating a Rails migration file for the models you are testing ( or expressing features for ) followed by:

rake db:migrate
rake db:test:prepare

As this is opinionated software my opinion is that, except for the most trivial of cases, you should always use test data obtained from actual production environments. You are, after all, embarked on a real-world adventure; namely to discover how to make something work. However, to discover what actually works requires more than a passing familiarity with what is real. And made-up data is not reality. Since your manufactured data originates in the same place as most of your errors will, your own limited understanding of the problem domain, it is always suspect.

That said, there remains an important environmental consideration to keep in mind when using an actual database for testing: Cucumber, by default, uses database transactions and these transactions are rolled back after each scenario. This makes out-of-process testing problematic (for that see the Cucumber Aruba project) and may result in some unanticipated outcomes under certain scenarios. Transactions can be turned off, but then your features become responsible for ensuring that the database is in a condition suitable for testing. Cucumber provides hooks to accomplish this and the gem Database-Cleaner is configured in support/env.rb to assist. In the normal case, the end of any scenario results in the database being returned to a nil state.

Cucumber can be run in several ways. Be aware that rake cucumber, cucumber features, and autotest with ENV AUTOFEATURE=true do not necessarily produce the same results given the same features and step definitions.

Running rake cucumber from the command line provides the simplest, if not the speediest, method to run Cucumber tests. The rake script provided with cucumber performs much of the background magic required to get the test database and requisite libraries properly loaded. In fact, an important habit to acquire is to run cucumber as a rake task immediately after performing a migration. This step ensures that the test database schema is kept in sync with the development database schema. You can achieve the same effect by running rake db:test:prepare before your first cucumber run following a migration but developing the habit of just running rake cucumber or rake cucumber:wip is probably the better course.

As discussed above, the Cucumber Rake task recognises the @wip tag, so rake cucumber:wip will run only those scenarios tagged with @wip. For example, given a feature file containing:

Feature: .  .  .

  Scenario: A

  @wip
  Scenario: B

  Scenario: C

Then running the command rake cucumber:wip will run the steps contained inside Scenario B only, while running rake cucumber:ok will run the steps within all Scenarios other than B.

Cucumber-Rails creates a cucumber.yml file in the project config directory containing a number of predefined profiles, one of which is the default profile. When Cucumber is run from the command line it is usually necessary to provide both the directory name containing the root directory of the tree containing feature files and the directory name containing references to the necessary library files. In the typical project cucumber -r features features/some/path will normally suffice. Repetitious usages can be added to user defined profiles contained in the project’s cucumber.yml file.

Finally, running autotest with the environment variable AUTOFEATURE=true will run ALL tests, including those in /test and (if present) /rspec. As this will load all the TestUnit and RSpec fixtures as well, your test database may be left in an indefinite state when the Cucumber features are run. It is wise, as always, to write Cucumber steps either so that they do not depend upon an empty database or they place the database in the requisite state.

Anything Else?

The terminology for elements of Behaviour Driven Development differs somewhat from that employed by Test Driven Development. This article, because of the introductory nature of its contents, tends to blur the semantic distinction between these two divergent philosophies.

Cucumber is evolving, rapidly. Originally, Cucumber was written for Ruby on Rails. As discussed above this has long since ceased to be true and Cucumber now has a supplementary library, Aruba, which permits testing of Command Line Interface processes. This article is revised to Cucumber version 0.9.4 and Cucumber-Rails version 0.3.2 but it does not cover many of the ever expanding attributes of Cucumber, Cucumber-Rails and now Aruba. The essentials of this article remain applicable throughout all recent versions of Cucumber and Cucumber-Rails but the implementation details may have changed. It would not be wise to use any of the examples from this article as a recipe.

Cucumber supports tables in feature files. These are roughly analogous to Framework for Integrated Test (FIT) tables. You can use these when you are specifying behaviour that changes at some data threshold or as a substitute for data fixtures. I tend to avoid using tables in feature files altogether and use them sparingly in step definition files. I do not have any explicit reason for this avoidance but, tables and feature statements just do not seem to go together in my head.

If you are testing with intent then you should be using the ruby-debug gem (ruby-debug19 for Ruby-1.9.x). A really neat method to drop into an interactive debugging session inside a Cucumber step definition using ruby-debug was provided by Scott Taylor on the rspec mailing list. Just put these statements inside the step definition at the point that you wish to debug: require 'rubygems'; require 'ruby-debug'; debugger. When that code interrupts then type irb and you open an interactive debugging session wherein you can step forwards and backwards inside the code under test to determine exactly where the breakage is happening. Alternatively, you can add require 'rubygems'; require 'ruby-debug'; to your support/local_env.rb file (see below) and just put debugger wherever you desire it inside any step definition.

Realize that tests/assertions/expectations either pass or fail (raise an error) and that fail is NOT the same as false, whereas anything but fail is a pass. When, in RSpec, something.should_be 0 and it is not, then what is returned is an error exception and not a Boolean value. In raw Cucumber (pardon the pun) one writes fail if false and not simply false. A little reflection reveals why this is so, since false might be the expected successful outcome of a test and thus not an error. However, the distinction between fail and false escaped my notice until I tripped over it in an actual test suite.

Recall that Cucumber is an integration test harness. It is designed to exercise the entire application stack from view down to the database. It is certainly possible to write features and construct step definitions in such a fashion as to conduct unit tests and no great harm will result. However, this is not considered best practice by many and may prove insupportable for very large projects due to the system overhead it causes and the commensurate delay in obtaining test results.

Cucumber-Rails is pre-configured with support for view integration testing using either Capybara (script/generate cucumber —capybara) or Webrat (script/generate cucumber). If you do not know what Capybara or Webrat are or do, and you are doing web application testing, then you should find out more about both. The Cucumber-Rails generator will set up the necessary support files for whichever you choose. However, the most recent release of Webrat (0.7.1) only works with Rails-3.0.x in some places and not in others. Capybara (0.4.0) does work with Rails-3.0.×.

While Capybara is emerging as the preferred testing method it does not play well with Rails’ own built-in Test Assertions. In particular, whenever Capybara is required into a Cucumber World then the response.body method of Rails Test::Unit is removed.

Calls for any additional Ruby libraries that your particular testing environment may require are typically placed in the ./features/support/local_env.rb file. I advise against putting local customization in support/env.rb as it is typically overwritten by script/generate cucumber. As a matter of good practice you should always run script/generate cucumber whenever you install an updated version. You should do the same for rspec as well.

Those of you that have used growl or snarl to provide desktop notifiers from autotest are advised that, as of this writing, Cucumber did not hook into the :red :green notifier capability of autotest; so, no pop-ups when a step fails. However, there exists a project to add a similar functionality to Cucumber. See Cucumber_Growler.

autotest is installed via the ZenTest gem. If you use autotest then take a look at the contents of example_dot_autotest.rb in the ZenTest gem root directory.

Need Help?

The best place to go for help, that I know of, is the Google Cucumber Group.

If you find a bug in Cucumber, or wish a new feature added, then you should open a ticket at Lighthouse for it.

2008 November 28 – J. B. Byrne initial
2010 January 17 – J. B. Byrne revised to 0.6.1
2010 May 28 – J. B. Byrne revised 0.7.3
2010 July 13 – J. B. Byrne revised to 0.8.4
2010 October 11 – J. B. Byrne revised to 0.9.0
2010 November 06 – J. B. Byrne revised to 0.9.4

Postscript.

A caution, Cucumber is meant to facilitate expressing required behaviours. Indirection and excessive adherence to the principle of DRY, particularly in features, is at variance with both the intent and the major benefit of the tool. Requirement expression in features should remain as self evident to the non-technical reader and be as self contained as possible. Resist the temptation to effectively program features using the DSL. Features should remain patent statements of intent. If you feel the need to “program” a scenario in order to simplify writing a feature then you are likely doing something considerably at odds with the intent of BDD methodology. In such circumstances, mentally step back and reconsider your approach to the problem.

Clone this wiki locally