测试使用ActiveRecord模型的gem [英] Testing a gem that uses ActiveRecord models
问题描述
我写了一个gem,如果您传入ActiveRecord模型,它将数据导入数据库。例如:
I wrote a gem that imports data into your database if you pass in an ActiveRecord model. For example:
importer = Importer.new(Widget)
importer.import(data_source)
是否有测试此gem的好方法?我将以某种方式需要连接到测试数据库并创建测试模型。谢谢!
Is there a good way to test this gem? I would somehow need to connect to a test database and create a test model. Thanks!
推荐答案
此帖子的主要启发是:
http://blog.markstarkman.com/blog/2013/01/23/using -sqlite-to-test-active-record-models /
Mostly inspired from this post: http://blog.markstarkman.com/blog/2013/01/23/using-sqlite-to-test-active-record-models/
首先,在您的gemspec中,可以将ActiveRecord和sqlite3添加为依赖项,如下所示:
First, in your gemspec, you can add ActiveRecord and sqlite3 as dependencies like so:
spec.add_development_dependency "activerecord", "~> 4.0.0"
spec.add_development_dependency "sqlite3"
然后在spec / schema.rb中,您可以这样定义模式:
Then in spec/schema.rb, you can define your schema like so:
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
然后您可以在模型中创建模型。 rb文件:
Then you can create your models in a models.rb file:
class User < ActiveRecord::Base
end
在您的spec_helper.rb中,您想连接到内存中的sqlite数据库,加载架构并需要模型:
In your spec_helper.rb, you want to connect to an in-memory sqlite database, load the schema, and require the models:
require 'active_record'
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
load File.dirname(__FILE__) + '/schema.rb'
require File.dirname(__FILE__) + '/models.rb'
这篇关于测试使用ActiveRecord模型的gem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!