woohaaha

woohaaha

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

Showing Posts 1 to 3

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 GitHub - alexocode/knigge: An opinionated way of dealing with behaviours · GitHub 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
ityonemo

ityonemo

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

Can you go into more detail as to why this is a problem?

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews