2012-03-30 49 views
2

我正在研究包含迁移生成器和一堆模型,类等的Gem,这些模型,类等利用作为迁移一部分创建的表。Gem中的测试需要测试迁移生成器并将迁移应用于测试

虽然测试迁移生成器本身是很容易的 - 有大量的教程来完成这个工作,我正在努力解决的是如何在测试数据库上真正运行迁移,以便稍后测试宝石与测试数据交互?

由于gem没有schema.rb,所以我不知道该怎么去做。

回答

1

我这是怎么运行的代码迁移;

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") 
    ActiveRecord::Migration.verbose = false 

    @migration = Class.new(ActiveRecord::Migration) do 

    def change 
     create_table :users, :force => true do |t| 
     t.string  :roles_mask 
     end 
     create_table :user_without_roles, :force => true do |t| 
     t.string  :roles_mask 
     end 
     create_table :user_without_role_masks, :force => true do |t| 
     end 
    end 

    end 

    @migration.new.migrate(:up) 

如果您拥有一个包含生成的迁移,你可以做这样的事情在您的测试设置的字符串;

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") 
    ActiveRecord::Migration.verbose = false 

    # Or however you intend to grab the output of the migration generator 
    migration_string = ERB.new(File.read(<file name here>)).result 

    migration = Class.new(ActiveRecord::Migration) 
    migration.class_eval(migration_string) 
    migration.new.migrate(:up) 

这应该为您提供一个使用您生成的迁移的迁移数据库。

0

你可以这样做:

我打算假设你正在使用ActiveRecord。因此,在您的测试帮助你应该建立一个内存数据库:

require 'active_record' 

# Connection must be establised before anything else 
ActiveRecord::Base.establish_connection(
    :adapter => defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3', 
    :database => ':memory:' 
) 

然后调用你的测试中rake任务。这看起来像这样:

require 'rake' 
requie File.expand_path('../Rakefile', __FILE__) # you'll need to modify this path to actually point to the Rakefile 

Rake::Task['db:migrate'].invoke 

耙taks调用是未经测试,但这应该指向你在正确的方向。

另一种选择是只运行命令:

%x{rake db:migrate}