Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test an image alt value using capybara?

I'm trying to define a step to test the value of alt text of an image using Capybara and CSS selectors.

I wrote one for input values based on the readme examples:

Then /^I should see a value of "([^\"]*)" within the "([^\"]*)" input$/ do |input_value, input_id|
  element_value = locate("input##{input_id}").value
  element_value.should == input_value
end

But I can't figure this one out...something like:

Then /^I should see the alttext "([^\"]*)"$/ do | alt_text |
  element_value = locate("img[alt]").value
end

Anyone know how I can locate the alt text value?

like image 887
kinet Avatar asked May 14 '10 22:05

kinet


3 Answers

Capybara uses xpath by default, so unless you changed that setting, that could be part of your problem. (You could use locate(:css, "img[alt]")).

I would write the tests using xpath to look something like this:

Then /^I should see the alt text "([^\"]*)"$/ do | alt_text |
    page.should have_xpath("//img[@alt=#{alt_text}]")
end

Then /^I should see a value of "([^\"])" within the "([^\"])" input$/ do |input_value, input_id|
    page.should have_xpath("//input[@id=#{input_id} and text()=#{input_value}]
end
like image 88
Eliza Brock Marcum Avatar answered Nov 20 '22 15:11

Eliza Brock Marcum


I believe the value method returns the value of input fields and cannot be used to test an attribute.

Something like this might work instead:

page.should have_css("img[alt=the_alt_text_you_are_expecting]")
like image 43
triskweline Avatar answered Nov 20 '22 16:11

triskweline


another variation on the theme:

Then /^I should see the image alt "([^"]*)"$/ do |alt_text|
  page.should have_css('img', :alt => alt_text)
end
like image 7
Josh Crews Avatar answered Nov 20 '22 15:11

Josh Crews