Skip to content

03 Writing custom steps

Joshua Moody edited this page Feb 25, 2015 · 13 revisions

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 which realizes 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.

Custom step definitions

To write custom steps you must create a file named ..._steps.rb in the directory features/step_definitions. If you ran the command calabash-ios gen then that should have generated a file you can use:

krukow:~/github/calabash-ios-example$ ls features/step_definitions/
calabash_steps.rb	my_first_steps.rb

Take a look at the file my_first_steps.rb:

Given /^I am on the Welcome Screen$/ do
    check_element_exists("view")
end

This is an example step definition matching the step "Given I am on the Welcome Screen". The block of Ruby code contained in do ... end is the code that is executed when cucumber encounters "Given I am on the Welcome Screen". You can put any Ruby code in here. In this case a call to the function check_element_exists("view") is made - this checks that there is actually a view present. This is not very interesting as the step will always pass.

Let's change that to actually check that we are on the welcome screen on the sample app. First we must identify some part of the UI that will only be present if we're on the welcome screen. We can then use this as our check. In the sample app, there is a text field with placeholder "Name". So let's change the test to check for the existence of this:

Given /^I am on the Welcome Screen$/ do
    check_element_exists("textField placeholder:'Name'")
end

and run it:

krukow:~/github/calabash-ios-example$ cucumber
Feature: Running a test
  As an iOS developer
  I want to have a sample feature file
  So I can begin testing quickly

  Scenario: Example steps  
...
    Given I am on the Welcome Screen                 # features/step_definitions/my_first_steps.rb:1
    Then I swipe left                                # calabash-cucumber-   0.9.127.pre1/features/step_definitions/calabash_steps.rb:190
    And I wait until I don't see "Please swipe left" # calabash-cucumber-   0.9.127.pre1/features/step_definitions/calabash_steps.rb:128
    And take picture                                 # calabash-cucumber-0.9.127.pre1/features/step_definitions/calabash_steps.rb:185

1 scenario (1 passed)
4 steps (4 passed)

Just to see it fail, try replacing 'Name' with 'Username' and run the test again.

Clone this wiki locally