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 let's you interact with your application without doing any actual 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 of what that step is supposed to do. This is done by writing a little bit of Ruby code.

In Cucumber 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 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 'I enter "#{USERS[user][:user]}" into the "Login" text field'
    macro 'I enter "#{USERS[user][:pass]}" into the "Password" text field'
    macro 'I touch the "login" button'
end

Two things to note: 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.

The other important thing here is that 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