対象者
RSpec初心者.
Capybara::ElementNotFound: Unable to find linkとうエラーが出力された方
目次
- linkのテスト.
linkのテスト.
↓猫を探すとクリックすると検索条件とはというページに画面が先しているかをテストしたいです。
↓RSpecのコード
require 'rails_helper' RSpec.describe CatsController, type: :controller do describe "#search" do it "responds to search" do get :home click_link '猫を探す' expect(page).to have_content '検索条件' end end end
意味はurlの語尾に/homeとするとhome.html.erbのファイルに外面遷移し、そのhtmlファイルに猫を探すというリンクがありクリックすると、クリックした先のページに検索条件という文字列があることをテストしています。
テストを走らせると
Failure/Error: click_link '猫を探す' Capybara::ElementNotFound: Unable to find link "猫を探す"
とlink "猫を探す"が見つからないよと言われました。 home.html.erb↓
<%= link_to "猫を探す", controller: "cats", action: "search" =%>
リンクがあるのに‥なぜ見つからない?.
⇨結論get :homeという書き方が間違っており、なのでhomeアクションが反応せずhome.html.erbが表示されないので今回のエラー「リンク見つからないよ」とエラーが出力されました。
↓RSpecのコード
require 'rails_helper' RSpec.describe CatsController, type: :controller do describe "#search" do it "responds to search" do visit home_url click_link '猫を探す' expect(page).to have_content '検索条件' end end end
visit home_urlや visit home_pathのように書き換えるとテストが通りました.
指定のurlに飛びたい場合.
システムスペック内⇨visit home_urlや visit home_path コントローラースペック内⇨get :home
テストする場所によって書き方に違いがあるようです。