page.has_content?()vs. expect(page).to have_content(page.has_content?() vs. expect(page).to have_content)

嗨,来自StackOverflow的人,

我正在接管某人的工作,而我的前任使用Cucumber&Capybara&Selenium创建了一个测试集。 我对这个很熟悉,但我对他在页面上查找文本的方式有疑问。

他的实施:

期望(页面).to have_content(文本)

我的实施:

page.has_content?(文本)

我注意到的是,第一个实现经常失败,因为自动化对于网站加载其页面而言“太快”。 后者似乎是一个更强大的实现,也许是因为它的简单性?

有人可以告诉我是否有对或错,或者这两者是否有根本的不同。 因为我一直在试图搜索网页,但还没有真正找到一个坚实的结论..

提前致谢!

Hi people from StackOverflow,

I'm taking over someone's work, and my predecessor created a testset using Cucumber&Capybara&Selenium. I'm familiar with the lot, but I've got a question concerning his way of finding text on a page.

His implementation:

expect(page).to have_content(text)

My implementation:

page.has_content?(text)

What I've noticed is that the first implementation often fails because the automation is 'too quick' for the website to load its page. The latter seems a more robust implementation, perhaps because of its simplicity?

Can someone tell me if there's a right or a wrong, or whether these two are fundamentally different. Because I've been trying to search the web but have not really found a solid conclusion..

Thanks in advance!

最满意答案

如果期望失败, have_content会引发异常,并且在大多数测试套件中应该比has_content更频繁地使用它。 has_content? 基本上只是一个包含has_content的包装器,它捕获异常并返回true或false,并用于条件

if page.has_content?(...) # click something else # click something else end

您的前任正在正确使用Capybara,因为如果您正在测试以确保页面具有特定内容,则应使用have_content 。 has_content? 将永远不会失败的测试(只是默默地返回false并继续)。 如果你的have_content断言因为站点太慢而失败,你可能需要增加Capybara.default_max_wait_time (或弄清楚为什么页面加载时间太长)

have_content raises an exception when it's expectation fails and should be used much more often in most test suites than has_content?. has_content? is basically just a wrapper around have_content that catches the exception and returns true or false, and is for use with conditionals

if page.has_content?(...) # click something else # click something else end

Your predecessor is using Capybara correctly since if you are testing to make sure a page has specific content you should be using have_content. has_content? will never fail the test (just silently return false and continue on). If your have_content assertions are failing because the site is too slow you probably need to increase Capybara.default_max_wait_time (or figure out why page load times are so long)

更多推荐