Techioz Blog

ビューコンポーネントのルートをテストする方法

概要

クリックするとアプリケーション内の別のルートに移動するカード コンポーネントがあります。コンポーネントは Rails ViewComponents を使用して構築されます。ユーザーがコンポーネントをクリックしたときに正しいルートに誘導されることを確認するテストを作成する最良の方法は何ですか?

View コンポーネントの .rb ファイルは次のとおりです。

class LandingCardComponent < ViewComponent::Base

  def initialize(title: "", description: "", label: "", path: "")
    @title = title
    @description = description
    @label = label
    @path = path
  end
end

解決策

レンダリングされたビューに期待どおりのリンクがあるかどうかをテストすることをお勧めします。

require "test_helper"

class LandingCardComponentTest < ViewComponent::TestCase
  def test_render_component
    render_inline(LandingCardComponent.new(title:       "Title", 
                                           description: "Description", 
                                           label:       "Label", 
                                           path:        "/foo/bar"))

    assert_select("a[href=?]", "/foo/bar", text: "Label")
  end
end