The Issue
We previously utilized the if/else statements with Ruby for Watir Webdriver scripts. Now we can take a look at how we can implement them into our Cucumber feature files and step definitions.
The Code
In the below example, we want to see if a button is visible, and fail it if not. We have implemented the if/else statements; if the browser finds the specified text, it will use the puts command to display output in the command line. If it does not find the text, it will fail the step and display a message in the command line.
1 2 3 4 5 6 7 |
Then(/I see the button with text "([^"]*)"$/) do |text| if @browser.button(:text, text).present? puts("Button with text '#{text}' is visible.") else fail("Button with text '#{text}' is not visible.") end end |
For this step, |text| is whatever we write in our feature file. In the below feature file, where the step is implemented, the |text| variable is “Remove” and “Add”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
2 # ta101_if_statement.feature Feature: TA101 If Statement Scenario: Demonstrate use of if statements in step definitions Given I open a browser And I maximize the browser When I go to url "http://the-internet.herokuapp.com/dynamic_controls" Then I see the button with text "Remove" When I click the button with text "Remove" And I wait for 4 seconds Then I see the button with text "Add" Then I see the button with text "Remove" Then I close the browser |
This will give us the below output in our command line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Button with text 'Remove' is visible. Button with text 'Add' is visible. RuntimeError: Button with how 'Remove' is not visible. ./features/step_definitions/ta101_ruby_automation_steps.rb:393:in `/I see the button with "([^"]*)" "([^"]*)"$/' ./features/ta101_if_statement.feature:17:in `Then I see the button with "text" "Remove"' Skipped step 1 scenario (1 failed) 11 steps (1 failed, 1 skipped, 9 passed) 0m12.373s Process finished with exit code 1 |
The command line output displays the visible validations when the button is found, and the fail when it is not, as per our previously defined step.
The Takeaway
Implementing if/else logic in your test automation allows you to develop more complex and efficient scripts. As you build out your step definitions, you’ll see just how often you use statements!