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 online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
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)