2012-03-30 52 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}