Phoenix/Elixir 测试视图助手

Phoenix/Elixir test view helpers

我创建了一个助手来在将数字呈现给视图之前进行一些计算:

defmodule FourtyWeb.CalculationHelpers do

  use Phoenix.HTML

  def value_in_euro(amount_in_cents) when is_binary(amount_in_cents) do
    cond do
      # some code
    end
  end

end

这东西有用。我现在正在尝试测试它:

defmodule FourtyWeb.CalculationHelpersTest do
  use FourtyWeb.ConnCase, async: true
  
  import Phoenix.View

  @amount_in_cents 1020

  describe "it calculates the correct value in euro" do
     test "with correct data" do
       assert 10.20 == value_in_euro(@amount_in_cents)
     end
   end

end

如果我 运行 混合测试我得到以下错误,我不知道为什么:

== Compilation error in file test/app_web/views/calculation_helpers_test.exs ==
** (CompileError) test/fourty_web/views/calculation_helpers_test.exs:11: undefined function value_in_euro/1

谁能详细说说?

您正在测试文件中调用 value_in_euro/1,但该函数未定义。要解决这个问题,请从定义它的模块中调用它,如下所示:

assert 10.20 == FourtyWeb.CalculationHelpers.value_in_euro(@amount_in_cents)

或导入模块,以便您可以将 FourtyWeb.CalculationHelpers 中的所有函数作为本地函数引用:

import FourtyWeb.CalculationHelpers
...
   assert 10.20 == value_in_euro(@amount_in_cents) # now this works

(顺便说一句,如果没有看到你的其余代码,这个测试不会失败,因为 @amount_in_cents 不是二进制文件吗?)