The Issue
Sometimes, when there is a need to run hundreds of automated tests, there will be cached memory every time a test is executed. Closing only the current tab/window of the web browser might increase the memory used by the system, and lead to memory leaks.
The Answer
The above-mentioned memory problem can be resolved with Selenium by using a function: quit().
There is another function in Selenium which is close() which closes only a single tab/window according to our requirement if we do not need to manage the cached memory completely. You can find the functionality of the close() function in our previous post, How To Use Selenium Function – Close().
The Code
Now, an example of how to use quit() function. The quit() function invokes another function called dispose(), which is responsible for flushing all the browser windows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Example for driver.quit() require 'selenium-webdriver' require 'rspec/expectations' include RSpec::Matchers Selenium::WebDriver::Chrome.driver_path="CHROME-DRIVER PATH" @driver = Selenium::WebDriver.for :chrome # Opening 3Qi Labs website in one tab @driver.get 'https://3qilabs.com/' # Opening a new browser window @driver.execute_script("window.open('');") # Switch to the new window to perform some actions @driver.switch_to.window(@driver.window_handles[1]) # Opening Google home page @driver.get("https://www.google.com/") # Opening a new browser window @driver.execute_script("window.open('');") # Switch to the new window to perform some actions @driver.switch_to.window(@driver.window_handles[2]) # Opening YouTube in the first window @driver.get("https://www.youtube.com/") puts "Quitting the browser" # Close all the tabs which will ultimately closes the browser @driver.quit() |
1 2 3 |
#Result after executing the above code Quitting the browser |
The Result
Steps performed by using the above-written code are
- Opens a new browser
- Navigates to “3Qi Labs website”
- Opens a new tab and switches to this new tab
- Navigates to “Google Home Page”
- Opens a second new tab and switches to this second new tab
- Navigates to “YouTube Home Page”
- Quits the entire browser closing all the tabs
The Takeaway
Selenium function quit() enables the user to terminate an entire browser (thereby closing all tabs) session. This can prevent memory leaks and issues when running a significant number of automated test cases.