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.
1
|
|
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
.
1 2 3 4 5 6 7 8 9 10 11 |
|
To actually run them you need to load the file. Add this line to your spec/spec_helper.rb
file.
1
|
|
Next, create your models. I did this in a spec/support/models.rb
file.
1 2 |
|
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.
1
|
|
Using an in-memory SQLite database helped me ensure that the CanBe gem works against fully functioning Active Record models.