11

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)

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!

Venkat D.
  • 2,979
  • 35
  • 42

1 Answers1

23

Mostly inspired from this post: http://blog.markstarkman.com/blog/2013/01/23/using-sqlite-to-test-active-record-models/

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"

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

Then you can create your models in a models.rb file:

class User < ActiveRecord::Base
end

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'
Venkat D.
  • 2,979
  • 35
  • 42
  • 1
    I had to change `require 'activerecord'` to be `require 'active_record`'. Very easy thing to mess up. Thanks for the answer. I doubt I would have noticed my problem without iti. – wuliwong Jul 31 '15 at 23:22
  • Perhaps it's not a good idea since different adapters, say sqlite3, mysql and postgresql, are in fact different. For a more comprehensive test, you need to test all 3 adapters. However, adapters except sqlite3 are a little difficult to test at installation time. So I'd prefer to test them in development time only. – Robert Oct 03 '16 at 03:26