Using SQLite to Test Active Record Models

When I started creating my CanBe gem, I realized that I would need to test fully functioning Active Record models. This would ensure that the gem would function correctly when used in a Rails app. However, I didn’t want to force myself or anyone else to setup a database on their local system when developing. A SQLite database seemed to fit the bill. Anyone developing functionality for my gem would likely already have the requirements for the sqlite3 gem since they probably would have already started a Rails application or two.

Still, I didn’t want to have to worry about creating the database and ensuring it was available every time the specs were run. Then I found out that you can create an in-memory SQLite database. This was a perfect fit!

There are only a few things you need to get this up and running. I am using RSpec for my testing, so all of the configuration below is in that context. First, you will need to add this line to your spec/spec_helper.rb file.

Add to spec/spec_helper.rb
1
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"

Now you have a database that you can run your migrations against and use your regular Active Record models. Here is an example migration that you could create in the spec/support/schema.rb.

spec/support/schema.rb
1
2
3
4
5
6
7
8
9
10
11
ActiveRecord::Schema.define do
  self.verbose = false

  create_table :addresses, :force => true do |t|
    t.string :street
    t.string :city
    t.string :state
    t.string :zip
    t.timestamps
  end
end

To actually run them you need to load the file. Add this line to your spec/spec_helper.rb file.

Add to spec/spec_helper.rb
1
load 'support/schema'

Next, create your models. I did this in a spec/support/models.rb file.

spec/support/models.rb
1
2
class Address < ActiveRecord::Base
end

Once, you require the models.rb file into your spec/spec_helper.rb file, you will have access to the Address model in your specs and it will function as a fully functioning Active Record model.

Add to spec/spec_helper.rb
1
require 'support/models'

Using an in-memory SQLite database helped me ensure that the CanBe gem works against fully functioning Active Record models.

Comments
« Shipping vs. Learning Defining your customers »

Comments