LoginSignup
10
9

More than 3 years have passed since last update.

Railsでいいね機能(ajax処理)のRSpecの書き方

Last updated at Posted at 2019-11-10

概要

ローカルで成功していたいいね機能(ajax)のRSpecテストがDockerで環境作成してテストを行ったら、失敗し解決したので書き残しておきます。

作ったいいねボタン

いいねボタンは、アイコンをクリックすると色が変わリ、いいね押したユーザ数がわかるように実装しました。

スクリーンショット 2019-11-10 16.33.07.png
スクリーンショット 2019-11-10 16.30.38.png

<div id="like-post-1">
    <a class="post_unlike" data-remote="true" rel="nofollow" 
       data-method="delete" href="/posts/1/like">
        <i class="fas fa-heart"></i>
    </a>1
</div>

RSpec

テストは、css要素をもとに2つ実装しました。

context 'いいねをクリックした場合' do
  it 'いいねできる' do
    find('.far').click
    expect(page).to have_css '.fas'
    expect(page).to have_css "div#like-post-#{post.id}", text: '1'
  end
end
context 'いいねを削除した場合' do
  it 'いいねを取り消せる' do
    find('.far').click
    find('.fas').click
    expect(page).to have_css '.far'
    expect(page).to have_css "div#like-post-#{post.id}", text: '0'
  end
end

発生したエラー

Failure/Error: expect(page).to have_css '.fas'
    expected to find css ".fas" but there were no matches

解決方法

作成したテストに、js: trueを追記するだけで解決しました。

context 'いいねをクリックした場合', js: true do
  it 'いいねできる' do
    find('.far').click
    expect(page).to have_css '.fas'
    expect(page).to have_css "div#like-post-#{post.id}", text: '1'
  end
end
context 'いいねを削除した場合', js: true do
  it 'いいねを取り消せる' do
    find('.far').click
    find('.fas').click
    expect(page).to have_css '.far'
    expect(page).to have_css "div#like-post-#{post.id}", text: '0'
  end
end

試したこと

エラー原因が、ajax処理が終わる前にテストが実行されているのかと思いajax処理が完了を待つような処理を記述しようとしました。

・下記の記事を参考し、実行してみたのですが自分の環境ではうまくいかず

evaluate_scriptをcapybaraはサポートしていないとエラーが出てしまいました。

https://thoughtbot.com/blog/automatically-wait-for-ajax-with-capybara

・Driverをcapybara-webkitに変更してみたり、色々試してみたのですがなかなかうまくいかなかったです。

最後に

ここまで読んでくださりありがとうございます。

Ruby on Railsのポートフォオを作成をしていく中で、様々な記事に助けられることが多いです。自分も誰かの助けになればと思い些細なエラーですが記事を書いてみました。

10
9
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
10
9