Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watir/Rspec Browser Loop

I need some help using multiple browsers in a loop with Watir/Rspec.

  • My Goal is to:
    1. Go to Google.ca
    2. Quickly search something
    3. Close browser.
    4. Loop steps 1-3 using a different browser.

I can get this to work with using Watir, but do not know how to get this to work with Rspec.

Watir (working code):

require 'watir-webdriver'
require 'rspec'

  browsers = [:ff, :chrome]
  browsers.map do |x|
  $browser = Watir::Browser.new x
  $browser.goto('http://www.google.ca')
  $browser.text_field(:id, 'gbqfq').set 'Juventus'
  $browser.send_keys :enter
  $browser.close


end #End loop

Rspec (not working):

require 'watir-webdriver'
require 'rspec'

  browsers = [:ff, :chrome]
  browsers.map do |x|
  $browser = Watir::Browser.new x
  $browser.goto('http://www.google.ca')

  describe 'loop' do
    it 'does something' do
      $browser.text_field(:id, 'gbqfq').set 'Juventus'
      $browser.send_keys :enter
      $browser.close
    end
  end #End describe
end #End loop

This is what happens with the code above:

  • Loads Firefox
  • Goes to Google
  • Loads Chrome
  • Goes to Google
  • Searches on Chrome

It seems when I include Rspec describe the loop does not work as I had intended it to.

like image 213
Bashir Osman Avatar asked Sep 13 '26 10:09

Bashir Osman


1 Answers

Finally figured it out :)

Here is the code for anyone that wants to do multiple browser testing without making different specs for each browser.

require 'watir-webdriver'
require 'rspec'

      browsers = [:ff, :chrome]
      browsers.map do |x|

        describe 'Browser' do

        before(:all) do
          @browser = Watir::Browser.new x
        end

        it 'goes to Google.ca' do
          @browser.goto('http://www.google.ca')
        end

        it 'searches' do
          @browser.text_field(:id, 'gbqfq').when_present(3).set 'Juventus'
          @browser.send_keys :enter
          sleep 0.5 #roughly takes 0.5s for the images to load. 
        end

        it 'closes browser' do
          @browser.close
        end
      end #end describe
    end #end loop

I think for this to work properly you need to initialize the browser after describe whereas before I was initializing the browser before describe

like image 155
Bashir Osman Avatar answered Sep 16 '26 06:09

Bashir Osman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!