Rewire (rewire v0.5.3) View Source

Rewire is a libary for replacing hard-wired dependencies of the module your unit testing. This keeps your production code free from any unit testing-specific concerns.

Usage

Given a module such as this:

# this module has a hard-wired dependency on the `English` module
defmodule Conversation do
  def start(), do: English.greet()
end

If you define a mox mock EnglishMock you can rewire the dependency in your unit test:

defmodule MyTest do
  use ExUnit.Case
  import Rewire                                  # (1) activate `rewire`
  import Mox

  rewire Conversation, English: EnglishMock      # (2) rewire `English` to `EnglishMock`

  test "start/0" do
    stub(EnglishMock, :greet, fn -> "g'day" end)
    assert Conversation.start() == "g'day"       # (3) test using the mock
  end
end

This example uses mox, but rewire is mocking library-agnostic.

You can use multiple rewires and multiple overrides:

  rewire Conversation, English: EnglishMock
  rewire OnlineConversation, Email: EmailMock, Chat: ChatMock

You can also give the alias a different name using as:

  rewire Conversation, English: EnglishMock, as: SmallTalk

Alternatively, you can also rewire a module inside a block:

  rewire Conversation, English: EnglishMock do   # (1) only rewired inside the block
    stub(EnglishMock, :greet, fn -> "g'day" end)
    assert Conversation.start() == "g'day"       # (2) test using the mock
  end

Link to this section Summary

Functions

Macro that allows to rewire (and alias) a module.

Link to this section Functions

Link to this macro

rewire(arg, opts)

View Source (macro)

Macro that allows to rewire (and alias) a module.

import Rewire

rewire App.ModuleToRewire, ModuleDep: Mock

# `ModuleToRewire` will use `Mock` now
end

Options

opts is a keyword list:

  • as - give the rewired module a different name

  • any other item, like ModuleDep: Mock, will be interpreted as a mapping from one module to another