为什么我会收到以下错误? “Mysql2 ::错误:关闭MySQL连接:SHOW TABLES”

时间:2011-12-15 20:14:50

标签: mysql ruby-on-rails-3 rspec2 capybara factory-bot

使用Spork,Rails3,RSpec2,Capybara和FactoryGirl。

在尝试执行Capybara测试时,我收到以下错误:

 Failure/Error: model = FactoryGirl.create(:model)
    ActiveRecord::StatementInvalid:
      Mysql2::Error: closed MySQL connection: SHOW TABLES

database.yml正在使用的MySQL数据库已启动并正在运行。我可以使用database.yml中的相同设置从命令行连接到它。

测试工作正常,我试图找出测试失败的原因然后开始发出错误。

我试过关闭并重新启动数据库无济于事。

来自database.yml

test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: mysql_app_test
  pool: 5
  username: root
  password:
  host: localhost

来自我的规范

require 'spec_helper'

describe "Model", :js => true do

  before(:each) do
    model = FactoryGirl.create(:model)
    visit model_path(model)
  end

  it "should show the button" do
    # Start the lesson
    find("#startButton")
  end
end

更新:

同样重要的是,我一直在使用solution 3与非Rack :: Test驱动程序相关联的Capybara Transactional Fixtures Issue

我已将解决方案放在 spec_helper.rb 文件中,如下所示:

Spork.prefork do
  ...
  class ActiveRecord::Base
    mattr_accessor :shared_connection
    @@shared_connection = nil

    def self.connection
      @@shared_connection || retrieve_connection
    end
  end

  ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
  ...
end

我听说issues when using solution 3 with spork的评论中有类似的solution 2。我不确定这些是评论者提到的问题。

1 个答案:

答案 0 :(得分:3)

我想我已经弄明白了。我无法在网上找到解决方案,因此我将在此处记录,以防其他人正在搜索该错误消息。

我认为问题在于Spork正在缓存/保持一个封闭的MySQL连接。

这是因为上面解决方案3 的实施位于 Spork.prefork 定义中。所以它只会在Spork发布时运行一次。杀死和重启Spork会暂时解决问题。但是,如果在新的Spork进程中关闭另一个MySQL连接,问题就会回来。

永久修复是将spec_helper.rb文件中的解决方案3 移动到同一文件中的 Spork.each_run 定义中。所以你的spec_helper.rb文件应如下所示:

Spork.prefork do
  ...
  ...
end

Spork.each_run do
  ...
  class ActiveRecord::Base
    mattr_accessor :shared_connection
    @@shared_connection = nil

    def self.connection
      @@shared_connection || retrieve_connection
    end
  end

  ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
  ...
end

这似乎对我有用。 干杯!