Testing ActiveRecord callbacks with RSpec

Updated . Posted . Visible to the public. Repeats.

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

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
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-02-22 13:40)