RSpec matcher to check if an ActiveRecord exists in the database

Updated . Posted . Visible to the public.

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

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
Henning Koch
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-03-18 19:48)