测试使用 ActiveRecord 模型的 gem [英] Testing a gem that uses ActiveRecord models

查看:25
本文介绍了测试使用 ActiveRecord 模型的 gem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个 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

然后你可以在一个 models.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆