2010-11-19 18 views
1

我知道/Interface \d/在頁面上出現三次。但我不知道如何用黃瓜水豚進行測試。這是我的第一次嘗試:如何檢查使用水豚(或Webrat,我猜)和黃瓜多次出現的單詞?

Then /^(?:|I)should see \/([^\/]*)\/ (\d+)(?:x|X| times?)?$/ do |regexp, count| 
    regexp = Regexp.new(regexp) 
    count = count.to_i 
    if page.respond_to? :should 
    page.should have_xpath('//*', { :text => regexp, :count => count }) 
    else 
    assert page.has_xpath?('//*', { :text => regexp, :count => count }) 
    end 
end 

但是,這將返回false爲我的Then I should see /Interface \d+/ 3 times

我發現這是因爲has_xpath使用all。在我的測試把這樣的:在

#<Capybara::Element tag="html" path="/html"> 
#<Capybara::Element tag="body" path="/html/body"> 
#<Capybara::Element tag="div" path="/html/body/div"> 
#<Capybara::Element tag="div" path="/html/body/div/div[2]"> 
#<Capybara::Element tag="table" path="/html/body/div/div[2]/table"> 
#<Capybara::Element tag="tbody" path="/html/body/div/div[2]/table/tbody"> 
#<Capybara::Element tag="tr" path="/html/body/div/div[2]/table/tbody/tr[1]"> 
#<Capybara::Element tag="td" path="/html/body/div/div[2]/table/tbody/tr[1]/td[3]"> 
#<Capybara::Element tag="tr" path="/html/body/div/div[2]/table/tbody/tr[2]"> 
#<Capybara::Element tag="td" path="/html/body/div/div[2]/table/tbody/tr[2]/td[3]"> 
#<Capybara::Element tag="tr" path="/html/body/div/div[2]/table/tbody/tr[3]"> 
#<Capybara::Element tag="td" path="/html/body/div/div[2]/table/tbody/tr[3]/td[3]"> 

puts all(:xpath, '//*', { :text => regexp}).map {|e| pp e} 

結果讓我得到沿途包含我的文本元素的每一步的計數。 : - \

我想也許has_content會救我,但它不接受一個計數。

幫助!

回答

2

像這樣的東西應該工作:

Then /^(?:|I)should see \/([^\/]*)\/ (\d+)(?:x|X| times?)?$/ do |regexp, count| 
    regexp = Regexp.new(regexp) 
    count = count.to_i 
    page.find(:xpath, '//body').text.split(regexp).length.should == count+1 
end 
+0

兩個原因我不喜歡「內嗒嗒」使用方法:1)它是脆。現在這些在​​s,但那會很快改變。我不想改變測試。 2)這不是真的從用戶的角度來看,我喜歡儘可能地堅持在黃瓜功能。 – chadoh 2010-11-22 13:50:47

+0

夠公平的......我已經刪除了CSS選擇器的建議。 – Zubin 2010-11-27 19:05:16