Skip to content

03 Writing custom steps

krukow edited this page Mar 15, 2012 · 13 revisions

We've already looked at the Predefined steps which lets you interact with your application without doing any actual test-code programming.

Custom steps let you define your own steps like Then I login as "Rune". When you want to use a custom step you have to specify an implementation defining what that step is supposed to do. This is done by writing a little bit of Ruby code.

In Cucumber a step definition consist of two things: a regular expression (to matching the step text) and a block of Ruby code.

If you are not familiar with Cucumber and step definitions, you must find the appropriate information using the links: Cucumber step definition.

Macro steps

The simplest way of writing custom steps is to combine one or more existing steps. You do this using the macro function.

Then /^I log in$/ do
    macro 'I enter "ruk" into the "Login" text field'
    macro 'I enter "mypass" into the "Password" text field'
    macro 'I touch the "login" button'
end

The step I log in will perform three actions for the price of only one step.

Steps can take parameters:

USERS = {"Rune" => {:pass => "mypass", :user => "ruk"}}

Then /^I log in as "([^\"]*)"$/ do |user|
    macro %Q[I enter "#{USERS[user][:user]}" into the "Login" text field]
    macro %Q[I enter "#{USERS[user][:pass]}" into the "Password" text field]
    macro %Q[I touch the "login" button]
end

Three things to note:

  1. You can write any Ruby code! In this case I define a global map USERS which has a key for each user, and :user and :pass entries for that user. The can be used inside the step definition.

  2. You can use Ruby's string escape syntax %Q[...] to write a string ... where you can use both single quote ('), double quote (") and interpolation (e.g., asdf#{variable}dsa).

  3. Step definitions can be parameterized. You can write regular expressions inside parentheses (...) - those are called groups. In our example we write a regular expresion that must start with I log in as then there must be a quote ". Then any text which doesn't contain quotes: the regular expression is written in parentheses as: [^\"]* meaning zero or more characters that are not " (for example Rune will match). After that there must be an end quote ".

Advanced custom steps using the Calabash Ruby API

TBD

Clone this wiki locally