cucumberphantomjspoltergeist

Setting a cookie with javascript doesn't work in Poltergeist and/or PhantomJS


I have a web page that sets a cookie with document.cookie = value, and it works perfectly while running on the server.

However, in my cucumber tests (with Poltergeist/PhantomJS), the cookies are not persisting from one page to the next.

The test flow is:

  1. page A opens
  2. user clicks a button, which triggers JS to set the cookie
  3. user clicks link to page B
  4. page B has a component that reflects the cookie's value

In a real browser against a running server, it's fine.

But in cucumber, step 4's display shows that it's seeing a blank cookie.

Does anyone know how I can fix or investigate this?


Solution

  • Turns out I got some bad advice from some other page, which was actually interfering with Poltergeist's natural behavior.

    I took that crap out, and Poltergeist worked. I have since implemented a better alternate way of setting cookies in tests, and all is good.

    By popular demand, here is the cookie-setter code in my test-step:

    case Capybara.current_session.driver
    when Capybara::Poltergeist::Driver
      page.driver.set_cookie(k,v)
    when Capybara::RackTest::Driver
      headers = {}
      Rack::Utils.set_cookie_header!(headers,k,v)
      cookie_string = headers['Set-Cookie']
      Capybara.current_session.driver.browser.set_cookie(cookie_string)
    when Capybara::Selenium::Driver
      page.driver.browser.manage.add_cookie(:name=>k, :value=>v)
    else
      raise "no cookie-setter implemented for driver #{Capybara.current_session.driver.class.name}"
    end
    

    IMPORTANT CAVEAT: If you set your cookie via a test step with the above code, your page's Javascript might not be allowed to overwrite it. If your test needs your page to alter the cookie, you may find that the cookie never gets altered.