简体   繁体   中英

Phoenix/Elixir test view helpers

I have created a helper to do some calculations before a number is presented to the view:

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

This thing works. I am now trying to test it:

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

If I run mix test I get the following error and I can't figure out why:

== 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

Can anyone elaborate?

You are calling value_in_euro/1 in your test file but that function is undefined. To fix that, call it from the module where it is defined, like this:

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

or import the module so you can reference all functions in FourtyWeb.CalculationHelpers as local functions:

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

(BTW, without seeing the rest of your code, won't this test fail since @amount_in_cents is not a binary?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM