環境
macOS: Big Sur Ver11.2.2
Rails: 6.0.0
Ruby: 2.6.5
エラーの内容
RSpecでモデルの単体テストを実行していたら以下のエラーが発生。
Failures:
1) OrderOrderDetail メニュー注文機能 メニュー注文ができるとき すべての情報が正しく入力されていれば注文できる
Failure/Error: @menu = FactoryBot.create(:menu)
ActiveRecord::LockWaitTimeout:
Mysql2::Error::TimeoutError: Lock wait timeout exceeded; try restarting transaction
# ./spec/models/order_order_detail_spec.rb:6:in `block (2 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# Mysql2::Error::TimeoutError:
# Lock wait timeout exceeded; try restarting transaction
# ./spec/models/order_order_detail_spec.rb:6:in `block (2 levels) in <top (required)>'
なぜこうなった?
記憶にないが、たぶんテスト実行をbinding.pryでストップさせながらやっているときにCtr+cとかを押してしまったからかと思っている。
解決策
①以下のコマンドでMySQLにログイン
mysql -u root
②以下を実行
SHOW ENGINE INNODB STATUS;
そして以下の部分に注目。
------------
TRANSACTIONS
------------
Trx id counter 79683
Purge done for trx's n:o < 79680 undo n:o < 0 state: running but idle
History list length 858
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0, not started
MySQL thread id 656, OS thread handle 0x70000b8e1000, query id 47472 localhost root init
SHOW ENGINE INNODB STATUS
---TRANSACTION 79619, not started
MySQL thread id 650, OS thread handle 0x70000b89d000, query id 46995 localhost root
---TRANSACTION 78207, not started
MySQL thread id 1, OS thread handle 0x70000b815000, query id 47466 localhost root
---TRANSACTION 0, not started
MySQL thread id 2, OS thread handle 0x70000b859000, query id 47467 localhost root
---TRANSACTION 79650, ACTIVE 520 sec
2 lock struct(s), heap size 360, 1 row lock(s)
MySQL thread id 651, OS thread handle 0x70000b925000, query id 47378 localhost root
一番下の2行を見ると、
2 lock struct(s), heap size 360, 1 row lock(s)
MySQL thread id 651, OS thread handle 0x70000b925000, query id 47378 localhost root
ここが怪しい。スレッドid651が犯人らしい。こいつをkillします。
③killコマンド実行
mysql> kill 651;
Query OK, 0 rows affected (0.00 sec)
以上!無事にテストが動くようになりました!