Testing 如何在Elixir中的doctest中执行字符串插值?
我一直在尝试Elixir的博士课程,在我尝试做字符串插值之前,效果一直不错 代码如下:Testing 如何在Elixir中的doctest中执行字符串插值?,testing,elixir,Testing,Elixir,我一直在尝试Elixir的博士课程,在我尝试做字符串插值之前,效果一直不错 代码如下: @doc""" Decodes the user resource from the sub claim in the received token for authentication. ## Examples iex> attrs = %{email: "test@example.com", password: "password", password_confirmat
@doc"""
Decodes the user resource from the sub claim in the received token for authentication.
## Examples
iex> attrs = %{email: "test@example.com", password: "password", password_confirmation: "password"}
iex> {:ok, user} = Accounts.create_user(attrs)
iex> resource_from_claims(%{"sub" => "User:#{user.id}"})
{:ok, %User{}}
"""
def resource_from_claims(%{"sub" => "User:" <> id}) do
resource = Accounts.get_user(id)
case resource do
nil -> {:error, :no_result}
_ -> {:ok, resource}
end
end
@doc”“”
从接收到的令牌中的子声明解码用户资源以进行身份验证。
##例子
iex>attrs=%{电子邮件:test@example.com,密码:“password”,密码确认:“password”}
iex>{:ok,user}=Accounts.create_user(attrs)
iex>resource_from_声明(%{“sub”=>“User:#{User.id}})
{:确定,%User{}
"""
def resource_from_声明(%%{“sub”=>“User:”id})do
资源=帐户。获取用户(id)
案例资源
nil->{:error,:no_result}
_->{:好的,资源}
结束
结束
我在运行混合测试时出现此错误:
变量“user”不存在,正在扩展为“user()”,请使用括号消除歧义或更改变量名称
我可以确认user
变量确实存在,并且可以处理几乎所有其他内容,除非我尝试将其放入字符串插值中
有没有其他方法可以在doctests中进行字符串插值
Edit:我似乎遇到了这个错误,因为@doc
中的字符串插值部分实际上在doctest的范围之外运行,而不是作为模块本身的一部分运行。我将看看是否有其他方法可以在doctest的上下文中执行字符串插值。发布编辑后(见上文),我发现解决方案是使用~s
调用@doc
字符串:
@doc ~S"""
Decodes the user resource from the sub claim in the received token for authentication.
## Examples
iex> attrs = %{email: "test@example.com", password: "password", password_confirmation: "password"}
iex> {:ok, user} = Accounts.create_user(attrs)
iex> resource_from_claims(%{"sub" => "User:#{user.id}"})
{:ok, %User{}}
"""
这样,模块将忽略@doc
块中写入的任何字符串插值,这将允许doctest执行字符串插值
参考资料:这与doctest本身无关;与之不同的是,sigil本身阻止插值。@mudasobwa怎么会这样?如果没有
~S
,doctest将失败,因为模块已经执行了插值,这将导致编译错误。我不认为~s
能解决我的问题,因为我需要doctest来代替插值。我的意思是,你需要防止整个注释字符串被插值。不管它是注释字符串还是代码库中某个地方的普通字符串,这都无关紧要~S
与~S
不同,与普通的“
不同,它阻止了这种插值。就是这样。