dashbitco / mox

Mocks and explicit contracts in Elixir
1.35k stars 77 forks source link

Global mocks? #67

Closed strzibny closed 5 years ago

strzibny commented 5 years ago

Imagine a thin HTTP client. We need to mock it in our tests which is pretty easy and straightforward with Mox. We can mock successful response in one and unsuccessful in another. That's great and one reason why it's a bit better than writing the HTTPMock module ourselves/

What I found though is that this brings a lot of repetition potentially for the successful response (and especially if the response is long). What if we can instrument Mox to stub the successful response for all test in one place and only change this response in the few tests that require it?

What if the following definition:

HTTPMock
|> stub(:get, ...

could exist once (loaded in test_helper.exs or in the similar way)? And just be overridable when necessary?

Perhaps something as:

HTTPMock
|> stub_default(:get, ...

Or are there other patterns how to make our life easier that I am probably not aware of?

josevalim commented 5 years ago

To solve that duplication you can use setup blocks with stub_with. You can encapsulate the setup block in a small function or even make it part of a ExUnit.CaseTemplate. So I think we have enough tooling in the test framework to help address this without having to change Mox, thanks!

strzibny commented 5 years ago

Thanks Jose, just tried it and it does exactly what I wanted to achieve!

For others: I defined a new stub using stub_with which is my default mock. It lives inside an ExUnit case so can be easily included in tests that depend on it. And I am still able to override it with default Mox stub call.