Skip to content

matcher for fire_query expect { }.not_to fire_mongodb_query #225

Open
@Startouf

Description

@Startouf

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions