Testing a gem using ActiveRecord models

I wrote a gem that imports data into your database if you are passing an ActiveRecord model. For example:

importer = Importer.new(Widget) importer.import(data_source) 

Is there a good way to test this stone? Somehow I will need to connect to the test database and create a test model. Thanks!

+7
ruby-on-rails activerecord testing rspec
source share
1 answer

Mostly inspired by 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:

 spec.add_development_dependency "activerecord", "~> 4.0.0" spec.add_development_dependency "sqlite3" 

Then in spec / schema.rb you can define your schema as follows:

 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 the models.rb file:

 class User < ActiveRecord::Base end 

In your spec_helper.rb you want to connect to the sqlite database in memory, load the schema, and require the model:

 require 'active_record' ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" load File.dirname(__FILE__) + '/schema.rb' require File.dirname(__FILE__) + '/models.rb' 
+13
source share

All Articles