Posted almost 4 years ago. Visible to the public. Repeats.

Testing ActiveRecord callbacks with RSpec

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.

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


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

(Side note: Avoid having callbacks like this in your core User model. Prefer to use a form model like User::RegistrationForm. Read our book Growing Rails Applications in Practice for details. Anyway, we will continue with the example.)

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

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Henning Koch
Last edit:
over 1 year ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more