Ivan Velichko
Ivan Velichko

Reputation: 6709

Clear cookies per each test in PhantomJS+GhostDriver+WebDriver client configuration

How can I clear cookies for each tests in my PhantomJS + GhostDriver + Selenium WebDriver + WebDriver Client system?

My test process looks like this:

  1. Start selenium-web-driver-standalone in hub role.
  2. Start phantomjs in webdriver mode and attach it to selenium webdriver.
  3. Start shell script that iterates over tests suites and start each.
  4. Each test uses webdriver client and communicate with browser connected to selenium web driver.

When I use firefox browser instead of phantomjs all tests passed ok. But when I switch to using phantomjs as browser all tests that checked registration failed because cookies already set after first test execution. Can I clear all cookies on every test start up? Or I should to restart phantomjs process on every separate test (as this is with firefox and selenium webdriver in not hub role)?

Upvotes: 6

Views: 3764

Answers (3)

userlond
userlond

Reputation: 3828

Maybe some offtopic, cause author marked that he uses php to run test.

But if you came from google and interested in C# solution to clear all cookies, look below:

// driver is fully initialized PhantomJS instance
driver.Manage().Cookies.DeleteAllCookies();

Requires NuGetPackages:

PhantomJS 2.0.0

Selenium.Support 2.48.2

Selenium.WebDriver 2.48.2

Tested with .NETFramework v4.5.2

Upvotes: 2

Cubius
Cubius

Reputation: 1324

I had similar problem with GhostDriver not being able to clear localStorage. Try these suggestions:

After you driver.get(URL) to your page, you can execute javascript in it from webdriver, like this

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past

Resources:

  1. https://sqa.stackexchange.com/a/10468
  2. https://stackoverflow.com/a/2421786/572348

Upvotes: 1

Johnny
Johnny

Reputation: 15413

You can delete specific cookie using:

webDriver.manage().deleteCookieNamed("smSession");

And to delete all the cookies using:

webDriver.manage().deleteAllCookies();

Upvotes: 1

Related Questions