Search code examples
seleniumcucumber

Apply Condition in Cucumber Feature Scenario


How would I handle the following kind of scenario using Cucumber Java with Selenium:

  Scenario: Raise Invoice by User according to Raise Invoice Type.
  When I select the Raise Invoice Type as "RaiseInvoiceType"
  IF RaiseInvoiceType == 'ABC'
     Method ABC()
  else if RaiseInvoiceType == 'XYZ'
     Method XYZ()

"RaiseInvoiceType" is a variable and is dependent on the radio button or drop-down. How to implement cucumber feature files and step definition class methods with the condition?


Solution

  • Background

    Cucumber feature files are all about bridging the conversational gap between the business and the development team, and thus, code and conditional statements should never appear inside them.

    The Solution

    The solution to your problem is how you write the step definition.

    Using Cucumber's Ruby implementation as an example:

    When('I select the Raise Invoice Type as "$invoice_type"') do | invoice_type |
      if invoice_type == 'ABC'
         method_abc
      else 
         if invoice_type == 'XYZ'
            method_xyz
         else
            raise 'Unknown invoice type'
         end
      end
    end
    

    This brings the code and conditional statements out of the feature file, which is in essence meant to be living documentation of the behaviours of the application/system

    Further Improvements

    But I would go so far as to change the wording of the step too:

    Scenario Outline: Raise Invoice by User according to Raise Invoice Type.
      When I raise the invoice type "<invoice_type>"
      Then some expected behaviour
    
    Examples:
      | invoice_type |
      | ABC          |
      | XYZ          |
    

    This brings the step away from implementation (that could be dropdown, radio or text boxes for example), and more towards behaviours of the system in place - the feature that this scenario is highlighting is that you should be able to raise an invoice, not that you should have a list of options to choose from in a select box.