【问题标题】:Rails test db 10x faster than development dbRails 测试数据库比开发数据库快 10 倍
【发布时间】:2014-02-20 20:33:03
【问题描述】:

我有一些种子数据,可以在我的开发设置中创建 1000 个用户。有时我会在开发过程中使用此命令重置我的数据库:

rake db:reset

它以大约 10 个用户/秒的速度插入我的用户。我认为这很慢,但学会了忍受它。

我最近在测试环境中运行了db:reset,同时使用此命令调试了一些 rspec 测试:

rake db:reset RAILS_ENV=test

它以大约 100 个用户/秒的速度插入用户!我可以重现它并在环境之间切换,开发环境很慢,而测试环境很快。

它在database.yml中使用完全相同的mysql设置:

发展

development:
  adapter: mysql2
  encoding: utf8
  database: mydb
  username: mydb
  password: password
  host: 127.0.0.1
  port: 3306

测试

development:
  adapter: mysql2
  encoding: utf8
  database: mydb_test
  username: mydb_test
  password: password
  host: 127.0.0.1
  port: 3306

这就是我为用户播种的方式(两种环境都一样):

ActiveRecord::Base.transaction do
  1000.times do |i|
      User.create :first_name => Faker::Name.first_name, :last_name => Faker::Name.last_name, :email => Faker::Internet.email, :username => Faker::Internet.user_name, :password => '123456'
  end
end

有谁知道 Rails 正在做什么让测试环境如此之快?我想在开发环境中实现这些设置,并将我的播种过程加快 10 倍。

【问题讨论】:

  • 您能否添加更多有关您的种子文件和测试环境的详细信息?
  • 用户表上有索引吗?开发数据库中有很多用户吗?
  • 我添加了播种技术。
  • 只有这 1000 个用户。 devise 添加了一个名为“reset_password_token”的索引。
  • 奇怪的是它完全相同的命令,相同的种子数据,相同的mysql实例。唯一的区别是RAILS_ENV=test

标签: mysql ruby-on-rails ruby performance rspec


【解决方案1】:

如果您使用的是 Devise,则可能是密码拉伸造成的。在 config/initializers/devise.rb 中:

# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10

这似乎是您正在寻找的开发和测试环境之间的差异。试试这条线

【讨论】:

  • 对,应该是这个
【解决方案2】:

我想在开发环境中实现这些设置,并将我的播种过程加快 10 倍。

底线是如果你想立即插入太多数据,你不应该考虑使用 rails 方法。我遭受了它。Rails 附加了太多回调,例如 before_update, after_create 等。我每个数据都插入了 500K 数据。我们使用原始 sql 来加速这个过程。我们做了这样的事情

ActiveRecord::Base.transaction do
  inserts = []
  TIMES.times do
   inserts.push "(3.0, '2009-01-23 20:21:13', 2, 1)"
 end
 sql = "INSERT INTO user_node_scores (`score`, `updated_at`, `node_id`, `user_id`) VALUES #{inserts.join(", ")}"
 User.connection.execute  s
end

【讨论】:

  • 这是一项很棒的技术,但我想知道为什么环境在性能方面如此不同。
猜你喜欢
  • 2021-09-16
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2011-10-02
  • 2012-05-08
  • 1970-01-01
相关资源
最近更新 更多