mhutter
mhutter

Reputation: 2916

How to test that the DB was NOT queried

In my Phoenix app, I have a function which fetches some data from the DB and then caches it in an Agent. How can I write a test to ensure only the first time a value is requested the DB is actually queried?

Upvotes: 1

Views: 73

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

The proper way of doing this would be to mock the DB instance with e.g. Mox to use an explicit contact for the DB queries.


If you are using Ecto, it does it itself; check the config/test.exs file to see that it uses Ecto.Adapters.SQL.Sandbox in tests. Copy the whole sandbox.ex file to your test suite, modify Connection.handle_execute/4 to perform something like IO.puts to a console or like. Change your test.exs config to use this pool. Then check that the first time it was printed, and the second time it was not.

That might look like an overkill here, but in the long run, this approach would pay back (I’d say sooner rather than later.)

Upvotes: 1

bschaeffer
bschaeffer

Reputation: 2904

I would say the simplest way to test this is to:

  1. Call the agent and store the value
  2. Modify the value on the database
  3. Call the agent again and expect the first value
:ok = DB.insert("old_value")
assert {:ok, "old_value"} = YourCache.get_value()
:ok = DB.insert("new_value")
assert {:ok, "old_value"} = YourCache.get_value()

Upvotes: 1

Related Questions