Read more

Testing ActiveRecord callbacks with RSpec

Henning Koch
February 22, 2016Software engineer at makandra GmbH

Our preferred way of testing ActiveRecord is to simply create/update/destroy the record and then check if the expected behavior has happened.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

We used to bend over backwards to avoid touching the database for this. For this we used a lot of stubbing and tricks like it_should_run_callbacks Show archive.org snapshot .

Today we would rather make a few database queries than have a fragile test full of stubs.

Example

Let's say your User model creates a first Project on creation, so the user doesn't see a blank application slate on her first visit:

class User < ActiveRecord::Base

  has_many :projects

  after_create :create_first_project
  
  private
  
  def create_first_project
    projects.create(name: 'My first project')
  end

end

Note

Avoid having callbacks like this in your core User model. Prefer to use a form model Show archive.org snapshot like User::RegistrationForm. Read our book Growing Rails Applications in Practice Show archive.org snapshot for details.

Here is a test for the User model that automatically creates a Project:

describe 'User' do

  describe '#save' do
  
    it "creates a first project for the user" do
      user = FactoryBot.create(:user)
      user.projects.size.should == 1
      user.projects[0].name.should == 'My first project'
    end
  
  end

end
Posted by Henning Koch to makandra dev (2016-02-22 14:40)