Elixir Enum.each在通过ExUnit测试循环时丢失变量
运行以下代码时,我收到警告:Elixir Enum.each在通过ExUnit测试循环时丢失变量,elixir,ex-unit,Elixir,Ex Unit,运行以下代码时,我收到警告: warning: variable "char" does not exist and is being expanded to "char()", please use parentheses to remove the ambiguity or change the variable name test/my_module_test.exs:7 然后是失败的测试: == Compilation error in file test/my_module_te
warning: variable "char" does not exist and is being expanded to "char()", please use parentheses to remove the ambiguity or change the variable name
test/my_module_test.exs:7
然后是失败的测试:
== Compilation error in file test/my_module_test.exs ==
** (CompileError) test/my_module_test.exs:7: undefined function char/0
(stdlib) lists.erl:1338: :lists.foreach/2
(stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
(elixir) lib/code.ex:767: Code.require_file/2
(elixir) lib/kernel/parallel_compiler.ex:209: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6
defmodule MyModule do
使用ExUnit.Case,async:true
doctestmymodule
Enum.each~w(a b c),fn字符->
测试“涉及#{char}的测试”do
断言字符==字符
终止
终止
终止
似乎在Enum.each
块中,char
的值是为行test“…{char}”do
定义的,但在断言中变得未定义
为什么会发生这种情况?这为您定义了一个函数
每次在Elixir中定义新函数时,它都会启动一个新的作用域。这意味着在函数外部定义的任何变量在函数内部都不可用。例如,您不能这样做:
foo = 1
def some_function() do
foo
end
有一些方法可以绕过此机制。一种是使用unquote
注入一些值作为AST。但是,在这种情况下,最简单的方法是将该值放入模块属性中,以便您可以在函数中读取该值:
@foo 1
def some_function() do
@foo
end
无论您是否希望使用不同的输入运行相同的测试(尽管这可能意味着测试结构设计存在问题),您都可以使用来设置测试上下文,或者使用文档中所示的模块属性 模块属性定义后,在模块中的任何位置都可以明显看到。是为您定义函数的 每次在Elixir中定义新函数时,它都会启动一个新的作用域。这意味着在函数外部定义的任何变量在函数内部都不可用。例如,您不能这样做:
foo = 1
def some_function() do
foo
end
有一些方法可以绕过此机制。一种是使用unquote
注入一些值作为AST。但是,在这种情况下,最简单的方法是将该值放入模块属性中,以便您可以在函数中读取该值:
@foo 1
def some_function() do
@foo
end
无论您是否希望使用不同的输入运行相同的测试(尽管这可能意味着测试结构设计存在问题),您都可以使用来设置测试上下文,或者使用文档中所示的模块属性 定义模块属性后,模块属性在模块中的任何位置都明显可见