前提・実現したいこと
RSpecのsystem specで、特定の要素にjQueryで新たにクラス名が付与されることをテストしたいのですがうまくできません。アドバイスいただけないでしょうか。
Railsでformを作成し、そのバリデーションエラーをjQueryで表示できるようにしました。
Haml
1= form_with model: @user do |f| 2 .last-name 3 = f.label :last_name, '名字', id: 'last_name-label' 4 = f.text_field :last_name, id: 'user-last_name' 5 6 = f.label :first_name, '名前', id: 'first_name-label' 7 = f.text_field :first_name, id: 'user-first_name'
jQuery
1$('#user-last_name').blur(function(){ 2 if($(this).val() == '') { 3 $(this).prev('label').addClass('error-label'); 4 $(this).addClass('error-frame'); 5 $(this).after(`<div id="name-blank-error" class="error-message">入力してください</div>`); 6 7 } else { 8 $(this).prev('label').removeClass('error-label'); 9 $(this).removeClass('error-frame'); 10 $(this).next().remove('.error-message'); 11 }; 12});
scss
1.error-label { 2 color: red; 3} 4 5.error-frame { 6 border: solid 3px red; 7}
そして、system specでaddClass
されていることをテストしようとしたのですが、通りませんでした。
Rspec
1describe 'name' do 2 context '空の場合' do 3 context 'フォーカスが外れた時' do 4 before do 5 fill_in 'user[last_name]', with: '' 6 find('#user-first_name).click 7 end 8 9 it { expect(find('#last_name-label')).to have_css '.error-label' } 10 11 it {expect(find('#user-last_name')).to have_css '.error-frame' } 12 end 13 end 14end
テスト結果
Failure/Error: it { expect(find('#last_name-label')).to have_css '.error-label' } expected to find css ".error-label" within #<Capybara::Node::Element tag="label" path="/HTML/BODY[1]/DIV[1]/DIV[2]/DIV[2]/FORM[1]/DIV[1]/LABEL[1]"> but there were no matches Failure/Error: it { expect(find('#user-last_name')).to have_css '.error-frame' } expected to find css ".error-frame" within #<Capybara::Node::Element tag="input" path="/HTML/BODY[1]/DIV[1]/DIV[2]/DIV[2]/FORM[1]/DIV[1]/INPUT[1]"> but there were no matches
試したこと
expect(find('#last_name-label')).to
の( )内をpage
にしてみるとテストは通りました。
it { expect(page)).to have_css '.error-label' }
- テスト失敗時のスクリーンショットを確認すると、クラス名は付与され、ラベルやフォームの枠はしっかり赤くなっていました。
have_css
をhave_selector
にしてみましたが、結果は同じで通りませんでした。
it { expect(find('#last_name-label')).to have_selector '.error-label' }
expect(find('#last_name-label')).to
の()内のfind
をall
に変更してみましたが、こちらもテストは通りませんでした。
it { expect(all('#last_name-label')).to have_selector '.error-label' } it { expect(all(:css, '#last_name-label')).to have_selector '.error-label' }
Failure/Error: it { expect(all(:css, '#last_name-label')).to have_selector '.error-label' } expected to find css ".error-label" but there were no matches Failure/Error: it { expect(all('#last_name-label')).to have_selector '.error-label' } expected to find css ".error-label" but there were no matches
find
やall
は( )内の要素を探してくれると思っていたのですが、使い方や考え方が間違っているのでしょうか?
補足情報(FW/ツールのバージョンなど)
rails (6.0.3.2)
ruby (2.7.1)
rspec-rails (4.0.1)
capybara (3.33.0)
selenium-webdriver (3.142.7)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。