简体   繁体   中英

Enum in Rails unit tests

I am working on testing some legacy code. One of the tables has an enum column. (I know, don't hate. I didn't write it).

Everything works fine until a try to run a unit test. Suddenly the database schema is saving the enum column as a varchar(0) . The obviously doesn't let me set any value.

Here's my big question. How can I add a hook to the rake test:units to adjust the column type? It doesn't matter if its an enum or just a varchar(100) .

Thanks!

So this problem turned out to have an easier solution than I expected. In the environment.rb file there is a section:

# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql

Uncommenting the last line means two things. First, the schema is exported in SQL instead of Ruby. Second, database specific datatypes are preserved.

config.active_record.schema_format = :sql

Okay I am not suggesting this as a solution to all problems but in this case you could hack in your own rake task to change the column type to a string as so:

namespace :db do
  desc "Change column type"
    task :test_setup do
      Rake::Task['db:test:prepare'].invoke
      Rails.env = ENV['RAILS_ENV'] = 'test'
      ActiveRecord::Migration.change_table :YOUR_TABLE_NAME do |t|
        t.change :YOUR_ENUM_COLUMN_NAME, :string, :limit => 100
      end
    end
end

This file would be placed in lib/tasks as whatever_you_want_to_call_it.rake. Then instead of rake db:test:prepare you would run rake db:test_setup which will run rake db:test:prepare and then alter the enum column to a varchar(100) which I believe will satisfy your needs here. Please correct me if I am wrong.

You should also be able to plug in your call to test:units here too with Rake::Task['test:units'].invoke although I have not tested this.

Again hacking things like this is not something I would generally recommend since you are really changing the data type and how it is handled by the database but since this is what you requested I thought I would try and help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM