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
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
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.name.should == 'My first project' end end end