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

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

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
Emanuel Over 6 years ago