【问题标题】:module ConnCase is not loaded and could not be found模块 ConnCase 未加载且找不到
【发布时间】:2019-01-18 04:09:09
【问题描述】:

无法找出这个错误。

我有这个文件:

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

这个配置在mix.ex

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

我对@9​​87654325@进行了测试

defmodule ProjectWeb.PageControllerTest do
  use ProjectWeb.ConnCase

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

仍然在运行mix test 时收到:

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

【问题讨论】:

标签: testing phoenix-framework elixir-mix


【解决方案1】:

编辑:我留下了非理想解决方案,只是为了讨论如何编辑路径,以及一个懒惰的、大部分可行的解决方案。然而,惯用的做法似乎是手动设置 env,而不是破坏 dev ENV 以使其正确运行您的测试。您应该只使用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

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

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

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2020-07-18
    • 2018-10-30
    • 2021-02-14
    相关资源
    最近更新 更多