The Issue
We previously learned about Local Variables 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
When a Cucumber step definition needs a value passed to it, that value is assigned to a local variable defined between the pipes ‘|’ after the ‘do’. This variable is |text| for the below example
1 2 3 4 5 6 7 8 9 |
Then /^I see "([^"]*)"$/ do |text| unless @browser.text.include?(text) fail("Did not find text '#{text}' on the page") end end And /^I do not see "([^"]*)"$/ do |text| fail("Found #{text}") if @browser.text.include?(text) end |
The step will check for text, and fail if none is found. Lets take a look at the feature file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# cucumber features/ta101_local_variable.feature –f pretty # ta101_local_variable.feature Feature: TA101 Local Variable Scenario: Demonstrate use local variables Given I open a browser And I maximize the browser When I go to url "http://the-internet.herokuapp.com/dynamic_controls" Then I do not see "Create Account" Then I see "Create Account" Then I close the browser |
After running this file, we will see the following output:
1 2 3 4 5 6 7 8 9 |
Button with text 'Remove' is visible. #Watir::Wait::TimeoutError: timed out after 30 seconds, waiting for true condition on # ./features/step_definitions/ta101_ruby_automation_steps.rb:301:in `/^I see "([^"]*)"$/' ./features/ta101_local_variable.feature:9:in `Then I see "Create Account"' Skipped step 1 scenario (1 failed) 6 steps (1 failed, |
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
Local variables are a foundational concept of Cucumber step definitions. Understand how to implement these, and you can get started building your own step definitions.