From f63dcd93dda1e65c93e4816b212de9bc25b731c2 Mon Sep 17 00:00:00 2001 From: Chris Keathley Date: Sat, 23 Apr 2016 16:29:40 -0400 Subject: [PATCH] Raise Exception is there is no base_url set --- lib/wallaby/exceptions.ex | 18 ++++++++++++++++++ lib/wallaby/session.ex | 23 +++++++++++++++++++---- test/wallaby/session_test.exs | 15 +++++++++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/lib/wallaby/exceptions.ex b/lib/wallaby/exceptions.ex index 45238b08..a727969b 100644 --- a/lib/wallaby/exceptions.ex +++ b/lib/wallaby/exceptions.ex @@ -13,3 +13,21 @@ end defmodule Wallaby.BadMetadata do defexception [:message] end + +defmodule Wallaby.NoBaseUrl do + defexception [:message] + + def exception(relative_path) do + msg = """ + You called visit with #{relative_path}, but did not set a base_url. + Set this in config/test.exs or in test/test_helper.exs: + + Application.put_env(:wallaby, :base_url, "http://localhost:4001") + + If using Phoenix, you can use the url from your endpoint: + + Application.put_env(:wallaby, :base_url, YourApplication.Endpoint.url) + """ + %__MODULE__{message: msg} + end +end diff --git a/lib/wallaby/session.ex b/lib/wallaby/session.ex index 5b19bf19..ef5e0910 100644 --- a/lib/wallaby/session.ex +++ b/lib/wallaby/session.ex @@ -52,12 +52,23 @@ defmodule Wallaby.Session do @doc """ Changes the current page to the provided route. - Routes are relative to any base url provided. + Relative paths are appended to the provided base_url. + Absolute paths do not use the base_url. """ @spec visit(t, String.t) :: t def visit(session, path) do - Driver.visit(session, request_url(path)) + uri = URI.parse(path) + + cond do + uri.host == nil && String.length(base_url) == 0 -> + raise Wallaby.NoBaseUrl, path + uri.host -> + Driver.visit(session, path) + true -> + Driver.visit(session, request_url(path)) + end + session end @@ -142,7 +153,11 @@ defmodule Wallaby.Session do session end - defp request_url(url) do - (Application.get_env(:wallaby, :base_url) || "") <> url + def request_url(path) do + base_url <> path + end + + defp base_url do + Application.get_env(:wallaby, :base_url) || "" end end diff --git a/test/wallaby/session_test.exs b/test/wallaby/session_test.exs index 627a8282..1df8d9cd 100644 --- a/test/wallaby/session_test.exs +++ b/test/wallaby/session_test.exs @@ -37,6 +37,21 @@ defmodule Wallaby.SessionTest do Application.put_env(:wallaby, :base_url, nil) end + test "visit/2 with a relative url and no base url raises exception", %{session: session, server: server} do + assert_raise(Wallaby.NoBaseUrl, fn -> + Application.put_env(:wallaby, :base_url, nil) + session + |> visit("/page_1.html") + end) + end + + test "visit/2 with an absolute path does not use the base url", %{session: session, server: server} do + session + |> visit(server.base_url <> "/page_1.html") + + assert has_css?(session, "#visible") + end + test "taking screenshots", %{session: session, server: server} do node = session