[英]How to take a screenshot on failure using hound/elixir
I am trying to take a screenshot using take_screenshot() (Hound).我正在尝试使用 take_screenshot() (Hound) 截取屏幕截图。 I just need to capture the screenshot on failure.我只需要捕获失败的屏幕截图。
I have tried try/rescue however rescue block always executed even though assertion fails.我尝试过尝试/救援,但是即使断言失败,救援块也总是执行。
try do
// some page elements action
assert visible_page_text(), "Hello World"
rescue
_ -> take_screenshot()
end
I also tried,我也试过,
try do
// some page elements action
assert visible_page_text(), "Hello World"
catch
_ -> take_screenshot()
end
I want, if assertion fails, only then it should take screenshot.我想,如果断言失败,那么它应该截图。
With a small modification your code works:稍作修改,您的代码就可以工作:
try do
// some page elements action
assert visible_page_text() =~ "Hello World"
catch
error ->
take_screenshot()
raise error
end
Or turn it into a macro:或者把它变成一个宏:
# assert screenshot on failure
defmacro assert_sof(assertion) do
quote do
try do
assert unquote(assertion)
rescue
error ->
take_screenshot()
raise error
end
end
end
And call it like this:并这样称呼它:
assert_sof visible_page_text() =~ "Hello World"
Update : As you mentioned, this will only take screenshots when doing an assertion.更新:正如您所提到的,这只会在进行断言时截取屏幕截图。 That can be fixed though.不过这可以解决。
Here is a macro that will wrap the contents of a whole test in a try/rescue block and save a screenshot on any error.这是一个宏,它将整个测试的内容包装在 try/rescue 块中,并保存任何错误的屏幕截图。 As a bonus, it prefixes the screenshot with the name of the test.作为奖励,它会在屏幕截图前面加上测试名称。
The big drawback is that you lose the stracktrace, so it's harder to pinpoint the failing line of test code.
最大的缺点是您丢失了 stracktrace,因此更难查明测试代码的失败行。
(solved with catch
instead of rescue
) Put the macro in support/conn_case.ex
or somewhere else if you prefer: (用catch
而不是rescue
解决)把宏放在support/conn_case.ex
或者你喜欢的其他地方:
def MyAppWeb.ConnCase
# ...
# Test and take screenshot on failure. Only works for hound tests.
defmacro test_sof(message, var \\ quote do _ end, contents) do
prefix = String.replace(message, ~r/\W+/, "-")
filename = Hound.Utils.temp_file_path(prefix, "png")
quote do
test unquote(message), unquote(var) do
try do
unquote(contents)
catch
error ->
take_screenshot(unquote(filename))
raise error
end
end
end
end
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
import MyAppWeb.ConnCase, only: [test_sof: 2, test_sof: 3] # <- Add this line
# ...
end
end
# ...
end
And call it like a normal test:并将其称为正常测试:
test_sof "form with valid data" do
navigate_to "/form"
click({:id, "test"})
assert visible_page_text() =~ "test successful"
end
Now it should work for all kinds of errors.现在它应该适用于各种错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.