LoginSignup
1
1

More than 1 year has passed since last update.

RSpecで表示順をテストする(SystemSpec)

Last updated at Posted at 2022-01-03

アプリ内のユーザーの表示順を任意に変更する機能のテストを書く上で、正規表現も含めて勉強になったのでメモを残します。

2人のuserの表示順が正しく変更されているかをテストします。

テスト

spec/system
RSpec.describe '表示順変更テスト', type: :system do
  let!(:user) { FactoryBot.create(:user) }
  let!(:other_user) { FactoryBot.create(:other_user) }

  describe '表示順を変更する' do
    it 'ユーザー表示順を変更できる' do
      #user→other_userの順番で表示されていることをテスト
      expect(page.text).to match %r{#{user.name}.*#{other_user.name}}
      #other_user→userの順番で表示されていないことをテスト
      expect(page.text).not_to match %r{#{other_user.name}.*#{user.name}}

      #表示順を変更する処理を記述

      #変更に成功し、user→other_userの順番で表示されていないことをテスト
      expect(page.text).not_to match %r{#{user.name}.*#{other_user.name}}
      #変更に成功し、other_user→userの順番で表示されていることをテスト
      expect(page.text).to match %r{#{other_user.name}.*#{user.name}}
    end
  end
end

%r{}で正規表現を生成

正規表現について

%r{#{user.name}.*#{other_user.name}}
#*user.nameはイチロー、other_user.nameはジロー

上記の箇所では正規表現の/イチロー.*ジロー/が生成されています。
正規表現において.*は「任意の文字列に一致」という意味です。
つまり、page.textの中に、イチロー(任意の文字列)ジローが含まれているかどうかをテストしており、ジロー(任意の文字列)イチローの場合は不一致となるため、表示順をテストすることができます。

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