How to restart the browser by saving cookies in Behat?

I am trying to test the Remember Me function using Behat / Mink. Here is my scenario:

Scenario: A user logs in ticking "Remember me". As he closes his browser and visits back the site, he should be automatically logged in
  Given I am on "/login"
  Then I should see "Site Login"
  When I fill in "Username" with "test"
  And I fill in "Password" with "test"
  And I check "Remember me"
  When I press "Login"
  Then I should see "Welcome"
  When I restart the browser
  Then I go to "/login"
  Then I should see "Welcome"

Here is the definition of browser restart:

/**
 * @When /^I restart the browser$/
 */
public function iRestartTheBrowser()
{
    $this->getSession()->restart();
}

I also tried $this->getSession()->reset();

The problem is that cookies are deleted when the browser restarts, the “remember me” function no longer works. Is there a way to restart in a mink without clearing cookies?

+4
source share
3 answers

You can get a cookie before reloading the session and set it back after that:

$cookie = $session->getCookie('remember_me');

$session->restart();

// I'm not sure if visiting a page before setting a cookie is actually needed
// after restarting the session. 
// It definitely needed when setting a cookie before the first request 
// (to set the cookie domain).
$session->visit('/')

$session->setCookie('remember_me', $cookie);
+3
source

, , .

/**
 * @When /^I close the browser$/
 */
public function iCloseTheBrowser(){
    $this->getSession()->getDriver()->stop();
}

:

...
When I close the browser
And I am on the "My" page
Then I should see "Logged: icon
...
+1

One way to do this is to get all cookies before closing and reopening the browser, and then set all cookies that have an explicit expiration date. The trick is to get cookies using the selenium web-serine session, rather than a general mink session, since the webdriver session returns everything for the cookie (path, expiration date, etc.), and not just the values. The code in my context is as follows:

/** @When I restart the browser */
public function iRestartTheBrowser()
{
    /** @var Selenium2Driver $driver */
    $driver = $this->getSession()->getDriver();
    /** @var \WebDriver\Session $session */
    $seleniumSession = $driver->getWebDriverSession();
    $cookies = $seleniumSession->getAllCookies();

    $minkSession = $this->getSession();
    $minkSession->restart();

    //The following is necessary - as the cookies can only be set after
    //you're already on the domain - this can be any page, even an error page
    $minkSession->visit($this->getMinkParameter('base_url'));

    $seleniumSession = $driver->getWebDriverSession();
    foreach ($cookies as $cookie) {
        if (isset($cookie['expiry'])) {
            $seleniumSession->setCookie($cookie);
        }
    }
}
0
source

Source: https://habr.com/ru/post/1532412/


All Articles