Exploring the seamless integration of CakePHP 3 with Selenium for automated testing

Currently, I am working with cakephp 3, selenium facebook web driver, and phpunit.

One issue that I am facing is the inability to access pages that require authentication. Despite trying to add the same auth session used in my controller unit tests, it has not been successful.

$this->session(['Auth.User.id' => 1, 'Auth.User.role' => 'admin']);

I attempted to have the test log in first before proceeding with other tests, but that approach also did not work. It seems like adding a session is necessary.

<?php

use \Facebook\WebDriver\Remote\DesiredCapabilities;
use \Facebook\WebDriver\Remote\RemoteWebDriver;
use \Facebook\WebDriver\WebDriverBy;

/**
 * Description of UserEditTest
 *
 * @author john
 */
class UserEditTest extends PHPUnit_Framework_TestCase 
{

    protected $webDriver;




    public function setUp()
    {
         $this->webDriver = RemoteWebDriver::create('http://localhost:4444/wd/hub', DesiredCapabilities::firefox());
        // $this->session(['Auth.User.id' => 1, 'Auth.User.role' => 'admin']);
    }

    protected $url = 'http://localhost:81/dev/usedCars/users/edit/11'; 


      //return should contain Please enter your username and password
    public function validLoginProvider()
    {
        $inputs[] = [
            [
                'username'              => 'testuser',
                'password'              => 'test',               
            ]
        ];

        return $inputs;
    }
    //login input
  public function fillLoginFormAndSubmit($inputs)
{
    $this->webDriver->get('http://localhost:81/dev/usedCars/users/login');
    $form = $this->webDriver->findElement(WebDriverBy::id('login'));
    var_dump($inputs);

    foreach ($inputs as $input => $value) {
        $form->findElement(WebDriverBy::name($input))->sendKeys($value);      
    }
    $form->submit();
}

/**
 * @dataProvider validLoginProvider
 */
public function testValidFormSubmission(array $inputs)
{
    $this->fillLoginFormAndSubmit($inputs);

    $content = $this->webDriver->findElement(WebDriverBy::tagName('body'))->getText();
    $this->assertContains('Showroom', $content);

    testValidEditSubmission();

}



 //for testing the edit view page
      public function validInputsProvider()
    {

           $inputs[] = [
            [
               'interests'              => 'changed'
            ] 
        ];

        return $inputs;
    }

     //for testing the edit page
    public static function invalidInputsProvider()
    {
         $inputs[] = [
            [              
                'email'              => 'mypassword'

            ]
        ];


        return $inputs;
    }



      public function fillFormAndSubmit($inputs)
{
       // $this->session(['Auth.User.id' => 1, 'Auth.User.role' => 'admin']);

    $this->webDriver->get('http://localhost:81/dev/usedCars/users/edit/11');
    $form = $this->webDriver->findElement(WebDriverBy::id('edit'));
    var_dump($inputs);

    foreach ($inputs as $input => $value) {
        $form->findElement(WebDriverBy::name($input))->sendKeys($value);


    }

    $form->submit();
}


/**
 * @dataProvider validInputsProvider
 */
public function testValidEditSubmission(array $inputs)
{


    $this->fillFormAndSubmit($inputs);

    $content = $this->webDriver->findElement(WebDriverBy::tagName('body'))->getText();
    $this->assertContains('The user has been saved', $content);
}


/**
 * @dataProvider invalidInputsProvider
 */
public function testInvalidEditSubmission(array $inputs)
{
    $this->fillFormAndSubmit($inputs);

   $content = $this->webDriver->findElement(WebDriverBy::tagName('body'))->getText();
     $this->assertContains('valid email', $content);
}

    public function tearDown()
{
    $this->webDriver->quit();
}   //put your code here
}

Answer №1

After some trial and error, I managed to find a solution by incorporating a login method into the test process. This method allows access to the login page and automatically enters the array data provided as parameters.

//login input
public function fillLoginFormAndSubmit($inputs)
{
    $this->webDriver->get('http://localhost:81/dev/usedCars/users/login');
    $form = $this->webDriver->findElement(WebDriverBy::id('login'));
    var_dump($inputs);

    foreach ($inputs as $input => $value) {
        $form->findElement(WebDriverBy::name($input))->sendKeys($value);      
    }
    $form->submit();
}

To streamline the process, ensure you add the login details to an array variable and invoke the login method prior to running your test script.

public function fillFormAndSubmit($inputs)
{
    //add login details here
    $login = array("username"=>"testuser","password"=>"test");
    
    //call login method            
    $this->fillLoginFormAndSubmit($login);

    $this->webDriver->get('http://localhost:81/dev/usedCars/users/edit/11');
    $form = $this->webDriver->findElement(WebDriverBy::id('edit'));
    var_dump($inputs);

    foreach ($inputs as $input => $value) {
        $form->findElement(WebDriverBy::name($input))->sendKeys($value);
    }

    $form->submit();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

Extract hidden form variables using a function in PHP

Here is the JavaScript function that I have written: function GetCellValues() { var rows = document.getElementsByTagName('tr'); var str = ''; for (var c = 1 ; c < rows.length ; c++) { str += '\n&apo ...

The issue of not displaying results in a DIV when using CakePHP 2 and jQuery

I'm having trouble creating an auto-refreshing DIV with updated data. Despite everything appearing to be correct, it's not displaying any results on the webpage. Any assistance would be greatly appreciated :) Controller: public function homeNe ...

Email will be dispatched once reCAPTCHA verification is completed

I'm currently facing an issue with sending an email from my website's form via PHP after the reCAPTCHA verification. Whenever I click the submit button, the page refreshes but the email is not being sent. I believe I might be overlooking somethin ...

The clash of interests between jQuery and Bootstrap

I'm facing a problem with conflicting jQuery and Bootstrap files in my header.php code. Whenever I include the jQuery file before the bootstrap.js file, it causes issues with the tabs on my website where clicking on them does not navigate me to the co ...

Serializing PHP objects for multiple bulky objects

I am currently working on a PHP application that involves building multiple extensive collections of objects while interacting with the user. These objects need to be persisted across user requests, and I have successfully achieved this using PHP sessions. ...

Ineffective Implementation of While Loop for Div Visibility

Here's a simple code that generates divs using a while loop. However, it doesn't seem to be working as expected. It's actually just basic HTML, nothing too complex. But for some reason, it's not displaying any of the five divs. <? ...

Sending a subdomain to a specific subfolder

I've been trying to redirect the subdomain to a subdirectory without success. Below is what I have attempted so far. RewriteEngine On RewriteCond %{HTTP_HOST} ^name\.site_url RewriteRule ^(.*)$ http://site_url/name/$1 [L,R=301] ...

How does Java compare to PHP's list() function when it comes to accessing variables in an array?

How can you achieve a similar functionality to PHP's list() function in Java? Consider the following example: $matches = array('12', 'watt'); list($value, $unit) = $matches; ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

The loop is being controlled but the data is not being added and shown in the HTML div

I am struggling to display JSON data in an HTML div using a for loop. While my control is entering the loop, the data is not being appended and displayed in the HTML div. Here is the JSON data: [{"id":"15","FirstName":"ranjan","MiddleName":"","LastName": ...

Retrieve a numeric value from a MySQL database table, perform a multiplication operation on it, and then

Hey there, I'm new to PHP MySQL and in need of some assistance: I currently have a Table in my MySQL database structured like this: Number1 | Number2 | Calculate  8    | 9    |     &nbs ...

Deleting items from an array of files and directories with PHP

Currently, I am attempting to retrieve a list of directories within a specified path using the scandir method and then removing any files from the resulting array. However, I am encountering issues with my echo statement. The code snippet I am working on ...

When using selenium webdriver, the actual text may appear as "Indian," but when trying to fetch the text using element.getText(), it may display

Here is the source code snippet for the element: <div id="q1"> <p>Are you an "Indian" by birth?</p> </div> The expected text is: Are you an "Indian" by birth? The actual text using Selenium WebDriver ...

Obtaining a cookie for the PHPUnit test involving Ajax functionality

When it comes to writing PHPUnit tests for ajax endpoints, I find it easy when the user doesn't need to be logged in. However, for the specific endpoint I want to test, the user must be logged in and I need to programmatically retrieve the cookie as p ...

Strip the quotes from the JSON output

Need help removing double quotes from my JSON output. Here's the issue: [{"id":"1","nom":"Magasin Jardins 2","ville":"Paris","latlng":["36.85715,10.127245"]} I want to remove quotes from the latlng value to get this result: [36.85715,10.127245] He ...

Unable to retrieve the textual content from an anchor tag

How can I retrieve the text value of a link with "My account" as the anchor text? I'm looking to verify if I am logged in to a website by checking this specific string. I've been struggling to find the correct approach, despite trying various m ...

Tips for transferring PHP variable from a drop down menu

Hello, I am currently working on creating a dropdown menu using the <select> tag. My goal is to have it so that when someone clicks on one of the options in the dropdown, a new window opens. Additionally, I want the PHP variable from the main page to ...

Can you assist with adding elements to a list array and then locating their position or index within the list using Java and Selenium?

I've been working on a page where I need to extract the header items from a table and store them in a list. My end goal is to locate the position of "Attempt Date" within that list. List<String> headerList = new ArrayList<>(); List<WebE ...

Steps for accessing the search input box in Office365 Hotmail:1. Open your web

I'm having trouble with automating the process of opening an email through searching for the email address. Despite trying various XPaths and Actions, I can't seem to click on the search box. Can anyone provide assistance? This is being done in ...