We will cover Rewire's core concepts, how to get started with it, and practical examples. We will also see how to use Rewire alongside Mox. One o

Advanced Dependency Injection in Elixir with Rewire

submited by
Style Pass
2024-06-11 10:30:02

We will cover Rewire's core concepts, how to get started with it, and practical examples. We will also see how to use Rewire alongside Mox.

One of the challenges we faced in our previous article was the lack of a structured way to define and inject dependencies into our modules. We had to manually define our mocks for testing.

To recap part one of the series, we discussed the benefits of DI for testability and modularity. We saw how we can use pass-in dependencies via function parameters:

In Elixir, modules are stateless, so the primary way to pass dependencies to a module is via function parameters. While Elixir modules can have attributes, these are used for compile-time information and metadata, not for holding runtime state.

Take the EmailScanner module, for example. We have to pass the SpamFilterService as a parameter to the scan_email function. This is unnecessary, as the only reason to have this function parameter is to make the module testable.

This approach might work well for small projects, but as our project grows, we might find ourselves repeating the same pattern over and over again. With Rewire, we don't have to worry about these issues. We can just focus on writing clean and maintainable code while keeping any testing concerns, mocks, and stubs in our test files.

Leave a Comment