Search code examples
mockingelixirphoenix-frameworkectostubbing

How to mock/stub methods in Elixir library Ecto/Repo?


Tell me please how to mock/stub methods of Repo module for my tests?

For ex.:

  link = Repo.get_by(Link, short_url: url)
  db_count = Repo.aggregate(Link, :count, :id)

I need that Repo.aggregate returns 10000000000 for my tests. The same with Repo.get_by.

How to do it?

And what is the best approach for module isolation in tests in Elixir?

Thanks!


Solution

  • Here's an example from https://github.com/gialib/ex_mock readme:

    defmodule MyTest do
      use ExUnit.Case, async: false
    
      import ExMock
    
      test "test_name" do
        with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do
          HTTPotion.get("http://example.com")
          # Tests that make the expected call
          assert called HTTPotion.get("http://example.com")
        end
      end
    end