Rails Unit Testing with MyISAM Tables
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?
You can edit your schema.rb and modify the create_table call to include the following flag, like so:
create_table(:suppliers, :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
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
you can set
self.use_transactional_fixtures = false
in test_helper.rb
You can add this to application.rb
:
config.active_record.schema_format = :sql
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 to up
method:
execute("ALTER TABLE your_table ENGINE=MyISAM")
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
精彩评论