0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

assert_selectメソッド

Posted at

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回存在することをテストする」コードである。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?