2010-05-14 28 views
7

我試圖定義一個步驟來測試使用水豚和CSS選擇器的圖像的ALT文本的值。如何使用水豚測試圖像alt值?

我寫了一個用於輸入值基於自述的例子:

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 

但我不能離開圖這個...是這樣的:

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

任何人都知道我可以找到替代文字值?

回答

12

水豚默認使用XPath的,所以,除非您更改了設置,這可能是你的問題的一部分。 (您可以使用locate(:css, "img[alt]"))。

我會使用XPath看起來像這樣寫測試:

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 
+0

謝謝Eliza - 我確實改變了默認設置,因爲我們主要使用CSS選擇器 – kinet 2010-05-18 22:53:16

9

我相信value方法返回輸入字段的值,不能用於測試屬性。

像這樣的東西可能不是工作:

page.should have_css("img[alt=the_alt_text_you_are_expecting]") 
7

的主題是另一個變化:

Then /^I should see the image alt "([^"]*)"$/ do |alt_text| 
    page.should have_css('img', :alt => alt_text) 
end 
+0

非常簡單,但這對我不起作用。 (RSpec 3.0 +水豚2.4) – 2014-12-02 03:13:34

0

我不知道你使用的方法找到圖像,但這適用於我:

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

一旦你有元素[:"tag"]會給你價值。

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

如果您有更復雜的測試,將設置值。