为什么我的 Rails 测试看不到内存 SQLite3 数据库的内容?

Raf*_*afe 5 sqlite testing ruby-on-rails

我试图通过使用 SQLite3 内存数据库作为应用程序的测试数据库来加快 Rails 应用程序的测试速度。我已按照这篇博文中的说明进行操作。

我的数据库配置database.yml如下所示:

test:
  adapter: sqlite3
  database: ":memory:"
  encoding: utf8
  verbosity: quiet
Run Code Online (Sandbox Code Playgroud)

我还按照建议创建了初始化程序:

def in_memory_database?
  Rails.env == "test" and
    ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLiteAdapter ||
      ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLite3Adapter and
    Rails.configuration.database_configuration['test']['database'] == ':memory:'
end

if in_memory_database?
  ActiveRecord::Schema.verbose = false
  puts "creating sqlite in memory database"
  load "#{Rails.root}/db/schema.rb"
end
Run Code Online (Sandbox Code Playgroud)

我的所有测试都失败了,因为无法加载装置,如您所见:

creating sqlite in memory database
Loaded suite test/unit/vendor_appliance_test
Started
E
Finished in 0.070079 seconds.

  1) Error:
test_the_truth(VendorApplianceTest):
ActiveRecord::StatementInvalid: Could not find table 'advertisers'


1 tests, 0 assertions, 0 failures, 1 errors
Run Code Online (Sandbox Code Playgroud)

初始化程序确实加载了数据库(正如您从输出的第一行中看到的那样),但由于某种原因,模式对测试不可见,要么是因为它在错误的位置查找,要么是因为它已被擦除测试开始。

有人以前见过这个吗?

hub*_*ert 2

看一下有关共享连接的信息:

http://blog.plataformatec.com.br/2011/12/ Three-tips-to-improve-the-performance-of-your-test-suite/

sqllite 维护每个连接的内存数据库。活动记录使用连接池,当您运行测试时,它使用不同的连接。您可以在各个点检查连接的对象 ID,以查看实际的对象更改。

如果您共享单个连接,您应该得到您期望的行为。

并且启动速度更快:-)