我们正在尝试一种新的机制来在测试运行之间清除我们的数据库,因为我们在使用shared connection策略的Capybara测试中度过了一段时间。
我们使用Postgresql的基本想法是在db:test:prepare
之后立即创建数据库的快照。然后,在功能规范之间断开数据库,删除数据库,从快照重新创建数据库并重新连接。
它似乎工作大多数,但有一些测试运行以某种方式维持连接。我们的设置大致如下:
# spec/spec_helper.rb
RSpec.configure do |config|
config.before(:each, type: :feature) do
DatabaseCleaner.strategy = nil
end
config.after(:each, type: :feature) do
ActiveRecord::Base.clear_all_connections!
`dropdb -Uroot our_apps_test_db`
`createdb -Uroot -T test_template our_apps_test_db`
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
end
end
我们在某些运行中发现的是,rspec进程仍然保持连接。如果我们在ActiveRecord::Base.clear_all_connections!
之后偷看postgres连接,那么:
puts `psql -c "select datname, application_name from pg_stat_activity;"`
有时(只有少数几个)我们会看到以下内容:
datname | application_name
----------------------------+-----------------------------------------------------------------
our_apps_test_db | /Users/dev/.rvm/gems/ruby-2.0.0-p353@influitive/bin/rspec
我想知道是否有任何人对ActiveRecord
及其连接处理的了解比我们更多。我们对此很难过。