15

I'm writing tests of some Elixir code that interacts with SSH. In my tests, I'd like to start an SSH server that I can run my code against. I'd prefer to store this code in it's own file in the test directory, and have it imported by various different tests.

I've not been able to get this to work too well though.

I've tried creating an test/ssh_server.ex file containing a SSHServer module, but when I add import SSHServer to my tests, I get:

(CompileError) test/end_to_end_test.exs:13: module SSHServer is not loaded and could not be found

Am I missing something? Is there some way to force mix test to import my test/ssh_server.ex file?

obmarg
  • 9,369
  • 36
  • 59

2 Answers2

17

I've currently got around this by manually loading the code from my test_helper.exs file:

Code.load_file("test/ssh_server.ex")
obmarg
  • 9,369
  • 36
  • 59
  • 13
    This is a good solution. I would name the file `.exs` too though, as it is never compiled. Another alternative is to tell Mix to compile everything in a special directory too, like test/support. Phoenix does this here: https://github.com/phoenixframework/phoenix/blob/db2f953f24973fab8aa2aab3bd8fc9c87a17adc8/installer/templates/new/mix.exs#L10 – José Valim Jun 04 '15 at 21:02
  • I'm using this for seeding before tests with `Code.load_file("priv/repo/seeds.exs")` in my test `setup` and it's working like a charm. –  Aug 18 '16 at 14:55
  • 3
    I would go with `Code.require_file` instead of load. This will ensure that the file is only loaded once. I would also agree on the use of the `.exs` extension. This is the way ecto does it: https://github.com/elixir-ecto/ecto/blob/master/test/ecto/test_helper.exs – Steven L. Sep 20 '16 at 13:51
2

Compile the module, then it will be available.

This can be done in either iex

iex > c "test/ssh_server.ex"

or with elixirc

elixirc "test/ssh_server.ex"

http://elixir-lang.org/getting-started/modules.html#compilation

Sasha
  • 2,227
  • 3
  • 23
  • 31