mongoid-rspec icon indicating copy to clipboard operation
mongoid-rspec copied to clipboard

matcher for fire_query `expect { }.not_to fire_mongodb_query`

Open Startouf opened this issue 7 years ago • 0 comments

Cf https://stackoverflow.com/questions/50647759/rspec-expect-no-mongoid-database-query-fired

I was wondering if it would be possible to add a matcher that checks whether any Mongoid query is performed by a block of code.

I am implementing various caching strategies (not necessarily using Rails.cacheas depicted below), and I'd like to test easily whether a query was actually fired by the adapter.

I'm not so knowledgeable about Mongoid internals, and after trying a bit I could not come up with some relevant expectation strategy for such a matcher.

The matcher I'm thinking about would be useful to test this

class FooService
  def self.recent_foos
    Rails.cache.fetch("foos", expires_in: 1.day) do
      Foo.desc(:created_at).limit(10)
    end
  end
end

describe FooService
  context 'when recent foos were already retrieved'
    before { FooService.recent_foos }

    context 'retrieving foos again within 2 hours'
      before { Timecop.freeze(2.hours.from_now }
      after { Timecop.return }

      it 'does not hit the DB'
        expect { FooService.recent_foos }.not_to fire_mongodb_query
      end
    end
  end

Startouf avatar Sep 25 '18 23:09 Startouf