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

2

6

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?

Fantasy answered 17/6, 2014 at 14:52 Comment(0)
F
6

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
Fantasy answered 17/6, 2014 at 17:38 Comment(0)
H
0

I found a way to clear local storage BEFORE execution of each test. When setting up the "test/application_system_test_case.rb", add the following option: options: { clear_local_storage: true}

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :chrome, screen_size: [1400, 1400],
  options: { clear_local_storage: true}
end

can also be used for clear_session_storage

Hallucinatory answered 6/11, 2018 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.