Read more

RSpec matcher to check if an ActiveRecord exists in the database

Henning Koch
March 18, 2011Software engineer at makandra GmbH

The attached RSpec matcher exist_in_database checks if a given record still exists in the database and has not been destroyed:

describe Ticket do
  describe '.purge_expired' do
    fresh_ticket = Ticket.create(:expiry => Date.tomorrow)
    expired_ticket = Ticket.create(:expiry => Date.yesterday)
    Ticket.purge_expired
    fresh_ticket.should exist_in_database
    expired_ticket.should_not exist_in_database
  end
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

Note that there is also ActiveRecord::Base#destroyed? Show archive.org snapshot , but that only checks the receiving instance and does not talk to the database. It would not help with the example above.

Spec::Matchers.define :exist_in_database do

  match do |actual|
    actual.class.exists?(actual.id)
  end

end
Posted by Henning Koch to makandra dev (2011-03-18 20:48)