When I first released both ArabicHelper and SimplySearchable I didn’t have any tests for them because I didn’t know the right way to write those tests. After doing some digging and looking at other plugins tests I found out how, and I’m sharing that here with you.
Specifically for ActiveRecord extensions you need a database and models definition to test your plugin, to do that you have to:
- Require ActiveRecord gem:
require 'activerecord'
- Establish an ActiveRecord connection to a memory based sqlite3 database:
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:")
- Define both setup_db and teardown_db:
def setup_db ActiveRecord::Schema.define(:version => 1) do create_table :posts do |t| t.column :title, :string t.column :body, :text t.column :category_id, :integer end create_table :categories do |t| t.column :id, :integer t.column :name, :string end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end
- Define your models:
class Post < ActiveRecord::Base belongs_to :category end class Category < ActiveRecord::Base has_many :posts end
- Finally define both setup and teardown methods in your test class (Note that all the above should be placed before your test class definition):
def setup setup_db end def teardown teardown_db end
That’s it, now you can write your tests as if you’re writing them in your Rails application unit tests. Check the following for more example tests: