Reputation: 1167
I'm usisng cucmber to test a php app and it's working quite well actually.
I have a cucmber feature that uses the following step to check for the presence of a link in a page:
Then /^I should see a link that contains "(.+)"$/ do |link|
assert !!(response_body =~
/<a ([\w\.]*="[\w\.]*" )*href="(http:\/\/)?([\w\.\/]*)?(#{link})/m), response_body
end
Now, this works but it's butt ugly and complicated.
Originally I tried using the xpath thing:
response_body.should have_xpath("//a[@href=\"#{link}\"]")
But then if I check for a link to 'blah.com' then it won't match 'http://blah.com" - which kind of defeats the whole purpose of the test. Hence the reason I switched to regex.
So is there a simpler way to write the test which doesn't rely on complicated regular expressions?
Cheers.
EDIT: After lots of hair-pulling... I did find a less messy way to find images on my page:
response_body.should include(image)
Where the image string is set to something like 'myimage.png' - of course, this will break if the actual text 'myimage.png' is on the page and not the image. There must be a better way. I was considering Hpricot to see if I can parse the html and pull out the attribute I want to test, then test that with a regex but that all seems so... bloated.
Upvotes: 2
Views: 509
Reputation: 1167
Then /^I should see the image "(.+)"$/ do |image|
response_body.should have_selector("img[src*='#{image}']")
end
Then /^I should see a link that contains "(.+)"$/ do |link|
response_body.should have_selector("a[href*='#{link}']")
end
Thanks AlistairH - your advice worked! :)
I still don't undestand why it's searching html with a css selector syntax but maybe that was just a design choice they guy who wrote it took because it looked easier than regex...? I don't know.
Upvotes: 0
Reputation: 3229
Something like this should work:
response_body.should have_css("a[href*='#{link}']")
See this for details: http://www.w3.org/TR/css3-selectors/#attribute-substrings
EDIT: Looks like the equivalent method for webrat is have_selector, so:
response_body.should have_selector("a[href*='#{link}']")
Upvotes: 1