Search code examples
cucumber

How to use common/shared "blocks" between cucumber features?


I'm new to cucumber, but enjoying it.

I'm currently writing some Frank tests, and would like to reuse blocks of cucumber script across multiple features - I'd like to do this a the cucumber level if possible (not inside the ruby).

For example, I might have 4 scripts that all start by doing the same login steps:

  given my app has started
     then enter "guest" in "user-field"
     and enter "1234" in "password-field"
     and press "login"
  then I will see "welcome"
  then *** here's the work specific to each script ***

Is there any way to share these first 5 lines across multiple scripts? Some kind of "include" syntax?


Solution

  • Generally there are 2 approaches:

    Backgrounds

    If you want a set of steps to run before each of the scenarios in a feature file:

    Background:
         given my app has started
         then enter "guest" in "user-field"
         and enter "1234" in "password-field"
         and press "login"
         then I will see "welcome"
    
    Scenario: Some scenario
        then *** here's the work specific to this scenario ***
    
    Scenario: Some other scenario
        then *** here's the work specific to this scenario ***
    

    Calling steps from step definitions

    If you need the 'block' of steps to be used in different feature files, or a Background section is not suitable because some scenarios don't need it, then create a high-level step definition which calls the other ones:

    Given /^I have logged in$/ do
        steps %Q {
             given my app has started
             then enter "guest" in "user-field"
             and enter "1234" in "password-field"
             and press "login"
             then I will see "welcome"
        }
    end
    

    Also, in this case I'd be tempted not to implement your common steps as separate steps at all, but to create a single step definition: (assuming Capybara)

    Given /^I have logged in$/ do
        fill_in 'user-field', :with => 'guest'
        fill_in 'password-field', :with => '1234'
        click_button 'login'
    end
    

    This lends a little bit more meaning to your step definitions, rather than creating a sequence of page interactions which need to be mentally parsed before you realise 'oh, this section is logging me in'.