How to use visible_text method of Capybara.Driver Package

Best Capybara code snippet using Capybara.Driver.visible_text

driver_spec.rb

Source:driver_spec.rb Github

copy

Full Screen

...92 driver.find_xpath("//body[contains(., 'foobar')]").should_not be_empty93 end94 it "returns a node's text" do95 driver.within_frame("f") do96 driver.find_xpath("//p").first.visible_text.should == "goodbye"97 end98 end99 it "returns the current URL" do100 driver.within_frame("f") do101 driver.current_url.should == driver_url(driver, "/iframe")102 end103 end104 it "evaluates Javascript" do105 driver.within_frame("f") do106 result = driver.evaluate_script(%<document.getElementById('farewell').innerText>)107 result.should == "goodbye"108 end109 end110 it "executes Javascript" do111 driver.within_frame("f") do112 driver.execute_script(%<document.getElementById('farewell').innerHTML = 'yo'>)113 driver.find_xpath("//p[contains(., 'yo')]").should_not be_empty114 end115 end116 it "returns focus to parent" do117 original_url = driver.current_url118 driver.within_frame("f") {}119 driver.current_url.should == original_url120 end121 it "returns the headers for the page" do122 driver.within_frame("f") do123 driver.response_headers['X-Redirected'].should == "true"124 end125 end126 it "returns the status code for the page" do127 driver.within_frame("f") do128 driver.status_code.should == 200129 end130 end131 it "returns the document title" do132 driver.within_frame("f") do133 driver.title.should == "Title"134 end135 end136 end137 context "error iframe app" do138 let(:driver) do139 driver_for_app do140 get "/inner-not-found" do141 invalid_response142 end143 get "/" do144 <<-HTML145 <html>146 <body>147 <iframe src="/inner-not-found"></iframe>148 </body>149 </html>150 HTML151 end152 end153 end154 it "raises error whose message references the actual missing url" do155 expect { visit("/") }.to raise_error(Capybara::Webkit::InvalidResponseError, /inner-not-found/)156 end157 end158 context "redirect app" do159 let(:driver) do160 driver_for_app do161 enable :sessions162 get '/target' do163 headers 'X-Redirected' => (session.delete(:redirected) || false).to_s164 "<p>#{env['CONTENT_TYPE']}</p>"165 end166 get '/form' do167 <<-HTML168 <html>169 <body>170 <form action="/redirect" method="POST" enctype="multipart/form-data">171 <input name="submit" type="submit" />172 </form>173 </body>174 </html>175 HTML176 end177 post '/redirect' do178 redirect '/target'179 end180 get '/redirect-me' do181 if session[:redirected]182 redirect '/target'183 else184 session[:redirected] = true185 redirect '/redirect-me'186 end187 end188 end189 end190 it "should redirect without content type" do191 visit("/form")192 driver.find_xpath("//input").first.click193 driver.find_xpath("//p").first.visible_text.should == ""194 end195 it "returns the current URL when changed by pushState after a redirect" do196 visit("/redirect-me")197 driver.current_url.should == driver_url(driver, "/target")198 driver.execute_script("window.history.pushState({}, '', '/pushed-after-redirect')")199 driver.current_url.should == driver_url(driver, "/pushed-after-redirect")200 end201 it "returns the current URL when changed by replaceState after a redirect" do202 visit("/redirect-me")203 driver.current_url.should == driver_url(driver, "/target")204 driver.execute_script("window.history.replaceState({}, '', '/replaced-after-redirect')")205 driver.current_url.should == driver_url(driver, "/replaced-after-redirect")206 end207 it "should make headers available through response_headers" do208 visit('/redirect-me')209 driver.response_headers['X-Redirected'].should == "true"210 visit('/target')211 driver.response_headers['X-Redirected'].should == "false"212 end213 it "should make the status code available through status_code" do214 visit('/redirect-me')215 driver.status_code.should == 200216 visit('/target')217 driver.status_code.should == 200218 end219 end220 context "css app" do221 let(:driver) do222 driver_for_app do223 get "/" do224 headers "Content-Type" => "text/css"225 "css"226 end227 end228 end229 before { visit("/") }230 it "renders unsupported content types gracefully" do231 driver.html.should =~ /css/232 end233 it "sets the response headers with respect to the unsupported request" do234 driver.response_headers["Content-Type"].should == "text/css"235 end236 it "does not wrap the content in HTML tags" do237 driver.html.should_not =~ /<html>/238 end239 end240 context "html app" do241 let(:driver) do242 driver_for_html(<<-HTML)243 <html>244 <head>245 <title>Hello HTML</title>246 </head>247 <body>248 <h1>This Is HTML!</h1>249 </body>250 </html>251 HTML252 end253 before { visit("/") }254 it "does not strip HTML tags" do255 driver.html.should =~ /<html>/256 end257 end258 context "binary content app" do259 let(:driver) do260 driver_for_app do261 get '/' do262 headers 'Content-Type' => 'application/octet-stream'263 "Hello\xFF\xFF\xFF\xFFWorld"264 end265 end266 end267 before { visit("/") }268 it "should return the binary content" do269 src = driver.html.force_encoding('binary')270 src.should == "Hello\xFF\xFF\xFF\xFFWorld".force_encoding('binary')271 end272 end273 context "hello app" do274 let(:driver) do275 driver_for_html(<<-HTML)276 <html>277 <head>278 <title>Title</title>279 <style type="text/css">280 #display_none { display: none }281 #visibility_hidden { visibility: hidden }282 </style>283 </head>284 <body>285 <div class='normalize'>Spaces&nbsp;not&nbsp;normalized&nbsp;</div>286 <div id="display_none">287 <div id="invisible">Can't see me</div>288 </div>289 <div id="visibility_hidden">290 <div id="invisible_with_visibility">Can't see me too</div>291 </div>292 <div id="hidden-text">293 Some of this text is <em style="display:none">hidden!</em>294 </div>295 <input type="text" disabled="disabled"/>296 <input id="checktest" type="checkbox" checked="checked"/>297 <script type="text/javascript">298 document.write("<p id='greeting'>he" + "llo</p>");299 </script>300 </body>301 </html>302 HTML303 end304 before { visit("/") }305 it "handles anchor tags" do306 visit("#test")307 driver.find_xpath("//*[contains(., 'hello')]").should_not be_empty308 visit("#test")309 driver.find_xpath("//*[contains(., 'hello')]").should_not be_empty310 end311 it "finds content after loading a URL" do312 driver.find_xpath("//*[contains(., 'hello')]").should_not be_empty313 end314 it "has an empty page after reseting" do315 driver.reset!316 driver.find_xpath("//*[contains(., 'hello')]").should be_empty317 end318 it "has a blank location after reseting" do319 driver.reset!320 driver.current_url.should == "about:blank"321 end322 it "raises an error for an invalid xpath query" do323 expect { driver.find_xpath("totally invalid salad") }.324 to raise_error(Capybara::Webkit::InvalidResponseError, /xpath/i)325 end326 it "raises an error for an invalid xpath query within an element" do327 expect { driver.find_xpath("//body").first.find_xpath("totally invalid salad") }.328 to raise_error(Capybara::Webkit::InvalidResponseError, /xpath/i)329 end330 it "returns an attribute's value" do331 driver.find_xpath("//p").first["id"].should == "greeting"332 end333 it "parses xpath with quotes" do334 driver.find_xpath('//*[contains(., "hello")]').should_not be_empty335 end336 it "returns a node's visible text" do337 driver.find_xpath("//*[@id='hidden-text']").first.visible_text.should == "Some of this text is"338 end339 it "normalizes a node's text" do340 driver.find_xpath("//div[contains(@class, 'normalize')]").first.visible_text.should == "Spaces not normalized"341 end342 it "returns all of a node's text" do343 driver.find_xpath("//*[@id='hidden-text']").first.all_text.should == "Some of this text is hidden!"344 end345 it "returns the current URL" do346 visit "/hello/world?success=true"347 driver.current_url.should == driver_url(driver, "/hello/world?success=true")348 end349 it "returns the current URL when changed by pushState" do350 driver.execute_script("window.history.pushState({}, '', '/pushed')")351 driver.current_url.should == driver_url(driver, "/pushed")352 end353 it "returns the current URL when changed by replaceState" do354 driver.execute_script("window.history.replaceState({}, '', '/replaced')")355 driver.current_url.should == driver_url(driver, "/replaced")356 end357 it "does not double-encode URLs" do358 visit("/hello/world?success=%25true")359 driver.current_url.should =~ /success=\%25true/360 end361 it "visits a page with an anchor" do362 visit("/hello#display_none")363 driver.current_url.should =~ /hello#display_none/364 end365 it "evaluates Javascript and returns a string" do366 result = driver.evaluate_script(%<document.getElementById('greeting').innerText>)367 result.should == "hello"368 end369 it "evaluates Javascript and returns an array" do370 result = driver.evaluate_script(%<["hello", "world"]>)371 result.should == %w(hello world)372 end373 it "evaluates Javascript and returns an int" do374 result = driver.evaluate_script(%<123>)375 result.should == 123376 end377 it "evaluates Javascript and returns a float" do378 result = driver.evaluate_script(%<1.5>)379 result.should == 1.5380 end381 it "evaluates Javascript and returns null" do382 result = driver.evaluate_script(%<(function () {})()>)383 result.should == nil384 end385 it "evaluates Infinity and returns null" do386 result = driver.evaluate_script(%<Infinity>)387 result.should == nil388 end389 it "evaluates Javascript and returns an object" do390 result = driver.evaluate_script(%<({ 'one' : 1 })>)391 result.should == { 'one' => 1 }392 end393 it "evaluates Javascript and returns true" do394 result = driver.evaluate_script(%<true>)395 result.should === true396 end397 it "evaluates Javascript and returns false" do398 result = driver.evaluate_script(%<false>)399 result.should === false400 end401 it "evaluates Javascript and returns an escaped string" do402 result = driver.evaluate_script(%<'"'>)403 result.should === "\""404 end405 it "evaluates Javascript with multiple lines" do406 result = driver.evaluate_script("[1,\n2]")407 result.should == [1, 2]408 end409 it "executes Javascript" do410 driver.execute_script(%<document.getElementById('greeting').innerHTML = 'yo'>)411 driver.find_xpath("//p[contains(., 'yo')]").should_not be_empty412 end413 it "raises an error for failing Javascript" do414 expect { driver.execute_script(%<invalid salad>) }.415 to raise_error(Capybara::Webkit::InvalidResponseError)416 end417 it "doesn't raise an error for Javascript that doesn't return anything" do418 lambda { driver.execute_script(%<(function () { "returns nothing" })()>) }.419 should_not raise_error420 end421 it "returns a node's tag name" do422 driver.find_xpath("//p").first.tag_name.should == "p"423 end424 it "reads disabled property" do425 driver.find_xpath("//input").first.should be_disabled426 end427 it "reads checked property" do428 driver.find_xpath("//input[@id='checktest']").first.should be_checked429 end430 it "finds visible elements" do431 driver.find_xpath("//p").first.should be_visible432 driver.find_xpath("//*[@id='invisible']").first.should_not be_visible433 driver.find_xpath("//*[@id='invisible_with_visibility']").first.should_not be_visible434 end435 it "returns the document title" do436 driver.title.should == "Title"437 end438 it "finds elements by CSS" do439 driver.find_css("p").first.visible_text.should == "hello"440 end441 end442 context "svg app" do443 let(:driver) do444 driver_for_html(<<-HTML)445 <html>446 <body>447 <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100">448 <text x="10" y="25" fill="navy" font-size="15" id="navy_text">In the navy!</text>449 </svg>450 </body>451 </html>452 HTML453 end454 before { visit("/") }455 it "should handle text for svg elements" do456 driver.find_xpath("//*[@id='navy_text']").first.visible_text.should == "In the navy!"457 end458 end459 context "console messages app" do460 let(:driver) do461 driver_for_html(<<-HTML)462 <html>463 <head>464 <meta http-equiv="content-type" content="text/html; charset=UTF-8">465 </head>466 <body>467 <script type="text/javascript">468 console.log("hello");469 console.log("hello again");470 console.log("hello\\nnewline");471 console.log("𝄞");472 oops473 </script>474 </body>475 </html>476 HTML477 end478 before { visit("/") }479 it "collects messages logged to the console" do480 url = driver_url(driver, "/")481 message = driver.console_messages.first482 message.should include :source => url, :message => "hello"483 [6, 7].should include message[:line_number]484 driver.console_messages.length.should eq 5485 end486 it "logs errors to the console" do487 driver.error_messages.length.should eq 1488 end489 it "supports multi-line console messages" do490 message = driver.console_messages[2]491 message[:message].should == "hello\nnewline"492 end493 it "empties the array when reset" do494 driver.reset!495 driver.console_messages.should be_empty496 end497 it "supports console messages from an unknown source" do498 driver.execute_script("console.log('hello')")499 driver.console_messages.last[:message].should == 'hello'500 driver.console_messages.last[:source].should be_nil501 driver.console_messages.last[:line_number].should be_nil502 end503 it "escapes unicode console messages" do504 driver.console_messages[3][:message].should == '𝄞'505 end506 end507 context "javascript dialog interaction" do508 context "on an alert app" do509 let(:driver) do510 driver_for_html(<<-HTML)511 <html>512 <head>513 </head>514 <body>515 <script type="text/javascript">516 alert("Alert Text\\nGoes Here");517 </script>518 </body>519 </html>520 HTML521 end522 before { visit("/") }523 it "should let me read my alert messages" do524 driver.alert_messages.first.should == "Alert Text\nGoes Here"525 end526 it "empties the array when reset" do527 driver.reset!528 driver.alert_messages.should be_empty529 end530 end531 context "on a confirm app" do532 let(:driver) do533 driver_for_html(<<-HTML)534 <html>535 <head>536 </head>537 <body>538 <script type="text/javascript">539 function test_dialog() {540 if(confirm("Yes?"))541 console.log("hello");542 else543 console.log("goodbye");544 }545 </script>546 <input type="button" onclick="test_dialog()" name="test"/>547 </body>548 </html>549 HTML550 end551 before { visit("/") }552 it "should default to accept the confirm" do553 driver.find_xpath("//input").first.click554 driver.console_messages.first[:message].should == "hello"555 end556 it "can dismiss the confirm" do557 driver.dismiss_js_confirms!558 driver.find_xpath("//input").first.click559 driver.console_messages.first[:message].should == "goodbye"560 end561 it "can accept the confirm explicitly" do562 driver.dismiss_js_confirms!563 driver.accept_js_confirms!564 driver.find_xpath("//input").first.click565 driver.console_messages.first[:message].should == "hello"566 end567 it "should collect the javsacript confirm dialog contents" do568 driver.find_xpath("//input").first.click569 driver.confirm_messages.first.should == "Yes?"570 end571 it "empties the array when reset" do572 driver.find_xpath("//input").first.click573 driver.reset!574 driver.confirm_messages.should be_empty575 end576 it "resets to the default of accepting confirms" do577 driver.dismiss_js_confirms!578 driver.reset!579 visit("/")580 driver.find_xpath("//input").first.click581 driver.console_messages.first[:message].should == "hello"582 end583 it "supports multi-line confirmation messages" do584 driver.execute_script("confirm('Hello\\nnewline')")585 driver.confirm_messages.first.should == "Hello\nnewline"586 end587 end588 context "on a prompt app" do589 let(:driver) do590 driver_for_html(<<-HTML)591 <html>592 <head>593 </head>594 <body>595 <script type="text/javascript">596 function test_dialog() {597 var response = prompt("Your name?", "John Smith");598 if(response != null)599 console.log("hello " + response);600 else601 console.log("goodbye");602 }603 </script>604 <input type="button" onclick="test_dialog()" name="test"/>605 </body>606 </html>607 HTML608 end609 before { visit("/") }610 it "should default to dismiss the prompt" do611 driver.find_xpath("//input").first.click612 driver.console_messages.first[:message].should == "goodbye"613 end614 it "can accept the prompt without providing text" do615 driver.accept_js_prompts!616 driver.find_xpath("//input").first.click617 driver.console_messages.first[:message].should == "hello John Smith"618 end619 it "can accept the prompt with input" do620 driver.js_prompt_input = "Capy"621 driver.accept_js_prompts!622 driver.find_xpath("//input").first.click623 driver.console_messages.first[:message].should == "hello Capy"624 end625 it "can return to dismiss the prompt after accepting prompts" do626 driver.accept_js_prompts!627 driver.dismiss_js_prompts!628 driver.find_xpath("//input").first.click629 driver.console_messages.first[:message].should == "goodbye"630 end631 it "should let me remove the prompt input text" do632 driver.js_prompt_input = "Capy"633 driver.accept_js_prompts!634 driver.find_xpath("//input").first.click635 driver.console_messages.first[:message].should == "hello Capy"636 driver.js_prompt_input = nil637 driver.find_xpath("//input").first.click638 driver.console_messages.last[:message].should == "hello John Smith"639 end640 it "should collect the javsacript prompt dialog contents" do641 driver.find_xpath("//input").first.click642 driver.prompt_messages.first.should == "Your name?"643 end644 it "empties the array when reset" do645 driver.find_xpath("//input").first.click646 driver.reset!647 driver.prompt_messages.should be_empty648 end649 it "returns the prompt action to dismiss on reset" do650 driver.accept_js_prompts!651 driver.reset!652 visit("/")653 driver.find_xpath("//input").first.click654 driver.console_messages.first[:message].should == "goodbye"655 end656 it "supports multi-line prompt messages" do657 driver.execute_script("prompt('Hello\\nnewline')")658 driver.prompt_messages.first.should == "Hello\nnewline"659 end660 end661 end662 context "form app" do663 let(:driver) do664 driver_for_html(<<-HTML)665 <html><body>666 <form action="/" method="GET">667 <input type="text" name="foo" value="bar"/>668 <input type="text" name="maxlength_foo" value="bar" maxlength="10"/>669 <input type="text" id="disabled_input" disabled="disabled"/>670 <input type="text" id="readonly_input" readonly="readonly" value="readonly"/>671 <input type="checkbox" name="checkedbox" value="1" checked="checked"/>672 <input type="checkbox" name="uncheckedbox" value="2"/>673 <select name="animal">674 <option id="select-option-monkey">Monkey</option>675 <option id="select-option-capybara" selected="selected">Capybara</option>676 </select>677 <select name="disabled" disabled="disabled">678 <option id="select-option-disabled">Disabled</option>679 </select>680 <select name="toppings" multiple="multiple">681 <optgroup label="Mediocre Toppings">682 <option selected="selected" id="topping-apple">Apple</option>683 <option selected="selected" id="topping-banana">Banana</option>684 </optgroup>685 <optgroup label="Best Toppings">686 <option selected="selected" id="topping-cherry">Cherry</option>687 </optgroup>688 </select>689 <select name="guitars" multiple>690 <option selected="selected" id="fender">Fender</option>691 <option selected="selected" id="gibson">Gibson</option>692 </select>693 <textarea id="only-textarea">what a wonderful area for text</textarea>694 <input type="radio" id="only-radio" value="1"/>695 <button type="reset">Reset Form</button>696 </form>697 </body></html>698 HTML699 end700 before { visit("/") }701 it "returns a textarea's value" do702 driver.find_xpath("//textarea").first.value.should == "what a wonderful area for text"703 end704 it "returns a text input's value" do705 driver.find_xpath("//input").first.value.should == "bar"706 end707 it "returns a select's value" do708 driver.find_xpath("//select").first.value.should == "Capybara"709 end710 it "sets an input's value" do711 input = driver.find_xpath("//input").first712 input.set("newvalue")713 input.value.should == "newvalue"714 end715 it "sets an input's value greater than the max length" do716 input = driver.find_xpath("//input[@name='maxlength_foo']").first717 input.set("allegories (poems)")718 input.value.should == "allegories"719 end720 it "sets an input's value equal to the max length" do721 input = driver.find_xpath("//input[@name='maxlength_foo']").first722 input.set("allegories")723 input.value.should == "allegories"724 end725 it "sets an input's value less than the max length" do726 input = driver.find_xpath("//input[@name='maxlength_foo']").first727 input.set("poems")728 input.value.should == "poems"729 end730 it "sets an input's nil value" do731 input = driver.find_xpath("//input").first732 input.set(nil)733 input.value.should == ""734 end735 it "sets a select's value" do736 select = driver.find_xpath("//select").first737 select.set("Monkey")738 select.value.should == "Monkey"739 end740 it "sets a textarea's value" do741 textarea = driver.find_xpath("//textarea").first742 textarea.set("newvalue")743 textarea.value.should == "newvalue"744 end745 let(:monkey_option) { driver.find_xpath("//option[@id='select-option-monkey']").first }746 let(:capybara_option) { driver.find_xpath("//option[@id='select-option-capybara']").first }747 let(:animal_select) { driver.find_xpath("//select[@name='animal']").first }748 let(:apple_option) { driver.find_xpath("//option[@id='topping-apple']").first }749 let(:banana_option) { driver.find_xpath("//option[@id='topping-banana']").first }750 let(:cherry_option) { driver.find_xpath("//option[@id='topping-cherry']").first }751 let(:toppings_select) { driver.find_xpath("//select[@name='toppings']").first }752 let(:guitars_select) { driver.find_xpath("//select[@name='guitars']").first }753 let(:fender_option) { driver.find_xpath("//option[@id='fender']").first }754 let(:reset_button) { driver.find_xpath("//button[@type='reset']").first }755 context "a select element's selection has been changed" do756 before do757 animal_select.value.should == "Capybara"758 monkey_option.select_option759 end760 it "returns the new selection" do761 animal_select.value.should == "Monkey"762 end763 it "does not modify the selected attribute of a new selection" do764 monkey_option['selected'].should be_nil765 end766 it "returns the old value when a reset button is clicked" do767 reset_button.click768 animal_select.value.should == "Capybara"769 end770 end771 context "a multi-select element's option has been unselected" do772 before do773 toppings_select.value.should include("Apple", "Banana", "Cherry")774 apple_option.unselect_option775 end776 it "does not return the deselected option" do777 toppings_select.value.should_not include("Apple")778 end779 it "returns the deselected option when a reset button is clicked" do780 reset_button.click781 toppings_select.value.should include("Apple", "Banana", "Cherry")782 end783 end784 context "a multi-select (with empty multiple attribute) element's option has been unselected" do785 before do786 guitars_select.value.should include("Fender", "Gibson")787 fender_option.unselect_option788 end789 it "does not return the deselected option" do790 guitars_select.value.should_not include("Fender")791 end792 end793 it "reselects an option in a multi-select" do794 apple_option.unselect_option795 banana_option.unselect_option796 cherry_option.unselect_option797 toppings_select.value.should == []798 apple_option.select_option799 banana_option.select_option800 cherry_option.select_option801 toppings_select.value.should include("Apple", "Banana", "Cherry")802 end803 let(:checked_box) { driver.find_xpath("//input[@name='checkedbox']").first }804 let(:unchecked_box) { driver.find_xpath("//input[@name='uncheckedbox']").first }805 it "knows a checked box is checked" do806 checked_box['checked'].should be_true807 end808 it "knows a checked box is checked using checked?" do809 checked_box.should be_checked810 end811 it "knows an unchecked box is unchecked" do812 unchecked_box['checked'].should_not be_true813 end814 it "knows an unchecked box is unchecked using checked?" do815 unchecked_box.should_not be_checked816 end817 it "checks an unchecked box" do818 unchecked_box.set(true)819 unchecked_box.should be_checked820 end821 it "unchecks a checked box" do822 checked_box.set(false)823 checked_box.should_not be_checked824 end825 it "leaves a checked box checked" do826 checked_box.set(true)827 checked_box.should be_checked828 end829 it "leaves an unchecked box unchecked" do830 unchecked_box.set(false)831 unchecked_box.should_not be_checked832 end833 let(:enabled_input) { driver.find_xpath("//input[@name='foo']").first }834 let(:disabled_input) { driver.find_xpath("//input[@id='disabled_input']").first }835 it "knows a disabled input is disabled" do836 disabled_input['disabled'].should be_true837 end838 it "knows a not disabled input is not disabled" do839 enabled_input['disabled'].should_not be_true840 end841 it "does not modify a readonly input" do842 readonly_input = driver.find_css("#readonly_input").first843 readonly_input.set('enabled')844 readonly_input.value.should == 'readonly'845 end846 it "should see enabled options in disabled select as disabled" do847 driver.find_css("#select-option-disabled").first.should be_disabled848 end849 end850 context "dom events" do851 let(:driver) do852 driver_for_html(<<-HTML)853 <html><body>854 <a href='#' class='watch'>Link</a>855 <ul id="events"></ul>856 <script type="text/javascript">857 var events = document.getElementById("events");858 var recordEvent = function (event) {859 var element = document.createElement("li");860 element.innerHTML = event.type;861 events.appendChild(element);862 };863 var elements = document.getElementsByClassName("watch");864 for (var i = 0; i < elements.length; i++) {865 var element = elements[i];866 element.addEventListener("mousedown", recordEvent);867 element.addEventListener("mouseup", recordEvent);868 element.addEventListener("click", recordEvent);869 element.addEventListener("dblclick", recordEvent);870 element.addEventListener("contextmenu", recordEvent);871 }872 </script>873 </body></html>874 HTML875 end876 before { visit("/") }877 let(:watch) { driver.find_xpath("//a").first }878 let(:fired_events) { driver.find_xpath("//li").map(&:visible_text) }879 it "triggers mouse events" do880 watch.click881 fired_events.should == %w(mousedown mouseup click)882 end883 it "triggers double click" do884 # check event order at http://www.quirksmode.org/dom/events/click.html885 watch.double_click886 fired_events.should == %w(mousedown mouseup click mousedown mouseup click dblclick)887 end888 it "triggers right click" do889 watch.right_click890 fired_events.should == %w(mousedown contextmenu mouseup)891 end892 end893 context "form events app" do894 let(:driver) do895 driver_for_html(<<-HTML)896 <html><body>897 <form action="/" method="GET">898 <input class="watch" type="email"/>899 <input class="watch" type="number"/>900 <input class="watch" type="password"/>901 <input class="watch" type="search"/>902 <input class="watch" type="tel"/>903 <input class="watch" type="text"/>904 <input class="watch" type="url"/>905 <textarea class="watch"></textarea>906 <input class="watch" type="checkbox"/>907 <input class="watch" type="radio"/>908 </form>909 <ul id="events"></ul>910 <script type="text/javascript">911 var events = document.getElementById("events");912 var recordEvent = function (event) {913 var element = document.createElement("li");914 element.innerHTML = event.type;915 events.appendChild(element);916 };917 var elements = document.getElementsByClassName("watch");918 for (var i = 0; i < elements.length; i++) {919 var element = elements[i];920 element.addEventListener("focus", recordEvent);921 element.addEventListener("keydown", recordEvent);922 element.addEventListener("keypress", recordEvent);923 element.addEventListener("keyup", recordEvent);924 element.addEventListener("input", recordEvent);925 element.addEventListener("change", recordEvent);926 element.addEventListener("blur", recordEvent);927 element.addEventListener("mousedown", recordEvent);928 element.addEventListener("mouseup", recordEvent);929 element.addEventListener("click", recordEvent);930 }931 </script>932 </body></html>933 HTML934 end935 before { visit("/") }936 let(:newtext) { 'newvalue' }937 let(:keyevents) do938 (%w{focus} +939 newtext.length.times.collect { %w{keydown keypress input keyup} }940 ).flatten941 end942 %w(email number password search tel text url).each do | field_type |943 it "triggers text input events on inputs of type #{field_type}" do944 driver.find_xpath("//input[@type='#{field_type}']").first.set(newtext)945 driver.find_xpath("//li").map(&:visible_text).should == keyevents946 end947 end948 it "triggers textarea input events" do949 driver.find_xpath("//textarea").first.set(newtext)950 driver.find_xpath("//li").map(&:visible_text).should == keyevents951 end952 it "triggers radio input events" do953 driver.find_xpath("//input[@type='radio']").first.set(true)954 driver.find_xpath("//li").map(&:visible_text).should == %w(mousedown focus mouseup change click)955 end956 it "triggers checkbox events" do957 driver.find_xpath("//input[@type='checkbox']").first.set(true)958 driver.find_xpath("//li").map(&:visible_text).should == %w(mousedown focus mouseup change click)959 end960 end961 context "mouse app" do962 let(:driver) do963 driver_for_html(<<-HTML)964 <html>965 <head>966 <style type="text/css">967 #hover { max-width: 30em; }968 #hover span { line-height: 1.5; }969 #hover span:hover + .hidden { display: block; }970 .hidden { display: none; }971 </style>972 </head>973 <body>974 <div id="change">Change me</div>975 <div id="mouseup">Push me</div>976 <div id="mousedown">Release me</div>977 <div id="hover">978 <span>This really long paragraph has a lot of text and will wrap. This sentence ensures that we have four lines of text.</span>979 <div class="hidden">Text that only shows on hover.</div>980 </div>981 <form action="/" method="GET">982 <select id="change_select" name="change_select">983 <option value="1" id="option-1" selected="selected">one</option>984 <option value="2" id="option-2">two</option>985 </select>986 </form>987 <script type="text/javascript">988 document.getElementById("change_select").989 addEventListener("change", function () {990 this.className = "triggered";991 });992 document.getElementById("change").993 addEventListener("change", function () {994 this.className = "triggered";995 });996 document.getElementById("mouseup").997 addEventListener("mouseup", function () {998 this.className = "triggered";999 });1000 document.getElementById("mousedown").1001 addEventListener("mousedown", function () {1002 this.className = "triggered";1003 });1004 </script>1005 <a href="/next">Next</a>1006 </body></html>1007 HTML1008 end1009 before { visit("/") }1010 it "hovers an element" do1011 driver.find_css("#hover").first.visible_text.should_not =~ /Text that only shows on hover/1012 driver.find_css("#hover span").first.hover1013 driver.find_css("#hover").first.visible_text.should =~ /Text that only shows on hover/1014 end1015 it "hovers an element off the screen" do1016 driver.resize_window(200, 200)1017 driver.evaluate_script(<<-JS)1018 var element = document.getElementById('hover');1019 element.style.position = 'absolute';1020 element.style.left = '200px';1021 JS1022 driver.find_css("#hover").first.visible_text.should_not =~ /Text that only shows on hover/1023 driver.find_css("#hover span").first.hover1024 driver.find_css("#hover").first.visible_text.should =~ /Text that only shows on hover/1025 end1026 it "clicks an element" do1027 driver.find_xpath("//a").first.click1028 driver.current_url =~ %r{/next$}1029 end1030 it "fires a mouse event" do1031 driver.find_xpath("//*[@id='mouseup']").first.trigger("mouseup")1032 driver.find_xpath("//*[@class='triggered']").should_not be_empty1033 end1034 it "fires a non-mouse event" do1035 driver.find_xpath("//*[@id='change']").first.trigger("change")1036 driver.find_xpath("//*[@class='triggered']").should_not be_empty1037 end1038 it "fires a change on select" do1039 select = driver.find_xpath("//select").first1040 select.value.should == "1"1041 option = driver.find_xpath("//option[@id='option-2']").first1042 option.select_option1043 select.value.should == "2"1044 driver.find_xpath("//select[@class='triggered']").should_not be_empty1045 end1046 it "fires drag events" do1047 draggable = driver.find_xpath("//*[@id='mousedown']").first1048 container = driver.find_xpath("//*[@id='mouseup']").first1049 draggable.drag_to(container)1050 driver.find_xpath("//*[@class='triggered']").size.should == 11051 end1052 end1053 context "nesting app" do1054 let(:driver) do1055 driver_for_html(<<-HTML)1056 <html><body>1057 <div id="parent">1058 <div class="find">Expected</div>1059 </div>1060 <div class="find">Unexpected</div>1061 </body></html>1062 HTML1063 end1064 before { visit("/") }1065 it "evaluates nested xpath expressions" do1066 parent = driver.find_xpath("//*[@id='parent']").first1067 parent.find_xpath("./*[@class='find']").map(&:visible_text).should == %w(Expected)1068 end1069 it "finds elements by CSS" do1070 parent = driver.find_css("#parent").first1071 parent.find_css(".find").first.visible_text.should == "Expected"1072 end1073 end1074 context "slow app" do1075 it "waits for a request to load" do1076 result = ""1077 driver = driver_for_app do1078 get "/result" do1079 sleep(0.5)1080 result << "finished"1081 ""1082 end1083 get "/" do1084 %{<html><body><a href="/result">Go</a></body></html>}1085 end1086 end1087 visit("/", driver)1088 driver.find_xpath("//a").first.click1089 result.should == "finished"1090 end1091 end1092 context "error app" do1093 let(:driver) do1094 driver_for_app do1095 get "/error" do1096 invalid_response1097 end1098 get "/" do1099 <<-HTML1100 <html><body>1101 <form action="/error"><input type="submit"/></form>1102 </body></html>1103 HTML1104 end1105 end1106 end1107 before { visit("/") }1108 it "raises a webkit error for the requested url" do1109 expect {1110 driver.find_xpath("//input").first.click1111 wait_for_error_to_complete1112 driver.find_xpath("//body")1113 }.1114 to raise_error(Capybara::Webkit::InvalidResponseError, %r{/error})1115 end1116 def wait_for_error_to_complete1117 sleep(0.5)1118 end1119 end1120 context "slow error app" do1121 let(:driver) do1122 driver_for_app do1123 get "/error" do1124 sleep(1)1125 invalid_response1126 end1127 get "/" do1128 <<-HTML1129 <html><body>1130 <form action="/error"><input type="submit"/></form>1131 <p>hello</p>1132 </body></html>1133 HTML1134 end1135 end1136 end1137 before { visit("/") }1138 it "raises a webkit error and then continues" do1139 driver.find_xpath("//input").first.click1140 expect { driver.find_xpath("//p") }.to raise_error(Capybara::Webkit::InvalidResponseError)1141 visit("/")1142 driver.find_xpath("//p").first.visible_text.should == "hello"1143 end1144 end1145 context "popup app" do1146 let(:driver) do1147 driver_for_app do1148 get "/" do1149 sleep(0.5)1150 return <<-HTML1151 <html><body>1152 <script type="text/javascript">1153 alert("alert");1154 confirm("confirm");1155 prompt("prompt");1156 </script>1157 <p>success</p>1158 </body></html>1159 HTML1160 end1161 end1162 end1163 before { visit("/") }1164 it "doesn't crash from alerts" do1165 driver.find_xpath("//p").first.visible_text.should == "success"1166 end1167 end1168 context "custom header" do1169 let(:driver) do1170 driver_for_app do1171 get "/" do1172 <<-HTML1173 <html><body>1174 <p id="user-agent">#{env['HTTP_USER_AGENT']}</p>1175 <p id="x-capybara-webkit-header">#{env['HTTP_X_CAPYBARA_WEBKIT_HEADER']}</p>1176 <p id="accept">#{env['HTTP_ACCEPT']}</p>1177 <a href="/">/</a>1178 </body></html>1179 HTML1180 end1181 end1182 end1183 before { visit("/") }1184 before do1185 driver.header('user-agent', 'capybara-webkit/custom-user-agent')1186 driver.header('x-capybara-webkit-header', 'x-capybara-webkit-header')1187 driver.header('accept', 'text/html')1188 visit('/')1189 end1190 it "can set user_agent" do1191 driver.find_xpath('id("user-agent")').first.visible_text.should == 'capybara-webkit/custom-user-agent'1192 driver.evaluate_script('navigator.userAgent').should == 'capybara-webkit/custom-user-agent'1193 end1194 it "keep user_agent in next page" do1195 driver.find_xpath("//a").first.click1196 driver.find_xpath('id("user-agent")').first.visible_text.should == 'capybara-webkit/custom-user-agent'1197 driver.evaluate_script('navigator.userAgent').should == 'capybara-webkit/custom-user-agent'1198 end1199 it "can set custom header" do1200 driver.find_xpath('id("x-capybara-webkit-header")').first.visible_text.should == 'x-capybara-webkit-header'1201 end1202 it "can set Accept header" do1203 driver.find_xpath('id("accept")').first.visible_text.should == 'text/html'1204 end1205 it "can reset all custom header" do1206 driver.reset!1207 visit('/')1208 driver.find_xpath('id("user-agent")').first.visible_text.should_not == 'capybara-webkit/custom-user-agent'1209 driver.evaluate_script('navigator.userAgent').should_not == 'capybara-webkit/custom-user-agent'1210 driver.find_xpath('id("x-capybara-webkit-header")').first.visible_text.should be_empty1211 driver.find_xpath('id("accept")').first.visible_text.should_not == 'text/html'1212 end1213 end1214 context "no response app" do1215 let(:driver) do1216 driver_for_html(<<-HTML)1217 <html><body>1218 <form action="/error"><input type="submit"/></form>1219 </body></html>1220 HTML1221 end1222 before { visit("/") }1223 it "raises a webkit error for the requested url" do1224 make_the_server_go_away1225 expect {1226 driver.find_xpath("//body")1227 }.1228 to raise_error(Capybara::Webkit::NoResponseError, %r{response})1229 make_the_server_come_back1230 end1231 def make_the_server_come_back1232 driver.browser.instance_variable_get(:@connection).unstub!(:gets)1233 driver.browser.instance_variable_get(:@connection).unstub!(:puts)1234 driver.browser.instance_variable_get(:@connection).unstub!(:print)1235 end1236 def make_the_server_go_away1237 driver.browser.instance_variable_get(:@connection).stub!(:gets).and_return(nil)1238 driver.browser.instance_variable_get(:@connection).stub!(:puts)1239 driver.browser.instance_variable_get(:@connection).stub!(:print)1240 end1241 end1242 context "custom font app" do1243 let(:driver) do1244 driver_for_html(<<-HTML)1245 <html>1246 <head>1247 <style type="text/css">1248 p { font-family: "Verdana"; }1249 p:before { font-family: "Verdana"; }1250 p:after { font-family: "Verdana"; }1251 </style>1252 </head>1253 <body>1254 <p id="text">Hello</p>1255 </body>1256 </html>1257 HTML1258 end1259 before { visit("/") }1260 let(:font_family) do1261 driver.evaluate_script(<<-SCRIPT)1262 var element = document.getElementById("text");1263 element.ownerDocument.defaultView.getComputedStyle(element, null).getPropertyValue("font-family");1264 SCRIPT1265 end1266 it "ignores custom fonts" do1267 font_family.should == "Arial"1268 end1269 it "ignores custom fonts before an element" do1270 font_family.should == "Arial"1271 end1272 it "ignores custom fonts after an element" do1273 font_family.should == "Arial"1274 end1275 end1276 context "cookie-based app" do1277 let(:driver) do1278 driver_for_app do1279 get "/" do1280 headers 'Set-Cookie' => 'cookie=abc; domain=127.0.0.1; path=/'1281 <<-HTML1282 <html><body>1283 <p id="cookie">#{request.cookies["cookie"] || ""}</p>1284 </body></html>1285 HTML1286 end1287 end1288 end1289 before { visit("/") }1290 def echoed_cookie1291 driver.find_xpath('id("cookie")').first.visible_text1292 end1293 it "remembers the cookie on second visit" do1294 echoed_cookie.should == ""1295 visit "/"1296 echoed_cookie.should == "abc"1297 end1298 it "uses a custom cookie" do1299 driver.browser.set_cookie 'cookie=abc; domain=127.0.0.1; path=/'1300 visit "/"1301 echoed_cookie.should == "abc"1302 end1303 it "clears cookies" do1304 driver.browser.clear_cookies1305 visit "/"1306 echoed_cookie.should == ""1307 end1308 it "allows enumeration of cookies" do1309 cookies = driver.browser.get_cookies1310 cookies.size.should == 11311 cookie = Hash[cookies[0].split(/\s*;\s*/).map { |x| x.split("=", 2) }]1312 cookie["cookie"].should == "abc"1313 cookie["domain"].should include "127.0.0.1"1314 cookie["path"].should == "/"1315 end1316 it "allows reading access to cookies using a nice syntax" do1317 driver.cookies["cookie"].should == "abc"1318 end1319 end1320 context "remove node app" do1321 let(:driver) do1322 driver_for_html(<<-HTML)1323 <html>1324 <div id="parent">1325 <p id="removeMe">Hello</p>1326 </div>1327 </html>1328 HTML1329 end1330 before { visit("/") }1331 before { set_automatic_reload false }1332 after { set_automatic_reload true }1333 def set_automatic_reload(value)1334 if Capybara.respond_to?(:automatic_reload)1335 Capybara.automatic_reload = value1336 end1337 end1338 it "allows removed nodes when reloading is disabled" do1339 node = driver.find_xpath("//p[@id='removeMe']").first1340 driver.evaluate_script("document.getElementById('parent').innerHTML = 'Magic'")1341 node.visible_text.should == 'Hello'1342 end1343 end1344 context "app with a lot of HTML tags" do1345 let(:driver) do1346 driver_for_html(<<-HTML)1347 <html>1348 <head>1349 <title>My eBook</title>1350 <meta class="charset" name="charset" value="utf-8" />1351 <meta class="author" name="author" value="Firstname Lastname" />1352 </head>1353 <body>1354 <div id="toc">1355 <table>1356 <thead id="head">1357 <tr><td class="td1">Chapter</td><td>Page</td></tr>1358 </thead>1359 <tbody>1360 <tr><td>Intro</td><td>1</td></tr>1361 <tr><td>Chapter 1</td><td class="td2">1</td></tr>1362 <tr><td>Chapter 2</td><td>1</td></tr>1363 </tbody>1364 </table>1365 </div>1366 <h1 class="h1">My first book</h1>1367 <p class="p1">Written by me</p>1368 <div id="intro" class="intro">1369 <p>Let's try out XPath</p>1370 <p class="p2">in capybara-webkit</p>1371 </div>1372 <h2 class="chapter1">Chapter 1</h2>1373 <p>This paragraph is fascinating.</p>1374 <p class="p3">But not as much as this one.</p>1375 <h2 class="chapter2">Chapter 2</h2>1376 <p>Let's try if we can select this</p>1377 </body>1378 </html>1379 HTML1380 end1381 before { visit("/") }1382 it "builds up node paths correctly" do1383 cases = {1384 "//*[contains(@class, 'author')]" => "/html/head/meta[2]",1385 "//*[contains(@class, 'td1')]" => "/html/body/div[@id='toc']/table/thead[@id='head']/tr/td[1]",1386 "//*[contains(@class, 'td2')]" => "/html/body/div[@id='toc']/table/tbody/tr[2]/td[2]",1387 "//h1" => "/html/body/h1",1388 "//*[contains(@class, 'chapter2')]" => "/html/body/h2[2]",1389 "//*[contains(@class, 'p1')]" => "/html/body/p[1]",1390 "//*[contains(@class, 'p2')]" => "/html/body/div[@id='intro']/p[2]",1391 "//*[contains(@class, 'p3')]" => "/html/body/p[3]",1392 }1393 cases.each do |xpath, path|1394 nodes = driver.find_xpath(xpath)1395 nodes.size.should == 11396 nodes[0].path.should == path1397 end1398 end1399 end1400 context "css overflow app" do1401 let(:driver) do1402 driver_for_html(<<-HTML)1403 <html>1404 <head>1405 <style type="text/css">1406 #overflow { overflow: hidden }1407 </style>1408 </head>1409 <body>1410 <div id="overflow">Overflow</div>1411 </body>1412 </html>1413 HTML1414 end1415 before { visit("/") }1416 it "handles overflow hidden" do1417 driver.find_xpath("//div[@id='overflow']").first.visible_text.should == "Overflow"1418 end1419 end1420 context "javascript redirect app" do1421 let(:driver) do1422 driver_for_app do1423 get '/redirect' do1424 <<-HTML1425 <html>1426 <script type="text/javascript">1427 window.location = "/";1428 </script>1429 </html>1430 HTML1431 end1432 get '/' do1433 "<html><p>finished</p></html>"1434 end1435 end1436 end1437 it "loads a page without error" do1438 10.times do1439 visit("/redirect")1440 driver.find_xpath("//p").first.visible_text.should == "finished"1441 end1442 end1443 end1444 context "localStorage works" do1445 let(:driver) do1446 driver_for_html(<<-HTML)1447 <html>1448 <body>1449 <span id='output'></span>1450 <script type="text/javascript">1451 if (typeof localStorage !== "undefined") {1452 if (!localStorage.refreshCounter) {1453 localStorage.refreshCounter = 0;1454 }1455 if (localStorage.refreshCounter++ > 0) {1456 document.getElementById("output").innerHTML = "localStorage is enabled";1457 }1458 }1459 </script>1460 </body>1461 </html>1462 HTML1463 end1464 before { visit("/") }1465 it "displays the message on subsequent page loads" do1466 driver.find_xpath("//span[contains(.,'localStorage is enabled')]").should be_empty1467 visit "/"1468 driver.find_xpath("//span[contains(.,'localStorage is enabled')]").should_not be_empty1469 end1470 it "clears the message after a driver reset!" do1471 visit "/"1472 driver.find_xpath("//span[contains(.,'localStorage is enabled')]").should_not be_empty1473 driver.reset!1474 visit "/"1475 driver.find_xpath("//span[contains(.,'localStorage is enabled')]").should be_empty1476 end1477 end1478 context "form app with server-side handler" do1479 let(:driver) do1480 driver_for_app do1481 post "/" do1482 "<html><body><p>Congrats!</p></body></html>"1483 end1484 get "/" do1485 <<-HTML1486 <html>1487 <head><title>Form</title>1488 <body>1489 <form action="/" method="POST">1490 <input type="hidden" name="abc" value="123" />1491 <input type="submit" value="Submit" />1492 </form>1493 </body>1494 </html>1495 HTML1496 end1497 end1498 end1499 before { visit("/") }1500 it "submits a form without clicking" do1501 driver.find_xpath("//form")[0].submit1502 driver.html.should include "Congrats"1503 end1504 end1505 def driver_for_key_body(event)1506 driver_for_app do1507 get "/" do1508 <<-HTML1509 <html>1510 <head><title>Form</title></head>1511 <body>1512 <div id="charcode_value"></div>1513 <div id="keycode_value"></div>1514 <div id="which_value"></div>1515 <input type="text" id="charcode" name="charcode" on#{event}="setcharcode" />1516 <script type="text/javascript">1517 var element = document.getElementById("charcode")1518 element.addEventListener("#{event}", setcharcode);1519 function setcharcode(event) {1520 var element = document.getElementById("charcode_value");1521 element.innerHTML = event.charCode;1522 element = document.getElementById("keycode_value");1523 element.innerHTML = event.keyCode;1524 element = document.getElementById("which_value");1525 element.innerHTML = event.which;1526 }1527 </script>1528 </body>1529 </html>1530 HTML1531 end1532 end1533 end1534 def charCode_for(character)1535 driver.find_xpath("//input")[0].set(character)1536 driver.find_xpath("//div[@id='charcode_value']")[0].visible_text1537 end1538 def keyCode_for(character)1539 driver.find_xpath("//input")[0].set(character)1540 driver.find_xpath("//div[@id='keycode_value']")[0].visible_text1541 end1542 def which_for(character)1543 driver.find_xpath("//input")[0].set(character)1544 driver.find_xpath("//div[@id='which_value']")[0].visible_text1545 end1546 context "keypress app" do1547 let(:driver) { driver_for_key_body "keypress" }1548 before { visit("/") }1549 it "returns the charCode for the keypressed" do1550 charCode_for("a").should == "97"1551 charCode_for("A").should == "65"1552 charCode_for("\r").should == "13"1553 charCode_for(",").should == "44"1554 charCode_for("<").should == "60"1555 charCode_for("0").should == "48"1556 end1557 it "returns the keyCode for the keypressed" do1558 keyCode_for("a").should == "97"1559 keyCode_for("A").should == "65"1560 keyCode_for("\r").should == "13"1561 keyCode_for(",").should == "44"1562 keyCode_for("<").should == "60"1563 keyCode_for("0").should == "48"1564 end1565 it "returns the which for the keypressed" do1566 which_for("a").should == "97"1567 which_for("A").should == "65"1568 which_for("\r").should == "13"1569 which_for(",").should == "44"1570 which_for("<").should == "60"1571 which_for("0").should == "48"1572 end1573 end1574 shared_examples "a keyupdown app" do1575 it "returns a 0 charCode for the event" do1576 charCode_for("a").should == "0"1577 charCode_for("A").should == "0"1578 charCode_for("\b").should == "0"1579 charCode_for(",").should == "0"1580 charCode_for("<").should == "0"1581 charCode_for("0").should == "0"1582 end1583 it "returns the keyCode for the event" do1584 keyCode_for("a").should == "65"1585 keyCode_for("A").should == "65"1586 keyCode_for("\b").should == "8"1587 keyCode_for(",").should == "188"1588 keyCode_for("<").should == "188"1589 keyCode_for("0").should == "48"1590 end1591 it "returns the which for the event" do1592 which_for("a").should == "65"1593 which_for("A").should == "65"1594 which_for("\b").should == "8"1595 which_for(",").should == "188"1596 which_for("<").should == "188"1597 which_for("0").should == "48"1598 end1599 end1600 context "keydown app" do1601 let(:driver) { driver_for_key_body "keydown" }1602 before { visit("/") }1603 it_behaves_like "a keyupdown app"1604 end1605 context "keyup app" do1606 let(:driver) { driver_for_key_body "keyup" }1607 before { visit("/") }1608 it_behaves_like "a keyupdown app"1609 end1610 context "javascript new window app" do1611 let(:driver) do1612 driver_for_app do1613 get '/new_window' do1614 <<-HTML1615 <html>1616 <script type="text/javascript">1617 window.open('http://#{request.host_with_port}/?#{request.query_string}', 'myWindow');1618 </script>1619 <p>bananas</p>1620 </html>1621 HTML1622 end1623 get "/" do1624 sleep params['sleep'].to_i if params['sleep']1625 "<html><head><title>My New Window</title></head><body><p>finished</p></body></html>"1626 end1627 end1628 end1629 before { visit("/") }1630 it "has the expected text in the new window" do1631 visit("/new_window")1632 driver.within_window(driver.window_handles.last) do1633 driver.find_xpath("//p").first.visible_text.should == "finished"1634 end1635 end1636 it "waits for the new window to load" do1637 visit("/new_window?sleep=1")1638 driver.within_window(driver.window_handles.last) do1639 driver.find_xpath("//p").first.visible_text.should == "finished"1640 end1641 end1642 it "waits for the new window to load when the window location has changed" do1643 visit("/new_window?sleep=2")1644 driver.execute_script("setTimeout(function() { window.location = 'about:blank' }, 1000)")1645 driver.within_window(driver.window_handles.last) do1646 driver.find_xpath("//p").first.visible_text.should == "finished"1647 end1648 end1649 it "switches back to the original window" do1650 visit("/new_window")1651 driver.within_window(driver.window_handles.last) { }1652 driver.find_xpath("//p").first.visible_text.should == "bananas"1653 end1654 it "supports finding a window by name" do1655 visit("/new_window")1656 driver.within_window('myWindow') do1657 driver.find_xpath("//p").first.visible_text.should == "finished"1658 end1659 end1660 it "supports finding a window by title" do1661 visit("/new_window?sleep=5")1662 driver.within_window('My New Window') do1663 driver.find_xpath("//p").first.visible_text.should == "finished"1664 end1665 end1666 it "supports finding a window by url" do1667 visit("/new_window?test")1668 driver.within_window(driver_url(driver, "/?test")) do1669 driver.find_xpath("//p").first.visible_text.should == "finished"1670 end1671 end1672 it "raises an error if the window is not found" do1673 expect { driver.within_window('myWindowDoesNotExist') }.1674 to raise_error(Capybara::Webkit::InvalidResponseError)1675 end1676 it "has a number of window handles equal to the number of open windows" do1677 driver.window_handles.size.should == 11678 visit("/new_window")1679 driver.window_handles.size.should == 21680 end1681 it "closes new windows on reset" do1682 visit("/new_window")1683 last_handle = driver.window_handles.last1684 driver.reset!1685 driver.window_handles.should_not include(last_handle)1686 end1687 end1688 it "preserves cookies across windows" do1689 session_id = '12345'1690 driver = driver_for_app do1691 get '/new_window' do1692 <<-HTML1693 <html>1694 <script type="text/javascript">1695 window.open('http://#{request.host_with_port}/set_cookie');1696 </script>1697 </html>1698 HTML1699 end1700 get '/set_cookie' do1701 response.set_cookie 'session_id', session_id1702 end1703 end1704 visit("/new_window", driver)1705 driver.cookies['session_id'].should == session_id1706 end1707 context "timers app" do1708 let(:driver) do1709 driver_for_app do1710 get "/success" do1711 '<html><body></body></html>'1712 end1713 get "/not-found" do1714 4041715 end1716 get "/outer" do1717 <<-HTML1718 <html>1719 <head>1720 <script>1721 function emit_true_load_finished(){var divTag = document.createElement("div");divTag.innerHTML = "<iframe src='/success'></iframe>";document.body.appendChild(divTag);};1722 function emit_false_load_finished(){var divTag = document.createElement("div");divTag.innerHTML = "<iframe src='/not-found'></iframe>";document.body.appendChild(divTag);};1723 function emit_false_true_load_finished() { emit_false_load_finished(); setTimeout('emit_true_load_finished()',100); };1724 </script>1725 </head>1726 <body onload="setTimeout('emit_false_true_load_finished()',100)">1727 </body>1728 </html>1729 HTML1730 end1731 get '/' do1732 "<html><body></body></html>"1733 end1734 end1735 end1736 before { visit("/") }1737 it "raises error for any loadFinished failure" do1738 expect do1739 visit("/outer")1740 sleep 11741 driver.find_xpath("//body")1742 end.to raise_error(Capybara::Webkit::InvalidResponseError)1743 end1744 end1745 describe "basic auth" do1746 let(:driver) do1747 driver_for_app do1748 get "/" do1749 if env["HTTP_AUTHORIZATION"] == "Basic #{Base64.encode64("user:password").strip}"1750 env["HTTP_AUTHORIZATION"]1751 else1752 headers "WWW-Authenticate" => 'Basic realm="Secure Area"'1753 status 4011754 "401 Unauthorized."1755 end1756 end1757 get "/reset" do1758 headers "WWW-Authenticate" => 'Basic realm="Secure Area"'1759 status 4011760 "401 Unauthorized."1761 end1762 end1763 end1764 before do1765 visit('/reset')1766 end1767 it "can authenticate a request" do1768 driver.browser.authenticate('user', 'password')1769 visit("/")1770 driver.html.should include("Basic "+Base64.encode64("user:password").strip)1771 end1772 it "returns 401 for incorrectly authenticated request" do1773 driver.browser.authenticate('user1', 'password1')1774 driver.browser.timeout = 21775 lambda { visit("/") }.should_not raise_error(Timeout::Error)1776 driver.status_code.should == 4011777 end1778 it "returns 401 for unauthenticated request" do1779 driver.browser.timeout = 21780 lambda { visit("/") }.should_not raise_error(Timeout::Error)1781 driver.status_code.should == 4011782 end1783 end1784 describe "url blacklisting" do1785 let(:driver) do1786 driver_for_app do1787 get "/" do1788 <<-HTML1789 <html>1790 <body>1791 <script src="/script"></script>1792 <iframe src="http://example.com/path" id="frame1"></iframe>1793 <iframe src="http://example.org/path/to/file" id="frame2"></iframe>1794 <iframe src="/frame" id="frame3"></iframe>1795 </body>1796 </html>1797 HTML1798 end1799 get "/frame" do1800 <<-HTML1801 <html>1802 <body>1803 <p>Inner</p>1804 </body>1805 </html>1806 HTML1807 end1808 get "/script" do1809 <<-JS1810 document.write('<p>Script Run</p>')1811 JS1812 end1813 end1814 end1815 before do1816 driver.browser.url_blacklist = ["http://example.org/path/to/file",1817 "http://example.com",1818 "#{AppRunner.app_host}/script"]1819 end1820 it "should not fetch urls blocked by host" do1821 visit("/")1822 driver.within_frame('frame1') do1823 driver.find_xpath("//body").first.visible_text.should be_empty1824 end1825 end1826 it "should not fetch urls blocked by path" do1827 visit('/')1828 driver.within_frame('frame2') do1829 driver.find_xpath("//body").first.visible_text.should be_empty1830 end1831 end1832 it "should not fetch blocked scripts" do1833 visit("/")1834 driver.html.should_not include("Script Run")1835 end1836 it "should fetch unblocked urls" do1837 visit('/')1838 driver.within_frame('frame3') do1839 driver.find_xpath("//p").first.visible_text.should == "Inner"1840 end1841 end1842 it "returns a status code for blocked urls" do1843 visit("/")1844 driver.within_frame('frame1') do1845 driver.status_code.should == 2001846 end1847 end1848 end1849 describe "timeout for long requests" do1850 let(:driver) do1851 driver_for_app do1852 html = <<-HTML1853 <html>...

Full Screen

Full Screen

visible_text

Using AI Code Generation

copy

Full Screen

1 config.allow_url("www.google.com")2 def search_for(search_term)3 visit('/')4 fill_in('q', :with => search_term)5 click_button('Google Search')6google.search_for('capybara')

Full Screen

Full Screen

visible_text

Using AI Code Generation

copy

Full Screen

1visit('/')2fill_in('q', :with => 'ruby')3click_button('Google Search')4visit('/')5fill_in('q', :with => 'ruby')6click_button('Google Search')

Full Screen

Full Screen

visible_text

Using AI Code Generation

copy

Full Screen

1Capybara.visit('/')2Capybara.visit('/')3Capybara.visit('/')4Capybara.visit('/')5Capybara.visit('/')6Capybara.visit('/')7Capybara.visit('/')8Capybara.visit('/')9Capybara.visit('/')10Capybara.visit('/')11Capybara.visit('/')12Capybara.visit('/')13Capybara.visit('/')14Capybara.visit('/')15Capybara.visit('/')16Capybara.visit('/')17Capybara.visit('/')

Full Screen

Full Screen

visible_text

Using AI Code Generation

copy

Full Screen

1 config.allow_url("www.google.co.in")2 page.find(:xpath, "//body").text3 config.allow_url("www.google.co.in")4 config.allow_url("www.google.co.in")

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful