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!
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With