如何测试元素是否显示在页面上 [英] How to test whether an element is displayed on the page
问题描述
以下代码检查元素是否显示以及元素是否存在运行特定操作,否则测试继续正常:
The following code checks whether an element is displayed and if the element is present runs a specific action, else the test continues normally:
require "selenium-webdriver"
require "rspec"
require 'rspec/expectations'
describe "Current Expense" do
before(:all) do
@driver = Selenium::WebDriver.for :firefox
@base_url = "http://the-internet.herokuapp.com/disappearing_elements"
@driver.manage.window.maximize
end
after(:all) do
@driver.quit
end
it "Check icon" do
@driver.get(@base_url)
if expect(@driver.find_element(:xpath, "//*[@href='/gallery/']").displayed?).to be_truthy
@driver.find_element(:xpath, "//*[@href='/gallery/']").click
sleep 2
puts "element appears"
else
puts "element NOT appears"
end
end
end
当元素存在时,会显示消息,但是当页面中不存在该元素时,会发生错误并且 else
块未执行。造成这个错误的原因是什么?
When the element is present, the message appears, but when the element is not present in the page, an error occurs and the else
block is not executed. What is causing this error?
推荐答案
我认为问题在于你正在使用 expect
当你应该只有条件 @ driver.find_element(:xpath,// * [@ href ='/ gallery /'))时显示?
。如果条件是 true
,您将看到预期的消息;同样,如果评估为 false
,您将看到元素未出现。
I think the problem is that you're using expect
when you should just have the conditional @driver.find_element(:xpath, "//*[@href='/gallery/']").displayed?
. If the conditional is true
you will see the expected message; likewise if it evaluates to false
you will see `"element NOT appears".
按照目前的构造,如果 find_element
方法返回 false
那么规范应该失败。请发布您所看到的错误或异常,以便我们确切知道。
As currently constructed, if the find_element
method returns false
then the spec should fail. Please post the error or exception you're seeing so that we can know for sure.
在旁注中,您现在拥有的内容很快就可以快速而肮脏测试页面是否正常运行,但您可能希望在测试文件中提供两种情况:一种是您知道图标将在页面上,另一种是不应该在页面上,然后测试每个的结果。例如:
On a side note, what you have right now is fine for a quick and dirty test of whether or not the page is functioning correctly, but you'll probably want to give two cases in your test file: one where you know the icon will be on the page, and one where it shouldn't be on the page, and then test the outcome for each. For example:
#Code omitted
it "has the icon when x is the case" do
# make x be the case
@driver.get(@base_url)
@driver.find_element(:xpath, "//*[@href='/gallery/']").displayed?
@driver.find_element(:xpath, "//*[@href='/gallery/']").click
sleep 2
# code that verifies that the element is on the page
end
it "doesn't have the icon when y is the case" do
# make y be the case
@driver.get(@base_url)
expect {
@driver.find_element(:xpath, "//*[@href='/gallery/']").displayed?
}.to be_false
end
#code omitted
这篇关于如何测试元素是否显示在页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!