模块 ConnCase 未加载且无法找到

lap*_*ira 3 testing elixir-mix phoenix-framework

无法弄清楚这个错误。

我有这个文件:

test/support/conn_case.ex

defmodule ProjectWeb.ConnCase do
  @moduledoc """
  This module defines the test case to be used by
  tests that require setting up a connection.

  Such tests rely on `Phoenix.ConnTest` and also
  import other functionality to make it easier
  to build common datastructures and query the data layer.

  Finally, if the test case interacts with the database,
  it cannot be async. For this reason, every test runs
  inside a transaction which is reset at the beginning
  of the test unless the test case is marked as async.
  """

  use ExUnit.CaseTemplate

  using do
    quote do
      # Import conveniences for testing with connections
      use Phoenix.ConnTest
      import ProjectWeb.Router.Helpers

      # The default endpoint for testing
      @endpoint ProjectWeb.Endpoint
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

并且这个配置mix.ex

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "test/support"]
  defp elixirc_paths(_),     do: ["lib"]
Run Code Online (Sandbox Code Playgroud)

我有一个测试test/controllers/page_controller_test.exs

defmodule ProjectWeb.PageControllerTest do
  use ProjectWeb.ConnCase

  test "GET /", %{conn: conn} do
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "OK"
  end
end
Run Code Online (Sandbox Code Playgroud)

运行时mix test我仍然收到:

** (CompileError) test/controllers/page_controller_test.exs:2: 模块 ProjectWeb.ConnCase 未加载且无法找到

Dwi*_*ght 6

编辑:我在下面留下了非理想的解决方案,只是为了讨论如何编辑路径,以及一个懒惰的、大部分可行的解决方案。然而,惯用的做法似乎是手动设置环境,而不是破坏开发环境以使其正确运行测试。您应该只使用它MIX_ENV=test mix test来实现您的目标,因为在大多数情况下修改开发环境是不可取的。

对于遇到此问题的其他人,您可能遇到了与我相同的问题 ->MIX_ENV默认设置为 dev。如果是这种情况,您可以通过运行轻松测试它MIX_ENV=test mix test,这将为一次调用设置环境。如果它有效,您将有一个解决方法,以及我在下面描述的更永久的解决方法。

这条线下面确实不推荐 - 留下来讨论如何加载这些模块以及那些不关心开发版本是否被测试模块覆盖的人

我目前修复它的方法是将其修改mix.exs为如下所示:

defmodule MyApp.MixProject do
use Mix.Project

  def project do
    [
      ...
      elixirc_paths: elixirc_paths(Mix.env()),
      ...
    ]
  end

  # Configuration for the OTP application.
  #
  # Type `mix help compile.app` for more information.
  def application do
    [
      mod: {MyApp.Application, []},
      extra_applications: [:logger, :runtime_tools]
    ]
  end

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "test/support"]
  defp elixirc_paths(:dev), do: ["lib", "test/support"]
  defp elixirc_paths(_), do: ["lib"]

  # Specifies your project dependencies.
  #
  # Type `mix help deps` for examples and options.
  defp deps do
    [
      ...
    ]
  end
end
Run Code Online (Sandbox Code Playgroud)

这里与默认值不同的重要一点是块中mix.exs的定义(这应该已经匹配,但如果不匹配,它应该),以及添加行elixirrc_pathsdef projectdefp elixirc_paths(:dev), do: ["lib", "test/support"]

这可能不完全是惯用的,但是当使用开发混合环境时,它将确保您的测试也被编译,并且仍然允许您单独定义开发和测试环境。