Phoenix framework is a nice Elixir web-framework with very useful features. Hound is a library to write browser-based integration tests in Elixir (and also automate browsers if you like).
A few people have had difficulties setting up Hound with Phoenix. So I dug into it and wrote down notes for anyone who’s trying it out.
We’ll call the project “hello_phoenix”.
$ mix phoenix.new hello_phoenix
mix.exs{:hound, "~> 0.7", only: :test}
and run mix deps.get to fetch dependencies.
mix.exs.This way you can start apps depending on Mix.env. You don’t want Hound to be running on development or production environments, because you don’t run tests there. Here’s the code that Phoenix generated for us in mix.exs.
def application do
[mod: {HelloPhoenix, []},
applications: [:phoenix, :phoenix_html, :cowboy, :logger,
:phoenix_ecto, :postgrex]]
end
We’ll change it to the following:
def application do
[mod: {HelloPhoenix, []},
applications: app_list(Mix.env) ]
end
def app_list do
[:phoenix, :phoenix_html, :cowboy, :logger, :phoenix_ecto, :postgrex]
end
def app_list(:test), do: [:hound | app_list]
def app_list(_), do: app_list
Like most webdrivers, Hound requires that your site be running on a port in order to access it like a user would do.
By default, Phoenix doesn’t start a server when running in test environment. In config/test.exs, you’ll find the below line. Change the server option to true.
config :hello_phoenix, HelloPhoenix.Endpoint,
http: [port: 4001],
server: true
As of v0.7, Hound assumes that your app is running on http://localhost:4001. In case you are running your test app on another host or port, you can change it in the configuration.
A webdriver server is a tool that can control browsers. You can choose between 3 webdrivers for now:
Install them from your software repository.
If you are on a Mac, all of these are available on HomeBrew. HomeBrew package names are
selenium-server-standalone,phantomjs&chromedriver.
Also ensure that the browser you prefer to test with is installed on your computer.
Hound defaults to
seleniumwebdriver &firefoxas a browser. If you choose anything else, ensure that you configure Hound appropriately.
Start up your webdriver (command depends on the webdriver you use).
Let’s write a sample test for the project in the file test/sample_test.exs.
defmodule HelloPhoenix.SampleTest do
use HelloPhoenix.ConnCase
# Import Hound helpers
use Hound.Helpers
# Start a Hound session
hound_session
test "GET /" do
navigate_to "/"
assert page_source =~ "Welcome to Phoenix"
end
end
That tests if the default Phoenix page welcomes you. You should be able to run the tests with mix test.
As of this writing, latest version of Hound is v0.7.2. The docs come with examples for each helper function. If you are stuck with something, I tweet as @HashNuke. Along with a lot of other people, I hangout on the #elixir-lang IRC channel on Freenode IRC and also on the Elixir mailing list.
Have fun ~!