佘小宝的爹 发表于 2016-12-1 09:49:07

在Ruby On Rail中使用memory方式SQLite数据库攻略

  ROR做Unit Test的速度有些让人失望,使用内存数据库能够大幅提高Unit Test的速度,提高开发效率,今天刚刚配上了SQLite3,下面作一个简要攻略。
   
  假设你已经有一个rails的工程了,并且已经用SQLite3生成了一个development模式的数据库db/eplanner_development.db。
   
  1.       安装SQLite-ruby
  运行: gem install sqlite3-ruby
  选择mswin32安装
  2.       测试SQLite-ruby
   
    require 'sqlite3'
   
    db = SQLite3::Database.new( "test.db" )
   
  3.       修改database.yml
  #   gem install sqlite3-ruby
  development:
    adapter: sqlite3
    database: db/eplanner_development.db
  # In-memory SQLite 3 database.  Useful for tests.
  test:
    adapter: sqlite3
    database: ":memory:"
  4.       修改environment.rb
  把
  # config.active_record.schema_format = :ruby
          中的注释去掉
  5.       运行rake db_schema_dump
  生成schema.rb
  6.       修改environment.rb,把下面代码加到environment.rb的结尾
  def in_memory_database?
    ENV["RAILS_ENV"] == "test" and
    ActiveRecord::Base.connection.class==ActiveRecord::ConnectionAdapters::SQLiteAdapter and
    Rails::Configuration.new.database_configuration['test']['database'] == ':memory:'
  end
   
  if in_memory_database?
    puts "creating sqlite in memory database"
    load "#{RAILS_ROOT}/db/schema.rb" # use db agnostic schema by default
  #  ActiveRecord::Migrator.up('db/migrate') # use migrations
  end
  好了,现在可以享受内存数据库上做单元测试的快感了。在我的机器上,比MySQL上作单元测试速度要快接近一个数量级。
   
  再讲一下如何再SQLite和MYSQL之间如何切换。除了修改database.xml外,还要注释掉
  config.active_record.schema_format = :ruby
  然后运行rake migrate
  这个可能是ror migrate的一个BUG。


http://c.services.spaces.live.com/CollectionWebService/c.gif?space=dongbinspace&page=RSS%3a+%e5%9c%a8Ruby+On+Rail%e4%b8%ad%e4%bd%bf%e7%94%a8memory%e6%96%b9%e5%bc%8fSQLite%e6%95%b0%e6%8d%ae%e5%ba%93%e6%94%bb%e7%95%a5&referrer=http://c.live.com/c.gif?NC=31263&NA=1149&PI=88469&RF=&DI=3919&PS=85545&TP=dongbinspace.spaces.live.com&GT1=dongbinspace%3b2052
页: [1]
查看完整版本: 在Ruby On Rail中使用memory方式SQLite数据库攻略