简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM