LoginSignup
1
0

More than 1 year has passed since last update.

【Rails】結合テストでボタンをクリックしてくれない

Posted at

はじめに

結合テストの際にクリックの動作がうまくいかずにエラーが出てしまった時に行った対処法を紹介したいと思います。

テストの実行

spec/system/users_spec.rb
require 'rails_helper'

RSpec.describe 'ユーザー新規登録', type: :system do
  before do
    @user = FactoryBot.build(:user)
  end

  context 'ユーザー登録ができるとき' do
    it '正しい情報を入力すればユーザー新規登録ができてトップページに移動する' do
      # トップページに移動する
      visit root_path
      # トップページにサインアップページへ遷移するボタンがあることを確認する
      expect(page).to have_content('新規登録')
      # 新規登録ページへ移動する
      visit new_user_registration_path
      # ユーザー情報を入力する
      fill_in 'ニックネーム', with: @user.nickname
      fill_in 'メールアドレス', with: @user.email
      fill_in 'パスワード', with: @user.password
      fill_in 'パスワード(確認)', with: @user.password_confirmation
      # 添付する画像を定義する
      image_path = Rails.root.join('public/images/test_image.png')
      # 画像選択フォームに画像を添付する
      attach_file('user[image]', image_path, make_visible: true)
      # サインアップボタンを押すとユーザーモデルのカウントが1上がることを確認する
      expect{
        find('input[name="commit"]').click
      }.to change { User.count }.by(1)
      # トップページへ遷移したことを確認する
      expect(current_path).to eq(root_path)
      # サインアップページへ遷移するボタンやログインページへ遷移するボタンが表示されていないことを確認する
      expect(page).to have_no_content('新規登録')
      expect(page).to have_no_content('ログイン')
    end
  end
end

これでテストを実行してみます。

ターミナル
% bundle exec rspec spec/system/users_spec.rb

エラーの発生

テストを実行したところ、以下のようなエラーメッセージがでてしまいました。

ターミナル
     Failure/Error: find('input[name="commit"]').click

     Capybara::Ambiguous:
       Ambiguous match, found 2 elements matching visible css "input[name=\"commit\"]"

input[name="commit"]という名前がついたボタンが2つあるためにエラーが起きてしまったようです。
この部分が怪しそうです。

spec/system/users_spec.rb
      # サインアップボタンを押すとユーザーモデルのカウントが1上がることを確認する
      expect{
        find('input[name="commit"]').click
      }.to change { User.count }.by(1)

対処法

記述を以下のように変更したところテストが通りました。

spec/system/users_spec.rb
      # サインアップボタンを押すとユーザーモデルのカウントが1上がることを確認する
      expect do
        click_button "登録する"
      end.to change(User, :count).by(1)

"登録する"はこちらから取ってます。

app/views/devise/registrations/new.html.erb
  <%= f.submit "登録する" %>

参考文献

今回のエラーの解決にあたり、こちらの記事を参考にさせていただきました。
https://samoant.com/rspec4/

1
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
1
0