Multiple Captures

You don’t have to stop at capturing just a single argument. Cucumber will pass an argument to your block for every capture group in your regular expression, so you can grab as many details as you like from a step.

Here’s an example. Let’s imagine our bank wants to start offering its customers savings accounts as well as their regular checking account. Customers can use the ATM to transfer money between their accounts. Here’s one of the scenarios for this new feature:

 
Scenario:​ Transfer funds from savings into checking account​
 
Given ​I have deposited $10 in my Checking Account​
 
And ​I have deposited $500 in my Savings Account​
 
When ​I transfer $500 from my Savings Account into my Checking Account​
 
Then ​the balance of the Checking Account should be $510​
 
And ​the balance of the Savings Account should be $0

Let’s try to write a step definition that can handle the first two steps. As well as the amount deposited, we need to capture the type of account so that we know where to put it.

We can use a modified version of the regular expression we used previously to capture the type of account:

 
Given /I have deposited $(d+) in my (w+) Account/ ​do​ |amount, account_type|
 
# TODO: code goes here
 
end

We use the shorthand character class w, modified with the plus to mean any word character, at least once, effectively capturing a single word. That word is then passed to the block in the second argument, which we’ve named account_type.

Try This

Write a step definition for the next step in the scenario, When I transfer $500 from my Savings Account into my Checking Account. The step definition should capture three arguments:

  • The amount of money being transferred

  • The type of account being debited in the transfer

  • The type of account that receives the credit in the transfer

Test it by writing simple puts statements in your step definition to print the value captured in each argument to the console.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.123.147