【问题标题】:How to take a screenshot on failure using hound/elixir如何使用 hound/elixir 截取失败的屏幕截图
【发布时间】:2019-09-27 09:20:22
【问题描述】:

我正在尝试使用 take_screenshot() (Hound) 截取屏幕截图。我只需要捕获失败的屏幕截图。

我尝试过 try/rescue,但是即使断言失败,救援块也总是执行。

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

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

【问题讨论】:

    标签: elixir hound


    【解决方案1】:

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

    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
    

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

    【讨论】:

    • 效果很好。但是,如果测试失败(除了断言之外的其他步骤,su as element not found),它不会捕获快照。
    • 好吧,可惜了。虽然如果我在不存在时测试assert_sof element_displayed?({:class, "foobar"}) 之类的东西,它会按预期工作。它需要一个屏幕截图。
    • 我已经更新了答案并添加了一个适用于整个测试的新宏,而不仅仅是断言。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多