jjh42 / mock

Mocking library for Elixir language

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

There is any way to improve the `setup_with_mocks` behaviour?

MrCoffey opened this issue · comments

Hi guys, I am trying to clean a bit my tests which in this moment are full of with_mock/4 functions, I found setup_with_mocks that looks like a potential solution, nevertheless, although it helps a lot with some tests that share the same mock, sometimes I need to change the data that was already mocked before in those cases I need to use with_mock/4 inside my test macro.

In order to help explain my issue, I would like to show a little bit of my code:

  describe "A user tries to login" do
    setup_with_mocks([
      {
        MyMockedModule, [], [
          log_user_in: fn(_user) -> {:ok, "Successfully logged in"} end,
          another_mocked_function: fn(_payload) -> standard_user_mock() end,
        ]
      }
    ], %{conn: conn}) do

      {:ok, conn: conn}
    end

    test "test 1", %{conn: conn} do
      conn =
        conn
        |> post(auth_path(conn, :login), %{"email" => "email@example.com", "password" => "1234"})

      body = json_response(conn, 200)
    end

    test "test 2", %{conn: conn} do
      with_mock MyMockedModule, [
        log_user_in: fn(_user) -> %{:error, "message" => "INVALID provided password"} end,
        another_mocked_function: fn(_payload) -> standard_user_mock() end,
      ] do
        conn =
          conn
          |> post(auth_path(conn, :login), %{"email" => "email@example.com", "password" => "1325"})

        body = json_response(conn, 401)
        assert body["errors"]["message"] == "INVALID provided password"
      end
    end
 end

In this example, I use setup_with_mocks to clean the describe group, the issue, as shown above, is when I need to mock a different function of my MyMockedModule the library force me to rewrite all the mocks again (even those that I don't need to change 🙁 ) if I don't I will receive a ** (UndefinedFunctionError) function exception.

Maybe am I doing something wrong here, do you have any advice?

Overriding the mocked data for a specific test should be possible given the setup you have.

setup_with_mocks is similar to Exunit's setup; there should only be one at the top of the file.

As far as I can tell, moving setup_with_mocks outside your describe statement should fix resolve the issue.

Thank you for your fast response. I move it outside and the ** (UndefinedFunctionError) function exception remains when I don't re-define a function inside the with_mock function.

When you mock something inside a specific test it completely overrides the mock setup in setup_with_mocks. If you're mocking two functions in setup, but only want to override the behaviour for one of the mocks in a specific test, while keeping the behaviour of the other mock the same, you'd have to redefine that.

Understood, thank you so much for your kind help.