1

我正在尝试使用 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

我想,如果断言失败,那么它应该截图。

4

1 回答 1

0

稍作修改,您的代码就可以工作:

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"

更新:正如您所提到的,这只会在进行断言时截取屏幕截图。不过这可以解决。

这是一个宏,它将整个测试的内容包装在 try/rescue 块中,并保存任何错误的屏幕截图。作为奖励,它会在屏幕截图前面加上测试名称。最大的缺点是您丢失了 stracktrace,因此更难查明测试代码的失败行。(用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

现在它应该适用于各种错误。

于 2019-09-27T17:40:59.407 回答