问题
I am writing request specs and I am using poltergeist-1.0.2 and capybara-1.1.2. I have the following code:
login_as @user, 'Test1234!' click_on 'Virtual Terminal'
the login has flash message that shows to the user that he is successfully logged in. When I am using click_link, the spec fails because Capybara can't find element 'Virtual Terminal' but when I am using click_on everything passes. 'Virtual Terminal' is not a button, it is a link.
What is the difference between click_on and click_link.
回答1:
Click link uses a finder which specifies that you are looking for a link with the locator you provided and then does click on it as such:
def click_link(locator, options={})
find(:link, locator, options).click
end
Click on instead uses a finder that specifies that it should be a link or a button as:
def click_link_or_button(locator, options={})
find(:link_or_button, locator, options).click
end
alias_method :click_on, :click_link_or_button
Source: Capybara actions
This leads us in turn to the selectors :link and :link_or_button and that is defined as follows:
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
Source: Capubara selectors
The Xpath locators only differ in searching for link or link and button as shown in this sourcecode:
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
Source: Xpath html
As you can see the button locator actually finds a lot of different types which your link might fall under, if I had the html source code I could tell if it does or not.
来源:https://stackoverflow.com/questions/17563553/difference-between-click-on-and-click-link