使用 MyISAM 表进行 Rails 单元测试
我有一个应用程序需要在几个表上使用MyISAM,但其余的都是传统的InnoDB类型。应用程序本身并不关心应用于这些记录的事务,但性能是一个问题。
不过,Rails 测试环境假定所使用的引擎是事务性的,因此当从 schema.rb 生成测试数据库时,它会使用相同的引擎导入。是否可以通过简单的方式覆盖此行为?
我采用了一种糟糕的方法,通过将其附加到 test_helper.rb 来确保表的类型正确:
(ActiveRecord::Base.connection.select_values("SHOW TABLES") - %w[ schema_info ]).each do |table_name|
ActiveRecord::Base.connection.execute("ALTER TABLE `#{table_name}` ENGINE=InnoDB")
end
是否有更好的方法使 MyISAM 支持的模型可测试?
I've got an application that requires the use of MyISAM on a few tables, but the rest are the traditional InnoDB type. The application itself is not concerned with transactions where it applies to these records, but performance is a concern.
The Rails testing environment assumes the engine used is transactional, though, so when the test database is generated from the schema.rb it is imported with the same engine. Is it possible to over-ride this behaviour in a simple manner?
I've resorted to an awful hack to ensure the tables are the correct type by appending this to test_helper.rb:
(ActiveRecord::Base.connection.select_values("SHOW TABLES") - %w[ schema_info ]).each do |table_name|
ActiveRecord::Base.connection.execute("ALTER TABLE `#{table_name}` ENGINE=InnoDB")
end
Is there a better way to make a MyISAM-backed model be testable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以编辑 schema.rb 并修改 create_table 调用以包含以下标志,如下所示:
创建迁移时,尝试将其添加到迁移中。我不知道当您运行 rake db:schema:dump 时这是否会持续。根据您的经验,测试环境似乎没有正确复制开发环境,它可能不会:(
有关 create_table 选项的更多信息,请参见:
http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M001901
You can edit your schema.rb and modify the create_table call to include the following flag, like so:
When you create your migrations, try adding that to the migrations. I don't know if this will stick when you run rake db:schema:dump. Given your experience that the test environment doesn't seem to be copying the development environment properly, it may not :(
More info about create_table options here:
http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M001901
你可以
在test_helper.rb中设置
you can set
in test_helper.rb
您可以将其添加到
application.rb
中:这样,测试数据库在使用命令
rake db:test:prepare
时就不会出现任何问题。在迁移文件中,您可以将其添加到up
方法中,而不是重新创建表(如果您需要将现有的 InnoDB 表更改为 MyISAM):You can add this to
application.rb
:With this, test db will not have any problem with the command
rake db:test:prepare
. In migration file, instead of recreating your tables (if you need to change existing InnoDB table to MyISAM), you can just add this toup
method:中显式添加引擎
您可以添加此 SchemaDumper Monkeypatch 以在 schema.rb https://gist.github.com/1374003
这是 Rails 2.3.14 的猴子补丁,因此不能保证 Rails 3
You can add this SchemaDumper monkeypatch to add the engine explicitly in your schema.rb
https://gist.github.com/1374003
This is monkeypatched from Rails 2.3.14 so no guarantees with Rails 3