Rspec Capybara Failure/Error: DatabaseCleaner.clean

Rspec Capybara Failure/Error: DatabaseCleaner.clean

我正在使用 rails 6.1.4 (Ubuntu 20.04) 并且正在使用 rspec、factorybot 和水豚进行 运行ning 测试。我还得到了 database_cleaner ,其中我使用 :t运行cation 以全新的方式开始每个测试块(是的,不是最快的方法,而是最严格的方法)。当我 运行 rspec spec (也适用于个别模型)时,我得到了一个 table 随机得到一堆失败的测试说

Failure/Error: DatabaseCleaner.clean
     
     ActiveRecord::Deadlocked:
       PG::TRDeadlockDetected: ERROR:  deadlock detected
       DETAIL:  Process 105987 waits for AccessExclusiveLock on relation 1876018 of database 1876015; blocked by process 105996.
       Process 105996 waits for AccessShareLock on relation 1876043 of database 1876015; blocked by process 105987.
       HINT:  See server log for query details.
     # ./spec/support/database_cleaner.rb:32:in `block (2 levels) in <top (required)>'
     # ------------------
     # --- Caused by: ---
     # PG::TRDeadlockDetected:
     #   ERROR:  deadlock detected
     #   DETAIL:  Process 105987 waits for AccessExclusiveLock on relation 1876018 of database 1876015; blocked by process 105996.
     #   Process 105996 waits for AccessShareLock on relation 1876043 of database 1876015; blocked by process 105987.
     #   HINT:  See server log for query details.
     #   ./spec/support/database_cleaner.rb:32:in `block (2 levels) in <top (required)>'

测试开始失败的地方确实是随机的,即我可以 运行 连续执行相同的测试命令,不同的测试将通过/失败。

in ./spec/support/database_cleaner.rb [评论我删了]

    RSpec.configure do |config|
      config.before(:suite) { DatabaseCleaner.clean_with(:truncation) }
    
      config.before(:each) { DatabaseCleaner.strategy = :truncation }
    
      config.before(:each, js: true) { DatabaseCleaner.strategy = :truncation }
    
      config.before(:each) { DatabaseCleaner.start }
      config.after(:each) do
[this is row 32:]        DatabaseCleaner.clean
        rescue NoMethodError => e # See: https://github.com/DatabaseCleaner/database_cleaner-sequel/issues/4
        next puts("Warning: catch #{e.message}") if e.message == %(undefined method `rollback' for nil:NilClass (DB Cleaner gem))
          raise e
      end
    end

有时,一段时间后,所有测试也可能会起作用。有谁知道是什么导致了这个问题?谢谢!

给数据库清理器一些时间来完成它的工作! 解决问题的一种虚拟方法是使用 sleep 方法,如下所示: sleep(1),在每个 "it" 块的开头。这应该可以完成工作 ✅

发生了什么事,数据库清理器没有时间清理您已经在尝试重新创建您在之前测试中使用的相同实例的 PSQL 数据库。