LoginSignup
0
0

More than 1 year has passed since last update.

【テストコード】「Mysql is not connected」というエラー

Last updated at Posted at 2021-08-10

今回の概要

①テストコードを行う
②「MySQL client is not connected」のエラーが発生
③「sleep」を記述して解決

①テストコードを行う

◇下記のテストコードを行うときにエラーが発生

purchase_shipping_spec
require 'rails_helper'

RSpec.describe PurchaseShipping, type: :model do
  before do
    @user = FactoryBot.create(:user)
    @item = FactoryBot.create(:item)
    @p_s = FactoryBot.build(:purchase_shipping, user_id: @user.id, item_id: @item.id)
  end
  describe '商品購入機能' do

〜テストコードは省略〜
  end
end

②「MySQL client is not connected」のエラーが発生

◇エラー内容

ActiveRecord::StatementInvalid:
Mysql2::Error: MySQL client is not connected

◇エラー原因
処理速度の速いPCやmacbook Proなどを使用されている場合に発生することが多いみたいですが、、、
PCの処理速度の関係でbeforeに記載されているコードが読み込まれる前に、次の処理に移っていることが原因の可能性が高いみたいです

③「sleep」を記述して解決

◇解決方法
purchase_shipping_spec.rbの下に「sleep(3)」と記述
※sleepとは、次の処理実行まで処理を遅延させるメソッド

purchase_shipping_spec
require 'rails_helper'

RSpec.describe PurchaseShipping, type: :model do
  before do
    @user = FactoryBot.create(:user)
    @item = FactoryBot.create(:item)
    @p_s = FactoryBot.build(:purchase_shipping, user_id: @user.id, item_id: @item.id)
    sleep(3)
  end

◇記述の挙動
処理が少し遅くなったが、解決!

テストコード結果
PurchaseShipping
  商品購入機能
    購入できるとき
      全ての項目が入力されていれば保存ができること
      建物名がなくても保存ができる
      購入できないとき
      tokenが空では登録できない
      郵便番号が空では登録できない
      郵便番号「3桁ハイフン4桁」ではないと登録できない
      郵便番号はハイフンがないと登録できない
      都道府県を選択しないと登録できない
      市区町村が空では登録できない
      番地が空では登録できない
      電話番号が空では登録できない
      電話番号が10桁以下では登録できない
      電話番号が11桁以上では登録できない
      電話番号が半角文字混合だと登録できない
      電話番号に-があると登録できない

Finished in 42.56 seconds (files took 1.74 seconds to load)
14 examples, 0 failures

以上。

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