assert_selectメソッドは、コントローラのアクション実行後のレスポンスHTML内の特定の要素を検証するためのアサーションメソッドです。
以下はその中でも、HTML内のボタンを押した時に、指定したURLページに飛ぶかを試すコードである。
require "test_helper"
class SiteLayoutTest < ActionDispatch::IntegrationTest
test "layout links" do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path, count: 2
assert_select "a[href=?]", help_path
assert_select "a[href=?]", about_path
assert_select "a[href=?]", contact_path
end
end
以下は、対応するHTMLを探すメソッド。
assert_select "div" <div>foobar</div>
assert_select "div", "foobar" <div>foobar</div>
assert_select "div.nav" <div class="nav">foobar</div>
assert_select "div#profile" <div id="profile">foobar</div>
assert_select "div[name=yo]" <div name="yo">hey</div>
assert_select "a[href=?]", '/', <a href="/">foo</a>
左のコードを書くことで、右のHTMLコードが存在するかを探すことができる。
assert_select "a[href=?]", root_path, count: 2
上記のコードは「?」にroot_pathが入ることで、
<a href="/"> </a>
が存在するかどうかを確かめてくれる。
ちなみに、「count: 2」というのは、「そのコードが2回存在することをテストする」コードである。