测试使用ActiveRecord模型的gem

Ven*_* D. 10 testing activerecord rspec ruby-on-rails

我写了一个gem,如果你传入一个ActiveRecord模型,它会将数据导入你的数据库.例如:

importer = Importer.new(Widget)
importer.import(data_source)
Run Code Online (Sandbox Code Playgroud)

有没有一种好方法来测试这个宝石?我会以某种方式需要连接到测试数据库并创建测试模型.谢谢!

Ven*_* D. 19

大多数灵感来自这篇文章:http: //blog.markstarkman.com/blog/2013/01/23/using-sqlite-to-test-active-record-models/

首先,在你的gemspec中,你可以添加ActiveRecord和sqlite3作为依赖,如下所示:

spec.add_development_dependency "activerecord", "~> 4.0.0"
spec.add_development_dependency "sqlite3"
Run Code Online (Sandbox Code Playgroud)

然后在spec/schema.rb中,您可以像这样定义您的模式:

ActiveRecord::Schema.define do
  self.verbose = false

  create_table :users, :force => true do |t|
    t.string :key
    t.string :name
    t.integer :age
    t.datetime :dob

    t.timestamps
  end

end
Run Code Online (Sandbox Code Playgroud)

然后,您可以在models.rb文件中创建模型:

class User < ActiveRecord::Base
end
Run Code Online (Sandbox Code Playgroud)

在spec_helper.rb中,您希望连接到内存中的sqlite数据库,加载架构并需要模型:

require 'active_record'

ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"

load File.dirname(__FILE__) + '/schema.rb'
require File.dirname(__FILE__) + '/models.rb'
Run Code Online (Sandbox Code Playgroud)