[RUBY] MySQL client is not connected while testing RSpec

Development environment

macOS Catalina 10.15.7 Ruby on Rails 6.0.0 RSpec 4.0.1 pry rails 0.3.9 FactoryBot 6.1.0

error contents

console


Failure/Error: _query(sql, @query_options.merge(options))
      
ActiveRecord::StatementInvalid:
  Mysql2::Error: MySQL client is not connected

Apparently the connection with the MySQL client has not been established.

As far as the definition is concerned, it seems that this error occurs when the network socket (file descriptor) is disabled even though the client is initialized. About "MySQL client is not connected" in Mysql2

Verification

テスト結果 Looking at the test execution results, the test was successful halfway, so I checked the test contents while stopping the process with binding.pry for the time being, and for some reason all the tests were successful.

console


Finished in 16.16 seconds (files took 2.21 seconds to load)
15 examples, 0 failures

hypothesis

Since the error started to occur at the timing when the description of FactoryBot instance generation was increased, I thought that there was a possibility that the processing was stopped due to the load applied here.

Remedy 1

I decided to make the process wait with sleep at the timing of creating an instance.

RSpec.describe OrderItem, type: :model do
  describe 'Save purchase information' do
    before do
      @user = FactoryBot.create(:user)
      @item = FactoryBot.create(:item)
      @order_item = FactoryBot.build(:order_item)
      sleep 0.1 # 0.Wait 1 second
    end
#abridgement

result

The test is now stable and successful without any errors.

Remedy 2

It was also possible to deal with it by writing the following in config/environments/test.rb.

config/environments/test.rb


Rails.application.configure do
  config.active_job.queue_adapter = :inline
#abridgement
end

Reference link

-About "MySQL client is not connected" in Mysql2 -How to use sleep in Ruby [For beginners]

Recommended Posts

MySQL client is not connected while testing RSpec
[Ruby On Rails] Error in test using RSpec MySQL client is not connected