smahi
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.
Marked As Solved
RudManusachi
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
Also Liked
smahi
@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
RudManusachi
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 ![]()
Need to separate out the declaration and the usage.
Last Post!
RudManusachi
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 ![]()
Need to separate out the declaration and the usage.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









