How do I test an image alt value using capybara?
Asked Answered
D

4

8

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?

Decorous answered 14/5, 2010 at 22:48 Comment(0)
H
13

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
Hindustani answered 17/5, 2010 at 16:9 Comment(1)
Thanks Eliza - I did change the default setting as we mostly use the CSS selectorsDecorous
S
11

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]")
Shinny answered 15/5, 2010 at 6:27 Comment(0)
H
6

another variation on the theme:

Then /^I should see the image alt "([^"]*)"$/ do |alt_text|
  page.should have_css('img', :alt => alt_text)
end
Hoop answered 11/6, 2011 at 1:55 Comment(2)
Very simple, but this did not work for me. (RSpec 3.0 + Capybara 2.4)Orazio
This would return invalid keys :alt now. I am not sure if this ever worked?Canara
T
0

I'm not sure about the method you're using to find the image but this works for me:

expect(find_by_id("image-1")[:alt]).to have_content('tree')

Once you have the element the [:"tag"] will give you the value.

$thing = find_by_id("image-1")[:alt] 

will set thing to the value if you have more complex tests.

Tinaret answered 14/6, 2013 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.