DEV Community

Samnang Chhun
Samnang Chhun

Posted on

Setup ActiveRecord model tests in RSpec which don't depend on Rails

Sometimes when we build a gem that depends on ActiveRecord, we want to set up RSpec to load ActiveRecord and some database migration to be ready for our integration tests. We can generate a dummy Rails application to load in your tests, but I feel it needs a lot of setups and have unnecessary files are generated which we don't need.

Below is a setup to load ActiveRecord with SQLite in-memory database which is easy to set up database migration and run it.

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
    t.string :title
  end
end

class Post < ActiveRecord::Base
end

RSpec.configure do |config|
  config.around do |example|
    ActiveRecord::Base.transaction do
      example.run

      raise ActiveRecord::Rollback
    end
  end
end

RSpec.describe "ActiveRecord Tests" do
  it "works with activerecord" do
    Post.create(title: "foobar")

    expect(Post.count).to eq(1)
  end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)