【问题标题】:Why aren't my Rails tests seeing the contents of my in-memory SQLite3 database?为什么我的 Rails 测试看不到内存中 SQLite3 数据库的内容?
【发布时间】:2012-04-11 08:18:04
【问题描述】:

我正在尝试通过使用 SQLite3 内存数据库作为应用程序的测试数据库来加快 Rails 应用程序的测试。我已按照blog post 中的说明进行操作。

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

test:
  adapter: sqlite3
  database: ":memory:"
  encoding: utf8
  verbosity: quiet

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

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

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

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

初始化程序确实加载了数据库(从输出的第一行可以看出),但由于某种原因,架构对测试不可见,要么是因为它在错误的位置寻找,要么是因为它已被擦除到测试开始时。

有人见过这个吗?

【问题讨论】:

    标签: ruby-on-rails testing sqlite


    【解决方案1】:

    看看这个关于共享连接的内容:

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

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

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

    启动速度更快:-)

    【讨论】:

      【解决方案2】:

      只需将下面的代码放在 test_helper.rb 中

      def in_memory_database?
          ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLiteAdapter ||
          ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLite3Adapter and
          Rails.configuration.database_configuration['test']['database'] == ':memory:'
      end
      
      class ActiveSupport::TestCase
          if in_memory_database?
              ActiveRecord::Schema.verbose = false
              puts "creating sqlite in memory database"
              load "#{Rails.root}/db/schema.rb"
          end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-06
        相关资源
        最近更新 更多