Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 2168 lines (1851 sloc) 63.69 kb
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
# -*- encoding: UTF-8 -*-

require 'spec_helper'
require 'capybara/webkit/driver'
require 'base64'

describe Capybara::Webkit::Driver do
  include AppRunner

  def visit(url, driver=driver)
    driver.visit("#{AppRunner.app_host}#{url}")
  end

  context "iframe app" do
    let(:driver) do
      driver_for_app do
        get "/" do
          if params[:iframe] == "true"
            redirect '/iframe'
          else
            <<-HTML
<html>
<head>
<style type="text/css">
#display_none { display: none }
</style>
</head>
<body>
<iframe id="f" src="/?iframe=true"></iframe>
<script type="text/javascript">
document.write("<p id='greeting'>hello</p>");
</script>
</body>
</html>
HTML
          end
        end

        get '/iframe' do
          headers 'X-Redirected' => 'true'
          <<-HTML
<html>
<head>
<style type="text/css">
#display_none { display: none }
</style>
</head>
<body>
<script type="text/javascript">
document.write("<p id='farewell'>goodbye</p>");
</script>
</body>
</html>
HTML
        end
      end
    end

    before do
      visit("/")
    end

    it "finds frames by index" do
      driver.within_frame(0) do
        driver.find("//*[contains(., 'goodbye')]").should_not be_empty
      end
    end

    it "finds frames by id" do
      driver.within_frame("f") do
        driver.find("//*[contains(., 'goodbye')]").should_not be_empty
      end
    end

    it "raises error for missing frame by index" do
      expect { driver.within_frame(1) { } }.
        to raise_error(Capybara::Webkit::InvalidResponseError)
    end

    it "raise_error for missing frame by id" do
      expect { driver.within_frame("foo") { } }.
        to raise_error(Capybara::Webkit::InvalidResponseError)
    end

    it "returns an attribute's value" do
      driver.within_frame("f") do
        driver.find("//p").first["id"].should == "farewell"
      end
    end

    it "returns an attribute's innerHTML" do
      driver.find('//body').first.inner_html.should =~ %r{<iframe.*</iframe>.*<script.*</script>.*}m
    end

    it "receive an attribute's innerHTML" do
      driver.find('//body').first.inner_html = 'foobar'
      driver.find("//body[contains(., 'foobar')]").should_not be_empty
    end

    it "returns a node's text" do
      driver.within_frame("f") do
        driver.find("//p").first.text.should == "goodbye"
      end
    end

    it "returns the current URL" do
      driver.within_frame("f") do
        driver.current_url.should == driver_url(driver, "/iframe")
      end
    end

    it "evaluates Javascript" do
      driver.within_frame("f") do
        result = driver.evaluate_script(%<document.getElementById('farewell').innerText>)
        result.should == "goodbye"
      end
    end

    it "executes Javascript" do
      driver.within_frame("f") do
        driver.execute_script(%<document.getElementById('farewell').innerHTML = 'yo'>)
        driver.find("//p[contains(., 'yo')]").should_not be_empty
      end
    end

    it "returns focus to parent" do
      original_url = driver.current_url

      driver.within_frame("f") {}

      driver.current_url.should == original_url
    end

    it "returns the headers for the page" do
      driver.within_frame("f") do
        driver.response_headers['X-Redirected'].should == "true"
      end
    end

    it "returns the status code for the page" do
      driver.within_frame("f") do
        driver.status_code.should == 200
      end
    end
  end

  context "error iframe app" do
    let(:driver) do
      driver_for_app do
        get "/inner-not-found" do
          invalid_response
        end

        get "/" do
          <<-HTML
<html>
<body>
<iframe src="/inner-not-found"></iframe>
</body>
</html>
HTML
        end
      end
    end

    it "raises error whose message references the actual missing url" do
      expect { visit("/") }.to raise_error(Capybara::Webkit::InvalidResponseError, /inner-not-found/)
    end
  end

  context "redirect app" do
    let(:driver) do
      driver_for_app do
        enable :sessions

        get '/target' do
          headers 'X-Redirected' => (session.delete(:redirected) || false).to_s
          "<p>#{env['CONTENT_TYPE']}</p>"
        end

        get '/form' do
          <<-HTML
<html>
<body>
<form action="/redirect" method="POST" enctype="multipart/form-data">
<input name="submit" type="submit" />
</form>
</body>
</html>
HTML
        end

        post '/redirect' do
          redirect '/target'
        end

        get '/redirect-me' do
          if session[:redirected]
            redirect '/target'
          else
            session[:redirected] = true
            redirect '/redirect-me'
          end
        end
      end
    end

    it "should redirect without content type" do
      visit("/form")
      driver.find("//input").first.click
      driver.find("//p").first.text.should == ""
    end

    it "returns the current URL when changed by pushState after a redirect" do
      visit("/redirect-me")
      driver.current_url.should == driver_url(driver, "/target")
      driver.execute_script("window.history.pushState({}, '', '/pushed-after-redirect')")
      driver.current_url.should == driver_url(driver, "/pushed-after-redirect")
    end

    it "returns the current URL when changed by replaceState after a redirect" do
      visit("/redirect-me")
      driver.current_url.should == driver_url(driver, "/target")
      driver.execute_script("window.history.replaceState({}, '', '/replaced-after-redirect')")
      driver.current_url.should == driver_url(driver, "/replaced-after-redirect")
    end

    it "should make headers available through response_headers" do
      visit('/redirect-me')
      driver.response_headers['X-Redirected'].should == "true"
      visit('/target')
      driver.response_headers['X-Redirected'].should == "false"
    end

    it "should make the status code available through status_code" do
      visit('/redirect-me')
      driver.status_code.should == 200
      visit('/target')
      driver.status_code.should == 200
    end
  end

  context "css app" do
    let(:driver) do
      driver_for_app do
        get "/" do
          headers "Content-Type" => "text/css"
          "css"
        end
      end
    end

    before { visit("/") }

    it "renders unsupported content types gracefully" do
      driver.html.should =~ /css/
    end

    it "sets the response headers with respect to the unsupported request" do
      driver.response_headers["Content-Type"].should == "text/css"
    end

    it "does not wrap the content in HTML tags" do
      driver.html.should_not =~ /<html>/
    end
  end

  context "html app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<head>
<title>Hello HTML</title>
</head>
<body>
<h1>This Is HTML!</h1>
</body>
</html>
HTML
    end

    before { visit("/") }

    it "does not strip HTML tags" do
      driver.html.should =~ /<html>/
    end
  end

  context "hello app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<head>
<style type="text/css">
#display_none { display: none }
#visibility_hidden { visibility: hidden }
</style>
</head>
<body>
<div class='normalize'>Spaces&nbsp;not&nbsp;normalized&nbsp;</div>
<div id="display_none">
<div id="invisible">Can't see me</div>
</div>
<div id="visibility_hidden">
<div id="invisible_with_visibility">Can't see me too</div>
</div>
<input type="text" disabled="disabled"/>
<input id="checktest" type="checkbox" checked="checked"/>
<script type="text/javascript">
document.write("<p id='greeting'>he" + "llo</p>");
</script>
</body>
</html>
HTML
    end

    before { visit("/") }

    it "handles anchor tags" do
      visit("#test")
      driver.find("//*[contains(., 'hello')]").should_not be_empty
      visit("#test")
      driver.find("//*[contains(., 'hello')]").should_not be_empty
    end

    it "finds content after loading a URL" do
      driver.find("//*[contains(., 'hello')]").should_not be_empty
    end

    it "has an empty page after reseting" do
      driver.reset!
      driver.find("//*[contains(., 'hello')]").should be_empty
    end

    it "has a blank location after reseting" do
      driver.reset!
      driver.current_url.should == "about:blank"
    end

    it "raises an error for an invalid xpath query" do
      expect { driver.find("totally invalid salad") }.
        to raise_error(Capybara::Webkit::InvalidResponseError, /xpath/i)
    end

    it "returns an attribute's value" do
      driver.find("//p").first["id"].should == "greeting"
    end

    it "parses xpath with quotes" do
      driver.find('//*[contains(., "hello")]').should_not be_empty
    end

    it "returns a node's text" do
      driver.find("//p").first.text.should == "hello"
    end

    it "normalizes a node's text" do
      driver.find("//div[contains(@class, 'normalize')]").first.text.should == "Spaces not normalized"
    end

    it "returns the current URL" do
      visit "/hello/world?success=true"
      driver.current_url.should == driver_url(driver, "/hello/world?success=true")
    end

    it "returns the current URL when changed by pushState" do
      driver.execute_script("window.history.pushState({}, '', '/pushed')")
      driver.current_url.should == driver_url(driver, "/pushed")
    end

    it "returns the current URL when changed by replaceState" do
      driver.execute_script("window.history.replaceState({}, '', '/replaced')")
      driver.current_url.should == driver_url(driver, "/replaced")
    end

    it "does not double-encode URLs" do
      visit("/hello/world?success=%25true")
      driver.current_url.should =~ /success=\%25true/
    end

    it "visits a page with an anchor" do
      visit("/hello#display_none")
      driver.current_url.should =~ /hello#display_none/
    end

    it "evaluates Javascript and returns a string" do
      result = driver.evaluate_script(%<document.getElementById('greeting').innerText>)
      result.should == "hello"
    end

    it "evaluates Javascript and returns an array" do
      result = driver.evaluate_script(%<["hello", "world"]>)
      result.should == %w(hello world)
    end

    it "evaluates Javascript and returns an int" do
      result = driver.evaluate_script(%<123>)
      result.should == 123
    end

    it "evaluates Javascript and returns a float" do
      result = driver.evaluate_script(%<1.5>)
      result.should == 1.5
    end

    it "evaluates Javascript and returns null" do
      result = driver.evaluate_script(%<(function () {})()>)
      result.should == nil
    end

    it "evaluates Infinity and returns null" do
      result = driver.evaluate_script(%<Infinity>)
      result.should == nil
    end

    it "evaluates Javascript and returns an object" do
      result = driver.evaluate_script(%<({ 'one' : 1 })>)
      result.should == { 'one' => 1 }
    end

    it "evaluates Javascript and returns true" do
      result = driver.evaluate_script(%<true>)
      result.should === true
    end

    it "evaluates Javascript and returns false" do
      result = driver.evaluate_script(%<false>)
      result.should === false
    end

    it "evaluates Javascript and returns an escaped string" do
      result = driver.evaluate_script(%<'"'>)
      result.should === "\""
    end

    it "evaluates Javascript with multiple lines" do
      result = driver.evaluate_script("[1,\n2]")
      result.should == [1, 2]
    end

    it "executes Javascript" do
      driver.execute_script(%<document.getElementById('greeting').innerHTML = 'yo'>)
      driver.find("//p[contains(., 'yo')]").should_not be_empty
    end

    it "raises an error for failing Javascript" do
      expect { driver.execute_script(%<invalid salad>) }.
        to raise_error(Capybara::Webkit::InvalidResponseError)
    end

    it "doesn't raise an error for Javascript that doesn't return anything" do
      lambda { driver.execute_script(%<(function () { "returns nothing" })()>) }.
        should_not raise_error
    end

    it "returns a node's tag name" do
      driver.find("//p").first.tag_name.should == "p"
    end

    it "reads disabled property" do
      driver.find("//input").first.should be_disabled
    end

    it "reads checked property" do
      driver.find("//input[@id='checktest']").first.should be_checked
    end

    it "finds visible elements" do
      driver.find("//p").first.should be_visible
      driver.find("//*[@id='invisible']").first.should_not be_visible
      driver.find("//*[@id='invisible_with_visibility']").first.should_not be_visible
    end
  end

  context "svg app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100">
<text x="10" y="25" fill="navy" font-size="15" id="navy_text">In the navy!</text>
</svg>
</body>
</html>
HTML
    end

    before { visit("/") }

    it "should handle text for svg elements" do
      driver.find("//*[@id='navy_text']").first.text.should == "In the navy!"
    end
  end

  context "console messages app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
console.log("hello");
console.log("hello again");
console.log("hello\\nnewline");
console.log("𝄞");
oops
</script>
</body>
</html>
HTML
    end

    before { visit("/") }

    it "collects messages logged to the console" do
      url = driver_url(driver, "/")
      message = driver.console_messages.first
      message.should include :source => url, :message => "hello"
      message[:line_number].should == 6
      driver.console_messages.length.should eq 5
    end

    it "logs errors to the console" do
      driver.error_messages.length.should eq 1
    end

    it "supports multi-line console messages" do
      message = driver.console_messages[2]
      message[:message].should == "hello\nnewline"
    end

    it "empties the array when reset" do
      driver.reset!
      driver.console_messages.should be_empty
    end

    it "supports console messages from an unknown source" do
      driver.execute_script("console.log('hello')")
      driver.console_messages.last[:message].should == 'hello'
      driver.console_messages.last[:source].should be_nil
      driver.console_messages.last[:line_number].should be_nil
    end

    it "escapes unicode console messages" do
      driver.console_messages[3][:message].should == '𝄞'
    end
  end

  context "javascript dialog interaction" do
    context "on an alert app" do
      let(:driver) do
        driver_for_html(<<-HTML)
<html>
<head>
</head>
<body>
<script type="text/javascript">
alert("Alert Text\\nGoes Here");
</script>
</body>
</html>
HTML
      end

      before { visit("/") }

      it "should let me read my alert messages" do
        driver.alert_messages.first.should == "Alert Text\nGoes Here"
      end

      it "empties the array when reset" do
        driver.reset!
        driver.alert_messages.should be_empty
      end
    end

    context "on a confirm app" do
      let(:driver) do
        driver_for_html(<<-HTML)
<html>
<head>
</head>
<body>
<script type="text/javascript">
function test_dialog() {
if(confirm("Yes?"))
console.log("hello");
else
console.log("goodbye");
}
</script>
<input type="button" onclick="test_dialog()" name="test"/>
</body>
</html>
HTML
      end

      before { visit("/") }

      it "should default to accept the confirm" do
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "hello"
      end

      it "can dismiss the confirm" do
        driver.dismiss_js_confirms!
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "goodbye"
      end

      it "can accept the confirm explicitly" do
        driver.dismiss_js_confirms!
        driver.accept_js_confirms!
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "hello"
      end

      it "should collect the javsacript confirm dialog contents" do
        driver.find("//input").first.click
        driver.confirm_messages.first.should == "Yes?"
      end

      it "empties the array when reset" do
        driver.find("//input").first.click
        driver.reset!
        driver.confirm_messages.should be_empty
      end

      it "resets to the default of accepting confirms" do
        driver.dismiss_js_confirms!
        driver.reset!
        visit("/")
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "hello"
      end

      it "supports multi-line confirmation messages" do
        driver.execute_script("confirm('Hello\\nnewline')")
        driver.confirm_messages.first.should == "Hello\nnewline"
      end

    end

    context "on a prompt app" do
      let(:driver) do
        driver_for_html(<<-HTML)
<html>
<head>
</head>
<body>
<script type="text/javascript">
function test_dialog() {
var response = prompt("Your name?", "John Smith");
if(response != null)
console.log("hello " + response);
else
console.log("goodbye");
}
</script>
<input type="button" onclick="test_dialog()" name="test"/>
</body>
</html>
HTML
      end

      before { visit("/") }

      it "should default to dismiss the prompt" do
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "goodbye"
      end

      it "can accept the prompt without providing text" do
        driver.accept_js_prompts!
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "hello John Smith"
      end

      it "can accept the prompt with input" do
        driver.js_prompt_input = "Capy"
        driver.accept_js_prompts!
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "hello Capy"
      end

      it "can return to dismiss the prompt after accepting prompts" do
        driver.accept_js_prompts!
        driver.dismiss_js_prompts!
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "goodbye"
      end

      it "should let me remove the prompt input text" do
        driver.js_prompt_input = "Capy"
        driver.accept_js_prompts!
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "hello Capy"
        driver.js_prompt_input = nil
        driver.find("//input").first.click
        driver.console_messages.last[:message].should == "hello John Smith"
      end

      it "should collect the javsacript prompt dialog contents" do
        driver.find("//input").first.click
        driver.prompt_messages.first.should == "Your name?"
      end

      it "empties the array when reset" do
        driver.find("//input").first.click
        driver.reset!
        driver.prompt_messages.should be_empty
      end

      it "returns the prompt action to dismiss on reset" do
        driver.accept_js_prompts!
        driver.reset!
        visit("/")
        driver.find("//input").first.click
        driver.console_messages.first[:message].should == "goodbye"
      end

      it "supports multi-line prompt messages" do
        driver.execute_script("prompt('Hello\\nnewline')")
        driver.prompt_messages.first.should == "Hello\nnewline"
      end

    end
  end

  context "form app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html><body>
<form action="/" method="GET">
<input type="text" name="foo" value="bar"/>
<input type="text" name="maxlength_foo" value="bar" maxlength="10"/>
<input type="text" id="disabled_input" disabled="disabled"/>
<input type="checkbox" name="checkedbox" value="1" checked="checked"/>
<input type="checkbox" name="uncheckedbox" value="2"/>
<select name="animal">
<option id="select-option-monkey">Monkey</option>
<option id="select-option-capybara" selected="selected">Capybara</option>
</select>
<select name="toppings" multiple="multiple">
<optgroup label="Mediocre Toppings">
<option selected="selected" id="topping-apple">Apple</option>
<option selected="selected" id="topping-banana">Banana</option>
</optgroup>
<optgroup label="Best Toppings">
<option selected="selected" id="topping-cherry">Cherry</option>
</optgroup>
</select>
<select name="guitars" multiple>
<option selected="selected" id="fender">Fender</option>
<option selected="selected" id="gibson">Gibson</option>
</select>
<textarea id="only-textarea">what a wonderful area for text</textarea>
<input type="radio" id="only-radio" value="1"/>
<button type="reset">Reset Form</button>
</form>
</body></html>
HTML
    end

    before { visit("/") }

    it "returns a textarea's value" do
      driver.find("//textarea").first.value.should == "what a wonderful area for text"
    end

    it "returns a text input's value" do
      driver.find("//input").first.value.should == "bar"
    end

    it "returns a select's value" do
      driver.find("//select").first.value.should == "Capybara"
    end

    it "sets an input's value" do
      input = driver.find("//input").first
      input.set("newvalue")
      input.value.should == "newvalue"
    end

    it "sets an input's value greater than the max length" do
      input = driver.find("//input[@name='maxlength_foo']").first
      input.set("allegories (poems)")
      input.value.should == "allegories"
    end

    it "sets an input's value equal to the max length" do
      input = driver.find("//input[@name='maxlength_foo']").first
      input.set("allegories")
      input.value.should == "allegories"
    end

    it "sets an input's value less than the max length" do
      input = driver.find("//input[@name='maxlength_foo']").first
      input.set("poems")
      input.value.should == "poems"
    end

    it "sets an input's nil value" do
      input = driver.find("//input").first
      input.set(nil)
      input.value.should == ""
    end

    it "sets a select's value" do
      select = driver.find("//select").first
      select.set("Monkey")
      select.value.should == "Monkey"
    end

    it "sets a textarea's value" do
      textarea = driver.find("//textarea").first
      textarea.set("newvalue")
      textarea.value.should == "newvalue"
    end

    let(:monkey_option) { driver.find("//option[@id='select-option-monkey']").first }
    let(:capybara_option) { driver.find("//option[@id='select-option-capybara']").first }
    let(:animal_select) { driver.find("//select[@name='animal']").first }
    let(:apple_option) { driver.find("//option[@id='topping-apple']").first }
    let(:banana_option) { driver.find("//option[@id='topping-banana']").first }
    let(:cherry_option) { driver.find("//option[@id='topping-cherry']").first }
    let(:toppings_select) { driver.find("//select[@name='toppings']").first }
    let(:guitars_select) { driver.find("//select[@name='guitars']").first }
    let(:fender_option) { driver.find("//option[@id='fender']").first }
    let(:reset_button) { driver.find("//button[@type='reset']").first }

    context "a select element's selection has been changed" do
      before do
        animal_select.value.should == "Capybara"
        monkey_option.select_option
      end

      it "returns the new selection" do
        animal_select.value.should == "Monkey"
      end

      it "does not modify the selected attribute of a new selection" do
        monkey_option['selected'].should be_nil
      end

      it "returns the old value when a reset button is clicked" do
        reset_button.click

        animal_select.value.should == "Capybara"
      end
    end

    context "a multi-select element's option has been unselected" do
      before do
        toppings_select.value.should include("Apple", "Banana", "Cherry")

        apple_option.unselect_option
      end

      it "does not return the deselected option" do
        toppings_select.value.should_not include("Apple")
      end

      it "returns the deselected option when a reset button is clicked" do
        reset_button.click

        toppings_select.value.should include("Apple", "Banana", "Cherry")
      end
    end

    context "a multi-select (with empty multiple attribute) element's option has been unselected" do
      before do
        guitars_select.value.should include("Fender", "Gibson")

        fender_option.unselect_option
      end

      it "does not return the deselected option" do
        guitars_select.value.should_not include("Fender")
      end
    end

    it "reselects an option in a multi-select" do
      apple_option.unselect_option
      banana_option.unselect_option
      cherry_option.unselect_option

      toppings_select.value.should == []

      apple_option.select_option
      banana_option.select_option
      cherry_option.select_option

      toppings_select.value.should include("Apple", "Banana", "Cherry")
    end

    let(:checked_box) { driver.find("//input[@name='checkedbox']").first }
    let(:unchecked_box) { driver.find("//input[@name='uncheckedbox']").first }

    it "knows a checked box is checked" do
      checked_box['checked'].should be_true
    end

    it "knows a checked box is checked using checked?" do
      checked_box.should be_checked
    end

    it "knows an unchecked box is unchecked" do
      unchecked_box['checked'].should_not be_true
    end

    it "knows an unchecked box is unchecked using checked?" do
      unchecked_box.should_not be_checked
    end

    it "checks an unchecked box" do
      unchecked_box.set(true)
      unchecked_box.should be_checked
    end

    it "unchecks a checked box" do
      checked_box.set(false)
      checked_box.should_not be_checked
    end

    it "leaves a checked box checked" do
      checked_box.set(true)
      checked_box.should be_checked
    end

    it "leaves an unchecked box unchecked" do
      unchecked_box.set(false)
      unchecked_box.should_not be_checked
    end

    let(:enabled_input) { driver.find("//input[@name='foo']").first }
    let(:disabled_input) { driver.find("//input[@id='disabled_input']").first }

    it "knows a disabled input is disabled" do
      disabled_input['disabled'].should be_true
    end

    it "knows a not disabled input is not disabled" do
      enabled_input['disabled'].should_not be_true
    end
  end

  context "dom events" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html><body>
<a href='#' class='watch'>Link</a>
<ul id="events"></ul>
<script type="text/javascript">
var events = document.getElementById("events");
var recordEvent = function (event) {
var element = document.createElement("li");
element.innerHTML = event.type;
events.appendChild(element);
};

var elements = document.getElementsByClassName("watch");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.addEventListener("mousedown", recordEvent);
element.addEventListener("mouseup", recordEvent);
element.addEventListener("click", recordEvent);
}
</script>
</body></html>
HTML
    end

    before { visit("/") }

    it "triggers mouse events" do
      driver.find("//a").first.click
      driver.find("//li").map(&:text).should == %w(mousedown mouseup click)
    end
  end

  context "form events app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html><body>
<form action="/" method="GET">
<input class="watch" type="email"/>
<input class="watch" type="number"/>
<input class="watch" type="password"/>
<input class="watch" type="search"/>
<input class="watch" type="tel"/>
<input class="watch" type="text"/>
<input class="watch" type="url"/>
<textarea class="watch"></textarea>
<input class="watch" type="checkbox"/>
<input class="watch" type="radio"/>
</form>
<ul id="events"></ul>
<script type="text/javascript">
var events = document.getElementById("events");
var recordEvent = function (event) {
var element = document.createElement("li");
element.innerHTML = event.type;
events.appendChild(element);
};

var elements = document.getElementsByClassName("watch");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.addEventListener("focus", recordEvent);
element.addEventListener("keydown", recordEvent);
element.addEventListener("keypress", recordEvent);
element.addEventListener("keyup", recordEvent);
element.addEventListener("input", recordEvent);
element.addEventListener("change", recordEvent);
element.addEventListener("blur", recordEvent);
element.addEventListener("mousedown", recordEvent);
element.addEventListener("mouseup", recordEvent);
element.addEventListener("click", recordEvent);
}
</script>
</body></html>
HTML
    end

    before { visit("/") }

    let(:newtext) { 'newvalue' }

    let(:keyevents) do
      (%w{focus} +
       newtext.length.times.collect { %w{keydown keypress keyup input} } +
       %w{change}).flatten
    end

    %w(email number password search tel text url).each do | field_type |
      it "triggers text input events on inputs of type #{field_type}" do
        driver.find("//input[@type='#{field_type}']").first.set(newtext)
        driver.find("//li").map(&:text).should == keyevents
      end
    end

    it "triggers textarea input events" do
      driver.find("//textarea").first.set(newtext)
      driver.find("//li").map(&:text).should == keyevents
    end

    it "triggers radio input events" do
      driver.find("//input[@type='radio']").first.set(true)
      driver.find("//li").map(&:text).should == %w(mousedown focus mouseup change click)
    end

    it "triggers checkbox events" do
      driver.find("//input[@type='checkbox']").first.set(true)
      driver.find("//li").map(&:text).should == %w(mousedown focus mouseup change click)
    end
  end

  context "mouse app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html><body>
<div id="change">Change me</div>
<div id="mouseup">Push me</div>
<div id="mousedown">Release me</div>
<form action="/" method="GET">
<select id="change_select" name="change_select">
<option value="1" id="option-1" selected="selected">one</option>
<option value="2" id="option-2">two</option>
</select>
</form>
<script type="text/javascript">
document.getElementById("change_select").
addEventListener("change", function () {
this.className = "triggered";
});
document.getElementById("change").
addEventListener("change", function () {
this.className = "triggered";
});
document.getElementById("mouseup").
addEventListener("mouseup", function () {
this.className = "triggered";
});
document.getElementById("mousedown").
addEventListener("mousedown", function () {
this.className = "triggered";
});
</script>
<a href="/next">Next</a>
</body></html>
HTML
    end

    before { visit("/") }

    it "clicks an element" do
      driver.find("//a").first.click
      driver.current_url =~ %r{/next$}
    end

    it "fires a mouse event" do
      driver.find("//*[@id='mouseup']").first.trigger("mouseup")
      driver.find("//*[@class='triggered']").should_not be_empty
    end

    it "fires a non-mouse event" do
      driver.find("//*[@id='change']").first.trigger("change")
      driver.find("//*[@class='triggered']").should_not be_empty
    end

    it "fires a change on select" do
      select = driver.find("//select").first
      select.value.should == "1"
      option = driver.find("//option[@id='option-2']").first
      option.select_option
      select.value.should == "2"
      driver.find("//select[@class='triggered']").should_not be_empty
    end

    it "fires drag events" do
      draggable = driver.find("//*[@id='mousedown']").first
      container = driver.find("//*[@id='mouseup']").first

      draggable.drag_to(container)

      driver.find("//*[@class='triggered']").size.should == 1
    end
  end

  context "nesting app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html><body>
<div id="parent">
<div class="find">Expected</div>
</div>
<div class="find">Unexpected</div>
</body></html>
HTML
    end

    before { visit("/") }

    it "evaluates nested xpath expressions" do
      parent = driver.find("//*[@id='parent']").first
      parent.find("./*[@class='find']").map(&:text).should == %w(Expected)
    end
  end

  context "slow app" do
    it "waits for a request to load" do
      result = ""
      driver = driver_for_app do
        get "/result" do
          sleep(0.5)
          result << "finished"
          ""
        end

        get "/" do
          %{<html><body><a href="/result">Go</a></body></html>}
        end
      end
      visit("/", driver)
      driver.find("//a").first.click
      result.should == "finished"
    end
  end

  context "error app" do
    let(:driver) do
      driver_for_app do
        get "/error" do
          invalid_response
        end

        get "/" do
          <<-HTML
<html><body>
<form action="/error"><input type="submit"/></form>
</body></html>
HTML
        end
      end
    end

    before { visit("/") }

    it "raises a webkit error for the requested url" do
      expect {
        driver.find("//input").first.click
        wait_for_error_to_complete
        driver.find("//body")
      }.
        to raise_error(Capybara::Webkit::InvalidResponseError, %r{/error})
    end

    def wait_for_error_to_complete
      sleep(0.5)
    end
  end

  context "slow error app" do
    let(:driver) do
      driver_for_app do
        get "/error" do
          sleep(1)
          invalid_response
        end

        get "/" do
          <<-HTML
<html><body>
<form action="/error"><input type="submit"/></form>
<p>hello</p>
</body></html>
HTML
        end
      end
    end

    before { visit("/") }

    it "raises a webkit error and then continues" do
      driver.find("//input").first.click
      expect { driver.find("//p") }.to raise_error(Capybara::Webkit::InvalidResponseError)
      visit("/")
      driver.find("//p").first.text.should == "hello"
    end
  end

  context "popup app" do
    let(:driver) do
      driver_for_app do
        get "/" do
          sleep(0.5)
          return <<-HTML
<html><body>
<script type="text/javascript">
alert("alert");
confirm("confirm");
prompt("prompt");
</script>
<p>success</p>
</body></html>
HTML
        end
      end
    end

    before { visit("/") }

    it "doesn't crash from alerts" do
      driver.find("//p").first.text.should == "success"
    end
  end

  context "custom header" do
    let(:driver) do
      driver_for_app do
        get "/" do
          <<-HTML
<html><body>
<p id="user-agent">#{env['HTTP_USER_AGENT']}</p>
<p id="x-capybara-webkit-header">#{env['HTTP_X_CAPYBARA_WEBKIT_HEADER']}</p>
<p id="accept">#{env['HTTP_ACCEPT']}</p>
<a href="/">/</a>
</body></html>
HTML
        end
      end
    end

    before { visit("/") }

    before do
      driver.header('user-agent', 'capybara-webkit/custom-user-agent')
      driver.header('x-capybara-webkit-header', 'x-capybara-webkit-header')
      driver.header('accept', 'text/html')
      visit('/')
    end

    it "can set user_agent" do
      driver.find('id("user-agent")').first.text.should == 'capybara-webkit/custom-user-agent'
      driver.evaluate_script('navigator.userAgent').should == 'capybara-webkit/custom-user-agent'
    end

    it "keep user_agent in next page" do
      driver.find("//a").first.click
      driver.find('id("user-agent")').first.text.should == 'capybara-webkit/custom-user-agent'
      driver.evaluate_script('navigator.userAgent').should == 'capybara-webkit/custom-user-agent'
    end

    it "can set custom header" do
      driver.find('id("x-capybara-webkit-header")').first.text.should == 'x-capybara-webkit-header'
    end

    it "can set Accept header" do
      driver.find('id("accept")').first.text.should == 'text/html'
    end

    it "can reset all custom header" do
      driver.reset!
      visit('/')
      driver.find('id("user-agent")').first.text.should_not == 'capybara-webkit/custom-user-agent'
      driver.evaluate_script('navigator.userAgent').should_not == 'capybara-webkit/custom-user-agent'
      driver.find('id("x-capybara-webkit-header")').first.text.should be_empty
      driver.find('id("accept")').first.text.should_not == 'text/html'
    end
  end

  context "no response app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html><body>
<form action="/error"><input type="submit"/></form>
</body></html>
HTML
    end

    before { visit("/") }

    it "raises a webkit error for the requested url" do
      make_the_server_go_away
      expect {
        driver.find("//body")
      }.
       to raise_error(Capybara::Webkit::NoResponseError, %r{response})
      make_the_server_come_back
    end

    def make_the_server_come_back
      driver.browser.instance_variable_get(:@connection).unstub!(:gets)
      driver.browser.instance_variable_get(:@connection).unstub!(:puts)
      driver.browser.instance_variable_get(:@connection).unstub!(:print)
    end

    def make_the_server_go_away
      driver.browser.instance_variable_get(:@connection).stub!(:gets).and_return(nil)
      driver.browser.instance_variable_get(:@connection).stub!(:puts)
      driver.browser.instance_variable_get(:@connection).stub!(:print)
    end
  end

  context "custom font app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<head>
<style type="text/css">
p { font-family: "Verdana"; }
p:before { font-family: "Verdana"; }
p:after { font-family: "Verdana"; }
</style>
</head>
<body>
<p id="text">Hello</p>
</body>
</html>
HTML
    end

    before { visit("/") }

    let(:font_family) do
      driver.evaluate_script(<<-SCRIPT)
var element = document.getElementById("text");
element.ownerDocument.defaultView.getComputedStyle(element, null).getPropertyValue("font-family");
SCRIPT
    end

    it "ignores custom fonts" do
      font_family.should == "Arial"
    end

    it "ignores custom fonts before an element" do
      font_family.should == "Arial"
    end

    it "ignores custom fonts after an element" do
      font_family.should == "Arial"
    end
  end

  context "cookie-based app" do
    let(:driver) do
      driver_for_app do
        get "/" do
          headers 'Set-Cookie' => 'cookie=abc; domain=127.0.0.1; path=/'
          <<-HTML
<html><body>
<p id="cookie">#{request.cookies["cookie"] || ""}</p>
</body></html>
HTML
        end
      end
    end

    before { visit("/") }

    def echoed_cookie
      driver.find('id("cookie")').first.text
    end

    it "remembers the cookie on second visit" do
      echoed_cookie.should == ""
      visit "/"
      echoed_cookie.should == "abc"
    end

    it "uses a custom cookie" do
      driver.browser.set_cookie 'cookie=abc; domain=127.0.0.1; path=/'
      visit "/"
      echoed_cookie.should == "abc"
    end

    it "clears cookies" do
      driver.browser.clear_cookies
      visit "/"
      echoed_cookie.should == ""
    end

    it "allows enumeration of cookies" do
      cookies = driver.browser.get_cookies

      cookies.size.should == 1

      cookie = Hash[cookies[0].split(/\s*;\s*/).map { |x| x.split("=", 2) }]
      cookie["cookie"].should == "abc"
      cookie["domain"].should include "127.0.0.1"
      cookie["path"].should == "/"
    end

    it "allows reading access to cookies using a nice syntax" do
      driver.cookies["cookie"].should == "abc"
    end
  end

  context "remove node app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<div id="parent">
<p id="removeMe">Hello</p>
</div>
</html>
HTML
    end

    before { visit("/") }

    before { set_automatic_reload false }
    after { set_automatic_reload true }

    def set_automatic_reload(value)
      if Capybara.respond_to?(:automatic_reload)
        Capybara.automatic_reload = value
      end
    end

    it "allows removed nodes when reloading is disabled" do
      node = driver.find("//p[@id='removeMe']").first
      driver.evaluate_script("document.getElementById('parent').innerHTML = 'Magic'")
      node.text.should == 'Hello'
    end
  end

  context "app with a lot of HTML tags" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<head>
<title>My eBook</title>
<meta class="charset" name="charset" value="utf-8" />
<meta class="author" name="author" value="Firstname Lastname" />
</head>
<body>
<div id="toc">
<table>
<thead id="head">
<tr><td class="td1">Chapter</td><td>Page</td></tr>
</thead>
<tbody>
<tr><td>Intro</td><td>1</td></tr>
<tr><td>Chapter 1</td><td class="td2">1</td></tr>
<tr><td>Chapter 2</td><td>1</td></tr>
</tbody>
</table>
</div>

<h1 class="h1">My first book</h1>
<p class="p1">Written by me</p>
<div id="intro" class="intro">
<p>Let's try out XPath</p>
<p class="p2">in capybara-webkit</p>
</div>

<h2 class="chapter1">Chapter 1</h2>
<p>This paragraph is fascinating.</p>
<p class="p3">But not as much as this one.</p>

<h2 class="chapter2">Chapter 2</h2>
<p>Let's try if we can select this</p>
</body>
</html>
HTML
    end

    before { visit("/") }

    it "builds up node paths correctly" do
      cases = {
        "//*[contains(@class, 'author')]" => "/html/head/meta[2]",
        "//*[contains(@class, 'td1')]" => "/html/body/div[@id='toc']/table/thead[@id='head']/tr/td[1]",
        "//*[contains(@class, 'td2')]" => "/html/body/div[@id='toc']/table/tbody/tr[2]/td[2]",
        "//h1" => "/html/body/h1",
        "//*[contains(@class, 'chapter2')]" => "/html/body/h2[2]",
        "//*[contains(@class, 'p1')]" => "/html/body/p[1]",
        "//*[contains(@class, 'p2')]" => "/html/body/div[@id='intro']/p[2]",
        "//*[contains(@class, 'p3')]" => "/html/body/p[3]",
      }

      cases.each do |xpath, path|
        nodes = driver.find(xpath)
        nodes.size.should == 1
        nodes[0].path.should == path
      end
    end
  end

  context "css overflow app" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<head>
<style type="text/css">
#overflow { overflow: hidden }
</style>
</head>
<body>
<div id="overflow">Overflow</div>
</body>
</html>
HTML
    end

    before { visit("/") }

    it "handles overflow hidden" do
      driver.find("//div[@id='overflow']").first.text.should == "Overflow"
    end
  end

  context "javascript redirect app" do
    let(:driver) do
      driver_for_app do
        get '/redirect' do
          <<-HTML
<html>
<script type="text/javascript">
window.location = "/";
</script>
</html>
HTML
        end

        get '/' do
          "<html><p>finished</p></html>"
        end
      end
    end

    it "loads a page without error" do
      10.times do
        visit("/redirect")
        driver.find("//p").first.text.should == "finished"
      end
    end
  end

  context "localStorage works" do
    let(:driver) do
      driver_for_html(<<-HTML)
<html>
<body>
<span id='output'></span>
<script type="text/javascript">
if (typeof localStorage !== "undefined") {
if (!localStorage.refreshCounter) {
localStorage.refreshCounter = 0;
}
if (localStorage.refreshCounter++ > 0) {
document.getElementById("output").innerHTML = "localStorage is enabled";
}
}
</script>
</body>
</html>
HTML
    end

    before { visit("/") }

    it "displays the message on subsequent page loads" do
      driver.find("//span[contains(.,'localStorage is enabled')]").should be_empty
      visit "/"
      driver.find("//span[contains(.,'localStorage is enabled')]").should_not be_empty
    end
  end

  context "form app with server-side handler" do
    let(:driver) do
      driver_for_app do
        post "/" do
          "<html><body><p>Congrats!</p></body></html>"
        end

        get "/" do
          <<-HTML
<html>
<head><title>Form</title>
<body>
<form action="/" method="POST">
<input type="hidden" name="abc" value="123" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
HTML
        end
      end
    end

    before { visit("/") }

    it "submits a form without clicking" do
      driver.find("//form")[0].submit
      driver.html.should include "Congrats"
    end
  end

  def driver_for_key_body(event)
    driver_for_app do
      get "/" do
        <<-HTML
<html>
<head><title>Form</title></head>
<body>
<div id="charcode_value"></div>
<div id="keycode_value"></div>
<div id="which_value"></div>
<input type="text" id="charcode" name="charcode" on#{event}="setcharcode" />
<script type="text/javascript">
var element = document.getElementById("charcode")
element.addEventListener("#{event}", setcharcode);
function setcharcode(event) {
var element = document.getElementById("charcode_value");
element.innerHTML = event.charCode;
element = document.getElementById("keycode_value");
element.innerHTML = event.keyCode;
element = document.getElementById("which_value");
element.innerHTML = event.which;
}
</script>
</body>
</html>
HTML
      end
    end
  end

  def charCode_for(character)
    driver.find("//input")[0].set(character)
    driver.find("//div[@id='charcode_value']")[0].text
  end

  def keyCode_for(character)
    driver.find("//input")[0].set(character)
    driver.find("//div[@id='keycode_value']")[0].text
  end

  def which_for(character)
    driver.find("//input")[0].set(character)
    driver.find("//div[@id='which_value']")[0].text
  end

  context "keypress app" do
    let(:driver) { driver_for_key_body "keypress" }

    before { visit("/") }

    it "returns the charCode for the keypressed" do
      charCode_for("a").should == "97"
      charCode_for("A").should == "65"
      charCode_for("\r").should == "13"
      charCode_for(",").should == "44"
      charCode_for("<").should == "60"
      charCode_for("0").should == "48"
    end

    it "returns the keyCode for the keypressed" do
      keyCode_for("a").should == "97"
      keyCode_for("A").should == "65"
      keyCode_for("\r").should == "13"
      keyCode_for(",").should == "44"
      keyCode_for("<").should == "60"
      keyCode_for("0").should == "48"
    end

    it "returns the which for the keypressed" do
      which_for("a").should == "97"
      which_for("A").should == "65"
      which_for("\r").should == "13"
      which_for(",").should == "44"
      which_for("<").should == "60"
      which_for("0").should == "48"
    end
  end

  shared_examples "a keyupdown app" do
    it "returns a 0 charCode for the event" do
      charCode_for("a").should == "0"
      charCode_for("A").should == "0"
      charCode_for("\r").should == "0"
      charCode_for(",").should == "0"
      charCode_for("<").should == "0"
      charCode_for("0").should == "0"
    end

    it "returns the keyCode for the event" do
      keyCode_for("a").should == "65"
      keyCode_for("A").should == "65"
      keyCode_for("\r").should == "13"
      keyCode_for(",").should == "188"
      keyCode_for("<").should == "188"
      keyCode_for("0").should == "48"
    end

    it "returns the which for the event" do
      which_for("a").should == "65"
      which_for("A").should == "65"
      which_for("\r").should == "13"
      which_for(",").should == "188"
      which_for("<").should == "188"
      which_for("0").should == "48"
    end
  end

  context "keydown app" do
    let(:driver) { driver_for_key_body "keydown" }
    before { visit("/") }
    it_behaves_like "a keyupdown app"
  end

  context "keyup app" do
    let(:driver) { driver_for_key_body "keyup" }
    before { visit("/") }
    it_behaves_like "a keyupdown app"
  end

  context "javascript new window app" do
    let(:driver) do
      driver_for_app do
        get '/new_window' do
          <<-HTML
<html>
<script type="text/javascript">
window.open('http://#{request.host_with_port}/?#{request.query_string}', 'myWindow');
</script>
<p>bananas</p>
</html>
HTML
        end

        get "/" do
          sleep params['sleep'].to_i if params['sleep']
          "<html><head><title>My New Window</title></head><body><p>finished</p></body></html>"
        end
      end
    end

    before { visit("/") }

    it "has the expected text in the new window" do
      visit("/new_window")
      driver.within_window(driver.window_handles.last) do
        driver.find("//p").first.text.should == "finished"
      end
    end

    it "waits for the new window to load" do
      visit("/new_window?sleep=1")
      driver.within_window(driver.window_handles.last) do
        driver.find("//p").first.text.should == "finished"
      end
    end

    it "waits for the new window to load when the window location has changed" do
      visit("/new_window?sleep=2")
      driver.execute_script("setTimeout(function() { window.location = 'about:blank' }, 1000)")
      driver.within_window(driver.window_handles.last) do
        driver.find("//p").first.text.should == "finished"
      end
    end

    it "switches back to the original window" do
      visit("/new_window")
      driver.within_window(driver.window_handles.last) { }
      driver.find("//p").first.text.should == "bananas"
    end

    it "supports finding a window by name" do
      visit("/new_window")
      driver.within_window('myWindow') do
        driver.find("//p").first.text.should == "finished"
      end
    end

    it "supports finding a window by title" do
      visit("/new_window?sleep=5")
      driver.within_window('My New Window') do
        driver.find("//p").first.text.should == "finished"
      end
    end

    it "supports finding a window by url" do
      visit("/new_window?test")
      driver.within_window(driver_url(driver, "/?test")) do
        driver.find("//p").first.text.should == "finished"
      end
    end

    it "raises an error if the window is not found" do
      expect { driver.within_window('myWindowDoesNotExist') }.
        to raise_error(Capybara::Webkit::InvalidResponseError)
    end

    it "has a number of window handles equal to the number of open windows" do
      driver.window_handles.size.should == 1
      visit("/new_window")
      driver.window_handles.size.should == 2
    end

    it "closes new windows on reset" do
      visit("/new_window")
      last_handle = driver.window_handles.last
      driver.reset!
      driver.window_handles.should_not include(last_handle)
    end
  end

  it "preserves cookies across windows" do
    session_id = '12345'
    driver = driver_for_app do
      get '/new_window' do
        <<-HTML
<html>
<script type="text/javascript">
window.open('http://#{request.host_with_port}/set_cookie');
</script>
</html>
HTML
      end

      get '/set_cookie' do
        response.set_cookie 'session_id', session_id
      end
    end

    visit("/new_window", driver)
    driver.cookies['session_id'].should == session_id
  end

  context "timers app" do
    let(:driver) do
      driver_for_app do
        get "/success" do
          '<html><body></body></html>'
        end

        get "/not-found" do
          404
        end

        get "/outer" do
          <<-HTML
<html>
<head>
<script>
function emit_true_load_finished(){var divTag = document.createElement("div");divTag.innerHTML = "<iframe src='/success'></iframe>";document.body.appendChild(divTag);};
function emit_false_load_finished(){var divTag = document.createElement("div");divTag.innerHTML = "<iframe src='/not-found'></iframe>";document.body.appendChild(divTag);};
function emit_false_true_load_finished() { emit_false_load_finished(); setTimeout('emit_true_load_finished()',100); };
</script>
</head>
<body onload="setTimeout('emit_false_true_load_finished()',100)">
</body>
</html>
HTML
        end

        get '/' do
          "<html><body></body></html>"
        end
      end
    end

    before { visit("/") }

    it "raises error for any loadFinished failure" do
      expect do
        visit("/outer")
        sleep 1
        driver.find("//body")
      end.to raise_error(Capybara::Webkit::InvalidResponseError)
    end
  end

  describe "basic auth" do
    let(:driver) do
      driver_for_app do
        get "/" do
          if env["HTTP_AUTHORIZATION"] == "Basic #{Base64.encode64("user:password").strip}"
            env["HTTP_AUTHORIZATION"]
          else
            headers "WWW-Authenticate" => 'Basic realm="Secure Area"'
            status 401
            "401 Unauthorized."
          end
        end
      end
    end

    it "can authenticate a request" do
      driver.browser.authenticate('user', 'password')
      visit("/")
      driver.html.should include("Basic "+Base64.encode64("user:password").strip)
    end

    it "returns 401 for incorrectly authenticated request" do
      driver.browser.authenticate('user1', 'password1')
      driver.browser.timeout = 2
      lambda { visit("/") }.should_not raise_error(Timeout::Error)
      driver.status_code.should == 401
    end

    it "returns 401 for unauthenticated request" do
      driver.browser.timeout = 2
      lambda { visit("/") }.should_not raise_error(Timeout::Error)
      driver.status_code.should == 401
    end
  end

  describe "url blacklisting" do
    let(:driver) do
      driver_for_app do
        get "/" do
          <<-HTML
<html>
<body>
<script src="/script"></script>
<iframe src="http://example.com/path" id="frame1"></iframe>
<iframe src="http://example.org/path/to/file" id="frame2"></iframe>
<iframe src="/frame" id="frame3"></iframe>
</body>
</html>
HTML
        end

        get "/frame" do
          <<-HTML
<html>
<body>
<p>Inner</p>
</body>
</html>
HTML
        end

        get "/script" do
          <<-JS
document.write('<p>Script Run</p>')
JS
        end
      end
    end

    before do
      driver.browser.url_blacklist = ["http://example.org/path/to/file",
                                      "http://example.com",
                                      "#{AppRunner.app_host}/script"]
    end

    it "should not fetch urls blocked by host" do
      visit("/")
      driver.within_frame('frame1') do
        driver.find("//body").first.text.should be_empty
      end
    end

    it "should not fetch urls blocked by path" do
      visit('/')
      driver.within_frame('frame2') do
        driver.find("//body").first.text.should be_empty
      end
    end

    it "should not fetch blocked scripts" do
      visit("/")
      driver.html.should_not include("Script Run")
    end

    it "should fetch unblocked urls" do
      visit('/')
      driver.within_frame('frame3') do
        driver.find("//p").first.text.should == "Inner"
      end
    end

    it "returns a status code for blocked urls" do
      visit("/")
      driver.within_frame('frame1') do
        driver.status_code.should == 200
      end
    end
  end

  describe "timeout for long requests" do
    let(:driver) do
      driver_for_app do
        html = <<-HTML
<html>
<body>
<form action="/form" method="post">
<input type="submit" value="Submit"/>
</form>
</body>
</html>
HTML

        get "/" do
          sleep(2)
          html
        end

        post "/form" do
          sleep(4)
          html
        end
      end
    end

    it "should not raise a timeout error when zero" do
      driver.browser.timeout = 0
      lambda { visit("/") }.should_not raise_error(Timeout::Error)
    end

    it "should raise a timeout error" do
      driver.browser.timeout = 1
      lambda { visit("/") }.should raise_error(Timeout::Error, "Request timed out after 1 second")
    end

    it "should not raise an error when the timeout is high enough" do
      driver.browser.timeout = 10
      lambda { visit("/") }.should_not raise_error(Timeout::Error)
    end

    it "should set the timeout for each request" do
      driver.browser.timeout = 10
      lambda { visit("/") }.should_not raise_error(Timeout::Error)
      driver.browser.timeout = 1
      lambda { visit("/") }.should raise_error(Timeout::Error)
    end

    it "should set the timeout for each request" do
      driver.browser.timeout = 1
      lambda { visit("/") }.should raise_error(Timeout::Error)
      driver.reset!
      driver.browser.timeout = 10
      lambda { visit("/") }.should_not raise_error(Timeout::Error)
    end

    it "should raise a timeout on a slow form" do
      driver.browser.timeout = 3
      visit("/")
      driver.status_code.should == 200
      driver.browser.timeout = 1
      driver.find("//input").first.click
      lambda { driver.status_code }.should raise_error(Timeout::Error)
    end

    it "get timeout" do
      driver.browser.timeout = 10
      driver.browser.timeout.should == 10
      driver.browser.timeout = 3
      driver.browser.timeout.should == 3
    end
  end

  describe "logger app" do
    it "logs nothing before turning on the logger" do
      visit("/")
      log.should == ""
    end

    it "logs its commands after turning on the logger" do
      driver.enable_logging
      visit("/")
      log.should_not == ""
    end

    let(:driver) do
      connection = Capybara::Webkit::Connection.new(:stdout => output)
      browser = Capybara::Webkit::Browser.new(connection)
      Capybara::Webkit::Driver.new(AppRunner.app, :browser => browser)
    end

    let(:output) { StringIO.new }

    def log
      output.rewind
      output.read
    end
  end

  context "synchronous ajax app" do
    let(:driver) do
      driver_for_app do
        get '/' do
          <<-HTML
<html>
<body>
<form id="theForm">
<input type="submit" value="Submit" />
</form>
<script>
document.getElementById('theForm').onsubmit = function() {
xhr = new XMLHttpRequest();
xhr.open('POST', '/', false);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('hello');
console.log(xhr.response);
}
</script>
</body>
</html>
HTML
        end

        post '/' do
          request.body.read
        end
      end
    end

    it 'should not hang the server' do
      visit('/')
      driver.find('//input').first.click
      driver.console_messages.first[:message].should == "hello"
    end
  end

  def driver_url(driver, path)
    URI.parse(driver.current_url).merge(path).to_s
  end
end
Something went wrong with that request. Please try again.