Determining if a link exists w/ Cucumber/Capybara
I want to verify that a link with a specific href exists on a page. I am currently doing I should see "/some-link-here" but that seems to fail. How can I make sure开发者_如何转开发 that link exists without having to do click + I should be on "/some-link-here" page?
You will need to add custom step
Then /^"([^\"]*)" should link to "([^\"]*)"(?: within "([^\"]*)")$/ do |link_text,
page_name, container|
with_scope(container) do
URI.parse(page.find_link(link_text)['href']).path.should == path_to(page_name)
end
end
You can use the step like Then "User Login" should link to "the user_login page"
, user_login is the name of your route
I used jatin's answer, but have a separate scoping step:
When /^(.*) within ([^:]+)$/ do |step, parent|
with_scope(parent) { When step }
end
Then /^"([^\"]*)" should link to "([^\"]*)"$/ do |link_text, page_name|
URI.parse(page.find_link(link_text)['href']).path.should == path_to(page_name)
end
Then I have this in my test:
step '"my foods" should link to "food_histories" within ".tabs"'
And this in my paths:
# note: lots not shown
def path_to(page_name)
case page_name
when /^food_histories$/
food_histories_path
end
end
This is what I have done myself, quite simple but it does mean you are hardcoding your url which to be honest is not ideal as it makes your test very brittle. Especially if you are using 3rd party URL's!
But if you are using a url that you manage and are happy to maintain this test then go for it.
Then /^the link is "(.*?)"$/ do |arg1|
page.should have_xpath("//a[@href='" + arg1 + "'][@target='_blank']")
end
I first landed here, when looking for a solution and thought I would give an updated answer. It depends what your capybara syntax is, but using the matcher has_link?
you could write for href = /some-link-here
and link_text "Click Me"
expect(page).to have_link("Click Me", href: '/some-link-here')
精彩评论