2
votes

I'm a newbie to Erlang just having gone through some tutorials on Erlang. Coming from TDD back-ground I thought I should follow some TDD principles in Erlang. I have organized my code as below

root
|- tests
|   |- name_builder_tests.erl
|- src
|   |- name_builder.erl

I start Erlang shell in root directory. But I cannot compile my erl files from there so I have to switch to tests or src directories every time I make a change to one of those files and I need to compile them.

Is there any way I can tell shell to look for module in all the sub-directories when compiling modules or executing functions from particular modules? What I'm trying to ask is, if my shell is at root directory can I successfully execute following

c(name_builder).
c(name_builder_tests).
3

3 Answers

3
votes

Let organize code like this.

root
|- test
|   |- name_builder_tests.erl
|- src
|   |- name_builder.erl
|- rebar
|- rebar.config

Than run './rebar compile eunit'. Rebar script and docs you can find here https://github.com/basho/rebar/wiki

1
votes

One of the approaches when doing unit testing, is to place the tests within the same module as the production code:

-module(my_code).
-export([run/0]).

run() -> ok.

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").

run_test() ->
    ?assertEqual(ok, run()).

-endif.

That way you have the tests close to you. Regarding the availability of the code, you should run the erlang shell using the "-pa" parameter and specify the location of your code:

erl -pa src/

that's because you're compiling by default will put the beam files to the same folder as the sources. But I would recommend using something like rebar, as it will make your life easier.

HTH, Alin

1
votes

You can do this using an Emakefile as well to tell the compiler where to look for source files.

Create a file named Emakefile in the root dir with following contents

{'src/*', [debug_info,
   {i, "src"},
   {i, "include"},     
   {outdir, "ebin"}]}.
{'test/*', [debug_info,
    {i, "src"},
    {i, "include"},
    {i, "test"},        
    {outdir, "ebin"}]}.

Now compile all modules using erl -make which will put all .beam files inside the ebin/ dir.

Then start the shell by running the command erl -pa ebin/ which will add the ebin dir to sys path

PS 1: I am pretty much an erlang newbie too and I learnt this approach from Learn You Some Erlang, more precisely from this lesson

PS 2: If you are working on an app that is planned to be more complicated than this, I would recommend you to check rebar