Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't execute localStorage.clear in teardown method of a Capybara test

I'm using Capybara to test the front-end portion of an app that utilizes HTML5 local storage to persist data values on the client. In order to ensure session data from one test doesn't interfere with another, I made sure to call Capybara.reset_sessions! in the teardown method of each test.

I soon realized this method does not actually clear local storage and was advised to make sure window.localStorage.clear() was manually executed after each test, so I put this line in the teardown method for my test class like so:

  def teardown
    super
    page.execute_script("localStorage.clear()")
  end

However when I try to run it:

  1) Error:
CartTest#test_adding_an_item_to_cart:
Selenium::WebDriver::Error::NoScriptResultError: <unknown>: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
  (Session info: chrome=34.0.1847.116)
  (Driver info: chromedriver=2.8.240825,platform=Linux 3.8.0-29-generic x86_64)

The strange part is that instead I tried to move the JavaScript call to the end of a test like so:

  test "test with storage" do
    # Test some browser stuff
    page.execute_script("localStorage.clear()")
  end

It works fine. Now I could of course just put that line at the end of each test to get it working but that would be a mess. Anyone know how to get it to work in the tearndown method?

like image 514
renfredxh Avatar asked Jun 17 '14 14:06

renfredxh


1 Answers

Figured this out. You have to call visit so your driver is on a page in the current session before calling execute_script. After changing my teardown method to the one below, it worked:

  def teardown
    super
    visit "/" # This can be whatever URL you need it to be
    page.execute_script("localStorage.clear()")
  end
like image 154
renfredxh Avatar answered Sep 30 '22 04:09

renfredxh