You are running into one of the challenges of working with pages that use a lot of ajax. The problem with ajax is that it makes it difficult for watir to know when the page is done loading.
What is happening in your script:
- The search field is inputted and the button is clicked
- The loading of the search results begins
- Watir thinks the page has finished loading
- The assertion gets run, which fails since the page has not finished loading the results
- The page actually finishes loading.
When you do this manually through irb, you likely wait long enough between clicking the button and checking the results that the page actually finishes loading.
If you change the assertion to a puts @browser.text
you will see that the page text only includes the heading of the page (the different links). If you do something like a sleep(5); puts @browser.text
, you will see that the text you expected appears.
The solution to this type of problem is to wait for the dynamically loaded element. While you could use sleep
, it is a bad choice since you could be waiting longer than you have to. Instead, use an implicit wait as described at http://watirwebdriver.com/waiting/.
The following script worked for me to resolve the timing issue. Basically it is waiting for the ol
element that contains the search results to appear.
require 'watir-webdriver'
require 'rspec'
item = 'watir'
@browser = Watir::Browser.new :ff
@browser.goto "http://www.google.com"
@browser.text_field(:name => "q").set(item)
@browser.button(:name => "btnG").click
@browser.ol(:id => 'rso').wait_until_present
@browser.text.include?(item).should == true
@browser.close
As an aside, note that instead of checking if the item
appears anywhere on the @browser.text
, it is better to check for something specific - for example are you expecting it in a link text, the blurb of the search result, etc. The problem with checking anywhere is that it can lead to false positives. For example, if item
is "search", you would always get true since the links at the bottom have that word. But really you wanted to see if it was in the search result.