【问题标题】:How to perform drag and drop using page-object?如何使用页面对象执行拖放?
【发布时间】:2014-07-29 05:49:10
【问题描述】:
我需要对场景执行拖放操作,我怎样才能使用 Page-Object 来实现。
我需要单击一个元素(例如选项中的按钮)并将其放到文本区域中。我正在寻找解决方案,但找不到。请帮助解决此问题。谢谢
【问题讨论】:
-
页面对象gem目前没有拖放方法。项目的问题列表中有一个feature request。现在,您需要深入了解底层的 Selenium(或 Watir)元素。
标签:
ruby
selenium-webdriver
cucumber
pageobjects
page-object-gem
【解决方案2】:
使用 Selenium WebDriver:
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();
使用 watir-webdriver(仅适用于 FF(?)):
browser.div(:text=>"from_div").wd.drag_and_drop_on(browser.div(:text=>"to_div").wd)
使用 HTML5 拖放 Selenium WebDriver for Ruby
>
1) 将_and_drop_helper.js(https://gist.github.com/2362544) 拖放到您的测试/助手目录
2) 创建一个新方法:
def drag_and_drop(source,target)
js_filepath=File.dirname(__FILE__)+"/drag_and_drop_helper.js"
js_file= File.new(js_filepath,"r")
java_script=""
while (line=js_file.gets)
java_script+=line
end
js_file.close
@driver.execute_script(java_script+"$('#{source}').simulateDragDrop({ dropTarget: '#{target}'});")
rescue Exception => e
puts "ERROR :" + e.to_s
end
希望有帮助
【解决方案3】:
Ruby 的 PageObject 拖放
以下是使用带有 Cucumber、Ruby、PageObject Selenium WebDriver 框架的 PageObject 的“拖放”示例,使用 jqueryui.com/droppable/ 页面:
#
# Feature file with Gherkin scenario
#
Feature: Drag and Drop test
Scenario: Perform drag-and-drop test
Given I am on drag and drop test page
When I switch to frame with demo-frame class
And I drag left element and drop it on right element
#
# Step definitions file
#
Given("I am on drag and drop test page") do
visit(HomePage)
end
When("I switch to frame with demo-frame class") do
on(HomePage) do |page|
# call switch_to.frame only in one step definition,
# as it will give an error when try to call it in the next step definition
page.browser.switch_to.frame page.browser.find_element(:class, 'demo-frame')
end
end
And("I drag left element and drop it on right element") do
on(HomePage) do |page|
from_el = page.get_from_element
to_el = page.get_to_element
# elements has to be assigned directly from Selenium WebDriver,
# if assigned from the PageObject next line will give an error
page.browser.action.click_and_hold(from_el).perform
page.browser.action.move_to(to_el).perform
page.browser.action.release.perform
sleep 10 # just to see the drag and drop result
end
end
#
# Page file
#
class HomePage
include PageObject
page_url "https://jqueryui.com/droppable/"
def get_from_element
self.browser.find_element(:id, "draggable")
end
def get_to_element
self.browser.find_element(:id, "droppable")
end
end
【解决方案4】:
从 Justin 提出的尚未实现的评论开始,然后您可以在以下位置对 Page-object gem 进行猴子修补:
module PageObject
module Elements
class Element
def drag_and_drop_on(other)
element.drag_and_drop_on other.element
end
end
end
end
这至少会在 watir-webdriver gem 中执行 drag_and_drop_on 方法,而不会出现弃用警告。