Posted about 4 years ago. Visible to the public.

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.

Copy
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.

Copy
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

Flaky tests are tests that sometimes fail for no obvious reason. They are the plague of many end-to-end (E2E) test suites that automate the browser through tools like Capybara and Selenium.

Join our free training event and learn to fix any flaky test suite, even in large legacy applications.

Owner of this card:

Avatar
Emanuel De
Last edit:
about 4 years 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 Emanuel De to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more