Rewire (rewire v0.3.1) View Source
Rewire is a libary for replacing hard-wired dependencies of the module your unit testing. This allows you to keep your production code free of any unit testing-specific concerns.
Example
defmodule Conversation do
def start(), do: English.greet() # the dependency is hard-wired
endYou can rewire the dependency with a mock, using mox for example:
defmodule MyTest do
use ExUnit.Case
use Rewire
import Mox
rewire Conversation, English: Mock # acts as an alias to the rewired module
test "greet" do
stub(Mock, :greet, fn -> "bonjour" end)
assert Conversation.start() == "bonjour" # this uses Mock now!
end
enddefmodule MyTest do
use ExUnit.Case
use Rewire
import Mox
rewire Conversation, English: Mock # acts as an alias to the rewired module
test "greet" do
stub(Mock, :greet, fn -> "bonjour" end)
assert Conversation.start() == "bonjour" # this uses Mock now!
end
endAlternatively, you can also rewire a module on a test-by-test basis:
defmodule MyTest do
use ExUnit.Case
use Rewire
import Mox
test "greet" do
rewire Conversation, English: Mock do # within the block it is rewired
stub(Mock, :greet, fn -> "bonjour" end)
assert Conversation.start() == "bonjour" # this uses Mock now!
end
end
endYou can also give the alias a different name using as:
rewire Conversation, English: Mock, as: SmallTalk Link to this section Summary
Functions
Macro that allows to rewire (and alias) a module.
Macro that allows to rewire a module within a block.
Link to this section Functions
Macro that allows to rewire (and alias) a module.
use Rewire
rewire App.ModuleToRewire, ModuleDep: Mock
# `ModuleToRewire` will use `Mock` now
endOptions
opts is a keyword list:
as- give the rewired module a different nameany other item, like
ModuleDep: Mock, will be interpreted as a mapping from one module to another
Macro that allows to rewire a module within a block.
use Rewire
rewire App.ModuleToRewire, ModuleDep: Mock do
# `ModuleToRewire` will use `Mock` now
endSee rewire/2 for a description of options.