Today I Learned

ActiveRecord test objects made easy

If you're testing a ActiveRecord model mixin in your application, you might be tempted to unit test it in the context of one of your app's models. However, that would violate your test isolation and introduce complexities related to the behavior of the model.

Better solution is to make an Active Record class just for your test, and the fact that you can invoke schema definitions on the fly makes it super easy. Here's the top of one of my specs, illustrating the technique.

require 'rails_helper'

ActiveRecord::Schema.define do
  create_table :test_objects, force: true do |t|
    t.jsonb :jobs, null: false, default: {}

class TestObject < ApplicationRecord
  include WorkerRegistry

RSpec.describe WorkerRegistry do
  let(:test_object) { TestObject.create }


The "Bible" of Ruby on Rails is better than ever

For a limited time, get half off the ultimate The Rails 5 Way package

The "Future Proof Package" is available to TIL readers for only $20. It includes The Rails 5 Way, plus early access to Obie's next two books: Mastering The Rails Way and Testing The Rails Way

Looking for help? Obie Fernandez of Kickass Consulting has been the foremost industry expert on Ruby on Rails development for over 10 years. Rails is a core skill for each developer at Kickass Consulting and we'd love to take a look at your project. Contact us today and find out how we can help you.