LoginSignup
0
0

More than 3 years have passed since last update.

Capybara::Ambiguous: Ambiguous match, found huga elements 〜  対処法

Posted at

□解決したいこと

systemspecテストコードでformで画像を選択するため、

attach_file( 'tip_image',image_path, make_visible: true )

を実行したら

Capybara::Ambiguous: Ambiguous match, found 4 elements matching file field "tip_image" that is not disabled

というエラーが発生しました。こちらの解決方法をアップしたいと思います。

□原因

"tip_image"に該当するエレメントが4つ存在しますという意味のエラー内容です。
画像の選択に限らず、capybaraで選択したname属性が複数ある場合に「どのエレメントを選択しているのでしょうか」ということを聞かれています。

new.html.erbを見てみると

new.html.erb
<div class="tip-images">
        <div class="tip-image-main">
          <p class="tip-image-main-text">画像(メイン)</p>
          <div id="image-list">
            <%= form.file_field :image, class: 'tip-image-main-img' %>
          </div>
        </div>
        <div class="tip-image-sub">
          <p class="tip-image-sub-text">画像(サブ)</p>
          <div class="tip-image-sub-images">
            <%= form.file_field :image, class: 'tip-image-sub-img' %>
            <%= form.file_field :image, class: 'tip-image-sub-img' %>
            <%= form.file_field :image, class: 'tip-image-sub-img' %>
          </div>
        </div>
      </div>

となっており、

こちらに"tip_image"に該当するエレメントはありません。

検証ツールで調べてみると、

スクリーンショット 2021-04-08 8.00.48.png

ありました。

name属性が tip[image]となっている要素が4つ存在します。

これが原因です。

□実行したこと

name属性が複数あることが原因ですので、画像投稿のフォームそれぞれに別々のname属性を付与してみます。
その上で、attachfileで当該name属性を指定することで、解決していこうと思います。

            <%= form.file_field :image, class: 'tip-image-main-img', name: 'tip-image-main-img' %>
            <%= form.file_field :image, class: 'tip-image-sub-img', name: 'tip-image-sub-img1' %>
            <%= form.file_field :image, class: 'tip-image-sub-img', name: 'tip-image-sub-img2' %>
            <%= form.file_field :image, class: 'tip-image-sub-img', name: 'tip-image-sub-img3' %>

としました。
次に、systemspecのテストコードのnameも変更します。

attach_file( 'tip-image-main-img',image_path, make_visible: true )

□結果

これでうまくいきました。

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