click_on和click_link之间的区别?

时间:2013-07-10 06:09:56

标签: ruby-on-rails-3 capybara poltergeist

我正在编写请求规范,我使用的是poltergeist-1.0.2和capybara-1.1.2。我有以下代码:

    login_as @user, 'Test1234!'
    click_on 'Virtual Terminal'

登录有flash消息,向用户显示他已成功登录。当我使用click_link时,规范失败,因为Capybara找不到元素'Virtual Terminal'但是当我使用click_on时,一切都通过了。 “虚拟终端”不是按钮,而是一个链接。

click_on和click_link有什么区别。

1 个答案:

答案 0 :(得分:7)

点击链接使用查找程序,指定您正在查找与您提供的定位器的链接,然后单击它:

def click_link(locator, options={})
  find(:link, locator, options).click
end

点击而不是使用查找器指定它应该是链接或按钮:

def click_link_or_button(locator, options={})
  find(:link_or_button, locator, options).click
end
alias_method :click_on, :click_link_or_button

来源:Capybara actions

这引导我们转向选择器:link和:link_or_button,其定义如下:

Capybara.add_selector(:link_or_button) do
  label "link or button"
  xpath { |locator| XPath::HTML.link_or_button(locator) }
  filter(:disabled, :default => false) { |node, value| node.tag_name == "a" or not(value ^ node.disabled?) }
end

Capybara.add_selector(:link) do
  xpath { |locator| XPath::HTML.link(locator) }
  filter(:href) do |node, href|
    node.first(:xpath, XPath.axis(:self)[XPath.attr(:href).equals(href.to_s)])
  end
end

来源:Capubara selectors

Xpath定位器仅在搜索链接或链接和按钮时有所不同,如此源代码所示:

def link_or_button(locator)
  link(locator) + button(locator)
end

def link(locator)
  link = descendant(:a)[attr(:href)]
  link[attr(:id).equals(locator) | string.n.contains(locator) |  attr(:title).contains(locator) | descendant(:img)[attr(:alt).contains(locator)]]
end

def button(locator)
  button = descendant(:input)[attr(:type).one_of('submit', 'reset', 'image', 'button')][attr(:id).equals(locator) | attr(:value).contains(locator) | attr(:title).contains(locator)]
  button += descendant(:button)[attr(:id).equals(locator) | attr(:value).contains(locator) | string.n.contains(locator) | attr(:title).contains(locator)]
  button += descendant(:input)[attr(:type).equals('image')][attr(:alt).contains(locator)]
end

来源:Xpath html

正如您所看到的,按钮定位器实际上找到了许多不同类型的链接,如果我有html源代码,我可以判断它是否存在。