我正在尝试使用take_screenshot(((Hound(截取屏幕截图。我只需要在失败时捕获屏幕截图。
我已经尝试过尝试/救援,但是即使断言失败,救援块也始终执行。
try do
// some page elements action
assert visible_page_text(), "Hello World"
rescue
_ -> take_screenshot()
end
我也试过,
try do
// some page elements action
assert visible_page_text(), "Hello World"
catch
_ -> take_screenshot()
end
我想要, 如果断言失败,则只有这样它才应该截取屏幕截图。
只需稍作修改,您的代码即可工作:
try do
// some page elements action
assert visible_page_text() =~ "Hello World"
catch
error ->
take_screenshot()
raise error
end
或者把它变成一个宏:
# 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
并像这样称呼它:
assert_sof visible_page_text() =~ "Hello World"
更新:正如您提到的,这只会在执行断言时截取屏幕截图。不过,这是可以解决的。
这是一个宏,它将整个测试的内容包装在尝试/救援块中,并在任何错误时保存屏幕截图。作为奖励,它会在屏幕截图前面加上测试的名称。最大的缺点是你丢失了跟踪跟踪,所以很难查明失败的测试代码行。(用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
并像普通测试一样称其为:
test_sof "form with valid data" do
navigate_to "/form"
click({:id, "test"})
assert visible_page_text() =~ "test successful"
end
现在它应该适用于各种错误。