Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a gem that uses ActiveRecord models

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!

like image 270
Venkat D. Avatar asked Aug 31 '13 00:08

Venkat D.


People also ask

Is ActiveRecord a gem?

ActiveRecord is a gem that is part of Ruby on Rails. It is the ORM, i.e. the library that maps our objects to tables. In other words, it is the Ruby library that allows us to use Ruby classes in order to access our data stored in an RDBMS, like MySQL or PostgreSQL.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

How do you test a Ruby gem?

The rub test includes rubbing your ruby across a smooth (but hard) surface, like glass, and seeing if the gem leaves any color behind. Glass only has a hardness of 5 on the Mohs scale, so it's much softer than actual rubies. Real rubies and some gems shouldn't leave any color behind, but cheap fakes or imitations can.

What is ActiveRecord?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

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'
like image 78
Venkat D. Avatar answered Oct 21 '22 03:10

Venkat D.