Search code examples
behatgherkin

Behat Test: Fetch a value from Input, Multiply it by a Number and Match the Result


I have one TEXTBOX(readonly) which contains some random value say for ex. 2 (This is quantity of product). Beside it there a BUTTON(Plus-Button) and a SPAN to show result.

Now each time when I click on Plus-Button - it should MULTIPLY 5(This is price of product) to the number in the Textbox(quantity of product) and display the result in SPAN.

<input type="text" readonly="readonly" value="2" id="product-qty" />
<button id="add-qty" value="Add Quantity"/>
<span id="show-result">10</span>

Now using a behat test I am writting a Feature for above Scenario. Can someone please help me writting this.

Problem is how do I fetch a value from text box and multiply it by 5? And match it to the value in SPAN.

Scenario: Check product cart
  Given I am on "detail-page"
  When I click on the element "#add-qty"
  #fetch value from the input multiply by it 5 and match the value with the content in the SPAN
  And I wait 2000 milliseconds
  Then I should see "Product added successfully"

Solution

  • One way would be to create a step definition for your functionality.

    You can add And I add quantity for "product-qty" in your scenario.

    And then in your FeatureContext.php (or equivalent) add something like this:

        /**
     * @Given I add quantity for :arg1
     */
    public function iAddQuantityFor($arg1)
    {
        $this->pressButton('Add Quantity');
    
        $page = $this->getMink()->getSession()->getPage();
        $quantity = (int)$page->find('css', '#product-qty')->getAttribute('value');
    
        $result = $quantity * 5;
        $actual = (int)$page->find('css', '#show-result')->getHtml();
    
        if ($result !== $actual) {
            throw new \Exception('Incorrect result');
        }
    }