0
0

More than 1 year has passed since last update.

Rails リンクが正しく動作しているかテストする方法

Posted at

Railsではリンクが正しく動作しているかどうかをテストする際に統合テストを用います。

まずはテストファイルを作成します。

rails generate integration_test site_layout

作成されたファイルを開きます。

sample_app/test/integration/site_layout_test.rb
require 'test_helper'

class SiteLayoutTest < ActionDispatch::IntegrationTest
 
end

このファイルにテストコードを書いていきます。

今回は以下の点についてのテストを行います。

  1. テンプレートが正しく表示されているかどうか。
  2. リンクが正しく動作しているかどうか。
sample_app/test/integration/site_layout_test.rb
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

まず、以下のコードでルートURLにgetリクエストを送ります。

get root_path

次に、テンプレートが描画されているかを以下のコードで確認します。

 assert_template "static_pages/home"

そして、以下のコードでリンクが正しく動作しているのかを確認します。

assert_select "a[href=?]", root_path, count:2

a[href=?]の?をrailsではroot_pathに置き換えています。
つまりこのテストコードがテストしているのは以下のコードになります。

<a href="/">,,,</a>

また、テストするページの中にリンクが複数ある場合、その数もcount: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