micah

micah

Mox with Applications - to start or not to start

Hello all! I’m in the process of writing an application with a couple moving parts, but unit testing it is making me question everything.

My application supervises three processes:

children = [
        {DynamicSupervisor, strategy: :one_for_one, name: MyApp.SuperSpider},
        {MyApp.Database, name: MyApp.CurrentDatabase},
        {MyApp.SiteAPI, name: MyApp.SiteAPI},
 ]

When the SiteAPI starts, it loads and starts processes based on what is in the database:

def init(opts) do
     super_spider = opts |> Keyword.get(:super_spider, MyApp.SuperSpider)
     db = opts |> Keyword.get(:db, MyApp.CurrentDatabase)
     sites = db |> Database.get_sites()
     spiders = sites |> Enum.reduce(%{}, fn (site, acc) ->
       {:ok, new_pid} = DynamicSupervisor.start_child(
         super_spider, {MyApp.Spider, {site, db}}
       )
       Map.put(acc, site.id, new_pid)
     end)
     {:ok, %{db: db, super_spider: super_spider, spiders: spiders}}
end

Everything as near as I can tell works, except that when I start the unit tests using mix test, the application first uses the real “database” instead of the MockDatabase which is defined in test/test_helper.ex:

  Code.require_file("test/mock_dets.ex") # Mocking dets with ets
  Mox.defmock(MyApp.MockRequest, for: MyApp.Request)
  Mox.defmock(MyApp.MockDatabase, for: MyApp.Database)
  
  Application.put_env(:my_app, :use_delay, false)
  Application.put_env(:my_app, :request, MyApp.MockRequest)
  Application.put_env(:my_app, :database, MyApp.MockDatabase)
  Application.put_env(:my_app, :dets, MyApp.MockDETS)
 
  ExUnit.start()

When I run the unit tests, the Application is started before the Mox(s) are configured, and the real Database is used. What can I do to avoid this?

I’ve tried not starting the application with “–no-start” but this also stops the dependencies (like Mox) from starting.

Most Liked

micah

micah

@stefanchrobot Thank you for your quick response! MyApp.Database is both a behavior and a stub that routes it through the application environment variable “:database”

defmodule MyApp.Database do

  @doc """
    Create a new database process
  """
  @callback start_link() :: GenServer.on_start()
  def start_link(), do: impl().start_link()
  @callback start_link(_ :: integer) :: GenServer.on_start()
  def start_link(arg), do: impl().start_link(arg)

  @doc """
    Information for adding to supervision trees
  """
  @callback child_spec(term()) :: Supervisor.child_spec()
  def child_spec(arg), do: impl().child_spec(arg)

  # Lots more functions following a similar pattern here...

  defp impl, do: Application.get_env(:my_app, :database, MyApp.FileDB)
end

The whole app is open source, but it’s really messy (I’ve made some poor design/naming decisions) and definitely a work in progress: ~electric/shop_local: apps/product_search/lib/database.ex - sourcehut git

ajur58

ajur58

I had a very similar use-case to yours and almost gave up. Then I found your implementation linked above and it works!! Thanks for making it open source!

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
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
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
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

We're in Beta

About us Mission Statement