woohaaha

woohaaha

How to use Mox for a module you own?

I cannot seem to get Mox to work for my Accounts module. Here is sort of the code.

# test_helper.exs

ExUnit.start(exclude: [:skip])
Mox.defmock(MyApp.MockAccounts, for: MyApp.Accounts)
# my_app/accounts.exs

defmodule MyApp.Accounts do
  @callback get_role(map()) :: :admin | :user

  def get_role(current_user) do
    # temporary authorization hack
    # yes, i am using my real email (note, real email is not being used here)
    case current_user.email do
      "myrealemail@gmail.com" -> :admin
      _ -> :user
    end
  end
# test/integration/admin_area_only_test.exs

defmodule MyApp.Integration.AdminAreaOnlyTest do
  use MyApp.ConnCase, async: true

  import Mox
  setup :verify_on_exit!

  test "admin area only" do
    MyApp.MockAccounts
    |> expect(:get_role, fn(_user) -> :admin end)

    # email used here is different because I don't want personal email in tests (yes, a bit ironic, but here we are)
    {:ok, user} = MyApp.Accounts.create_user(%{email: "hi@example.com", password: "123"})

    conn =
      session_conn()
      |> put_session(:user_id, user.id)
      |> put_session(:current_user, user)

   etc...

  # assertions
  # it fails because user doesn't have permission

I would rather not have to modify prod.exs, test.exs, and dev.exs because that means I’ll have to use Application.get_env for my Accounts module which is used everywhere. All the Mox examples are used for small libs and external requests like Httpoison but what about an internal module?

Any direction would be greatly appreciated.

Thank you

Most Liked

LostKobrakai

LostKobrakai

It’s not really an issue of external vs. internal modules.

You seem to be expecting mox to be able to intercept function calls, which is not possible on the beam. If you call MyApp.Accounts.create_user it’ll call the given module and not MyApp.MockAccounts. There’s no way to intercept calls to MyApp.Accounts and make them be magically resolved by the function on the mock module.

If you want to use mox you need to have means to switch out the real implementation with the mock implemenation in your codebase, so the functions are actually called on the mock module of mox. This can be done using the app env, but there are also other ways to inject the mock module.

Often those means are created automatically for things you expect to switch out anyways like http clients. That might make you feel like Mox is catered specifically for those elements. But the same mechanisms do work for switching out any real implementation with an mocked one. No matter what the code is about.

No matter how you’re going to deal with dependency injection (app env or not) you’re correct in that you don’t want to concern the callers of functions on MyApp.Accounts with the decision which implementation to call. But you can move the code you currently have in MyApp.Accounts to e.g. MyApp.Accounts.Impl and do the decision making within MyApp.Accounts. For every function either forward to MyApp.Accounts.Impl or use a different module, which was somehow injected to be used.

egze

egze

To add to this:

  1. Have a look at https://github.com/sascha-wolf/knigge It can simplify the boilerplate.
  2. Maybe it’s just my preference, but for behaviour MyApp.Accounts name the implementation - MyApp.AccountsImpl. Then if you use the quick find function in editors, if you type Accounts, you will see both. (some editors like VSCode will find both even in your case, but not all editors). Also I name my mock - MyApp.AccountsMock

Where Next?

Popular in Questions Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement