Mocking Elixir IO.puts
I’m diving head first into Elixir, but not following a linear approach. I’m taking the best experience I have from other programming languages and diving into parts of elixir I need. (So, I will be skipping lots of language details.)
Last post, I got into testing and building executables. The minimum for building out confident code for a client.
This time, let’s get into mocking. Not just any mocking, but mocking out user input and output! Software may interact with a person… and simulating a person through mocking will reduce development time.
Mocking in ExUnit
I love RSpec’s mocking faciities and with the great experience I had with ExUnit, I expected fantastic mocking.
At the time of writing, there wasn’t any mocking built-in to ExUnit. :-/ Shame, the relationship started so well!
Mocking other functions is easy, but mocking input and output… even RSpec had a hard time with that! Let’s see how to mock out user input and output with elixir.
The main Elixir method to print to the console or to debug is using
This is the equivalent of Ruby’s
puts or Python’s
Where would programming be without this fundmental feedback tool??
The README explains how to mock
Well, when I started to run tests, I started to see:
Huh? I thought I was mocking out the function. Why is it printing to the screen?
Looks like the
:passthrough option is like RSpec’s
is useful when wanting to use the original method in the test.
In this case though, not printing to console would be desirable. I love to have continuous green dots.
To elimiinate output, remove
:passthrough as an option to mock:
Weird… so the
:passthrough option was not causing the outpu. So, how I do
mock out IO.puts without on screen output?
Looking at other examples on the README, there are functions associated like so:
Let’s try using a simple function to
Running everything again:
Nice, nothing extra on the output line. This took a little more work, but it makes sense.
This is a quick tour of mocking in elixir using
jjh42’s mocking library. Getting
out so there is no on-screen output during test runs.
This time, I covered
IO.puts. Next time, I will go in-depth with
and also add some functionality.