如何测试元素是否显示在页面上

时间:2014-12-24 16:12:11

标签: ruby if-statement rspec selenium-webdriver

以下代码检查是否显示元素以及元素是否存在运行特定操作,否则测试会继续正常进行:

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块。导致此错误的原因是什么?

2 个答案:

答案 0 :(得分:1)

我认为问题在于,当您应该拥有条件expect时,您正在使用@driver.find_element(:xpath, "//*[@href='/gallery/']").displayed?。如果条件为true,您将看到预期的消息;同样,如果评估为false,您将看到“元素未出现”。

按照目前的构造,如果find_element方法返回false,则规范应该失败。请发布您所看到的错误或异常,以便我们确切知道。

在旁注中,您现在所拥有的内容适用于对页面是否正常运行进行快速而肮脏的测试,但您可能希望在测试文件中提供两种情况:一种是您知道的图标将在页面上,而不应该在页面上,然后测试每个图标的结果。例如:

#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

答案 1 :(得分:0)

expect是测试失败的原因。找到解决方案的以下片段。干杯!

it "has the icon when x is the case" do
  @driver.get(@base_url)
  begin
    @driver.find_element(:xpath, "//*[@href='/gallery/']")
    @driver.find_element(:xpath, "//*[@href='/gallery/']").click
  rescue Selenium::WebDriver::Error::NoSuchElementError
    raise 'The Element ' + what + ' is not available'
  end
end

it "doesn't have the icon when y is the case" do
  @driver.get(@base_url)
  begin
    @driver.find_element(:xpath, "//*[@href='/gallery/']")
    raise 'The Element ' + what + ' is available'
  rescue Selenium::WebDriver::Error::NoSuchElementError
    expect(true).to be_truthy
  end
end