Read more

RSpec: How to check that an ActiveRecord relation contains exactly these elements

Emanuel
December 20, 2017Software engineer at makandra GmbH

To check which elements an ActiveRecord relation contains use the contain_exactly matcher.

describe User do
  let!(:admin) { create(:user, role: 'admin') }
  let!(:customer) { create(:user, role: 'customer') }
  
  subject(:users) { User.where(role: 'admin') }
  
  # Recommended (The error output is most helpful)
  it { expect(users).to contain_exactly(admin) }
  
  # Other options
  it { expect(users).to eq([admin]) }
  it { expect(users.pluck(:id).to eq([admin.id]) }
end

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

In case you have an ActiveRecord::AssociationRelation you can splat it to arguments. That way the contain_exactly matcher will work like expected again.

describe User do
  let!(:admin) { create(:user, role: 'admin') }
  let!(:customer) { create(:user, role: 'customer') }
  
  subject(:users) { User.where(role: 'admin') }

  it { expect(users).to contain_exactly(*User.where(role: 'admin').to_a) }
end
Posted by Emanuel to makandra dev (2017-12-20 15:25)