2

I am running tests using Rspec, Capybara, Cucumber, and Selenium webdriver. For my app, if a user is a first time visitor to the site, a pop-up appears after 10 seconds, asking the user to signup for a newsletter. Whether the user signs up or not, a value gets saved to the browsers local storage, specifying that the user has viewed the pop-up (I do this so it doesn't popup every visit).

For some of my tests the popup gets in the way since it loads for every new scenario. What I want to do is before a scenario is run, to save a value to local storage before running the test, this way the popup doesn't appear. So far I have a before hook that specifies which scenarios should not have the popup:

Before('@no-newsletter') do
  page.execute_script "window.localStorage.setItem('subscribed','viewed');"
end

However, when I run this I get the following error:

SecurityError: The operation is insecure. (Selenium::WebDriver::Error::JavascriptError)

I can't figure out how to correct this issue and save a value to local storage. Any ideas?

Darkisa
  • 1,899
  • 3
  • 20
  • 40

1 Answers1

5

localStorage is stored for specific document origin - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage. Therefore you need to visit a URL for a specific origin before you can execute JS to store anything in the local storage (otherwise you'd be attempting to set local storage associated with about:blank which doesn't make sense)

Before('@no-newsletter') do
  page.visit('/something') # visit a valid location to set localStorage
  page.execute_script "window.localStorage.setItem('subscribed','viewed');"
end
Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78