使用 Postgres 数据库测试 Rails 突然失败

Testing Rails with Postgres database suddenly fails

在使用 Postgres 数据库的 Rails 项目中,我使用 rspec 进行测试。在我添加另一个迁移之前,这工作得很好。现在 rspec 失败了:

Failure/Error: ActiveRecord::Migration.maintain_test_schema!

PG::ConnectionBad:
connection is closed

我试过用各种方法准备测试数据库:

rails db:reset RAILS_ENV=test
rails db:prepare RAILS_ENV=test
rails db:migrate RAILS_ENV=test

还有

rails db:test:prepare

在我添加迁移之前,我的测试一直有效,很明显有些地方出错了,但是什么?


编辑以添加更多详细信息:

虽然 Postgres 日志根本没有透露,但我确实发现了以下内容:

错误发生在rails_helper.rb的这一行:

ActiveRecord::Migration.maintain_test_schema!

test 环境中的 Rails 控制台,我可以毫无问题地调用 maintain_test_schema! 方法:

root@0bf32217fb90:/home/dora/rails# bin/rails c -e test
Loading test environment (Rails 6.0.3.4)
[1] pry(main)> ActiveRecord::Migration.maintain_test_schema!
(1.2ms)  SELECT "ar_internal_metadata"."value" FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" =   [["key", "schema_sha1"]]
(1.8ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
=> nil
[2] pry(main)>

很明显,从 rspec 调用方法和从控制台调用方法是有区别的。

我会保持更新以供其他人使用,如果有人偶然发现并知道解决方案,我将不胜感激。

我遇到了同样的问题,经过几个小时的努力,我发现我们需要将每个规范顶部的所有 require 'rails_helper 替换为 require 'spec_helper'

将我的 rails 应用程序从 5.2 升级到 6.0 后,我遇到了同样的问题。最后我修复了它,详情在 PG::ConnectionBad(connection is closed) when running rspec after upgrading application from Rails 5.2 to 6.0 。您应该检查是否有任何 rspec 支持者覆盖 dB 连接的创建