Reputation: 2916
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
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
Reputation: 2904
I would say the simplest way to test this is to:
: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