Skip to content

Instantly share code, notes, and snippets.

@midu
Forked from jnicklas/template.rb
Created September 4, 2013 20:17
Show Gist options
  • Save midu/6442311 to your computer and use it in GitHub Desktop.
Save midu/6442311 to your computer and use it in GitHub Desktop.
require "minitest/autorun"
require "capybara"
class TestNthChild < Minitest::Unit::TestCase
def setup_with_html(html)
app = proc { |env| [200, { "Content-Type" => "text/html" }, [html] ] }
session = Capybara::Session.new(:rack_test, app)
session.visit("/")
return session
end
def test_works_when_direct_children
html = <<-EOHTML
<!doctype html>
<html>
<body>
<ul id="a-list">
<li class="an-item">a</li>
<li class="an-item">b</li>
<li class="an-item">c</li>
</ul>
</body>
</html>
EOHTML
session = setup_with_html(html)
session.within ".an-item:nth-of-type(1)" do assert_equal(session.text, 'a'); end
session.within ".an-item:nth-of-type(2)" do assert_equal(session.text, 'b'); end
session.within ".an-item:nth-of-type(3)" do assert_equal(session.text, 'c'); end
end
# Fails
def test_works_when_direct_children_with_tag_name_in_selector
html = <<-EOHTML
<!doctype html>
<html>
<body>
<ul id="a-list">
<li class="an-item">a</li>
<li class="an-item">b</li>
<li class="an-item">c</li>
</ul>
</body>
</html>
EOHTML
session = setup_with_html(html)
session.within "li.an-item:nth-of-type(1)" do assert_equal(session.text, 'a'); end
session.within "li.an-item:nth-of-type(2)" do assert_equal(session.text, 'b'); end
session.within "li.an-item:nth-of-type(3)" do assert_equal(session.text, 'c'); end
end
def test_works_when_separated_by_an_element
html = <<-EOHTML
<!doctype html>
<html>
<body>
<div id="a-list">
<h1>title</h1>
<p class="an-item">a</p>
<p class="an-item">b</p>
<p class="an-item">c</p>
</ul>
</body>
</html>
EOHTML
session = setup_with_html(html)
session.within ".an-item:nth-of-type(1)" do assert_equal(session.text, 'a'); end
session.within ".an-item:nth-of-type(2)" do assert_equal(session.text, 'b'); end
session.within ".an-item:nth-of-type(3)" do assert_equal(session.text, 'c'); end
end
def test_works_when_separated_by_an_element_with_tag_name_in_selector
html = <<-EOHTML
<!doctype html>
<html>
<body>
<div id="a-list">
<h1>title</h1>
<p class="an-item">a</p>
<p class="an-item">b</p>
<p class="an-item">c</p>
</ul>
</body>
</html>
EOHTML
session = setup_with_html(html)
session.within "p.an-item:nth-of-type(1)" do assert_equal(session.text, 'a'); end
session.within "p.an-item:nth-of-type(2)" do assert_equal(session.text, 'b'); end
session.within "p.an-item:nth-of-type(3)" do assert_equal(session.text, 'c'); end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment