How write test for an Elixir script file (Mix.install)

Hi,
I would like to know how to write test for an Elixir script created using Mix.install, let say I have script.exs then what is the best way to write test for it?

Thank you in advance.

4 Likes

not sure if this is the best way, but it should work =)

script.exs

defmodule Foo do
  def bar, do: :baz
end

In the same dir put script_test.exs

Code.require_file("script.exs")

ExUnit.start()

defmodule FooTest do
  use ExUnit.Case

  test "bar/0 does :baz" do
    assert :baz == Foo.bar()
  end
end

and run the test with

elixir script_test.exs
4 Likes

@RudManusachi
It work like charm, thank you so much.
The following is a working example.

# demo.exs
Mix.install([
  {:bunt, "~> 0.2.0"}
])

defmodule Demo do
  def hello(name \\ "John") do
    ["Hello, ", :green, :bright, name]
    |> Bunt.ANSI.format
    |> IO.puts
  end
end

Demo.hello("Smahi")
# demo_test.exs
Code.require_file("demo.exs")

ExUnit.start()

defmodule DemoTest do
  use ExUnit.Case
  import ExUnit.CaptureIO

  test "hello/1" do
   output = capture_io(fn -> Demo.hello("Jahn") end)
   assert output == "Hello, \e[32m\e[1mJahn\e[0m\n"
  end
end
7 Likes

One important thing to keep in mind!

When we run Code.require_file/1 it compiles (executes) the file. So if we do some side effects, external service calls etc… those will be run each time we run tests :slightly_smiling_face:
Need to separate out the declaration and the usage.

5 Likes