2012-01-04 89 views
0

我有一個黃瓜場景,它檢查文件中的某些字符串。不是一種非常理想的做事方式,但它被認爲是絕對的需要。其中有一個表使用紅寶石在文件中搜索黃瓜場景

我的黃瓜情景:

和電子郵件應該有

|search_string| 
|Nokogiri  | 
|Cucumber  | 
|White Tiger | 

我的步驟定義

Given /^the email should have$/ do |table| 
    table.hashes.each do |hash| 
    check_email(hash["search_string"]) 
    end 
end 

我check_email方法

require 'nokogiri' 

def check_email(search_string) 
    htmlFile = File.open(filename).read 
    doc = Nokogiri::HTML::DocumentFragment.parse(htmlFile) 
    if (doc.content["#{search_string}"]) 
    puts true 
    return true 
    end 
    htmlFile.close 
    puts false 
    return false 
end 

我正在閱讀的文件雖然是「.txt」文件擴展名,但文件中的內容爲HTML格式。

  1. 的方法讀取正確的文件
  2. 該文件具有該方法試圖找到

我們,我看到的實際問題的內容。

  1. 我的黃瓜場景中的search_string有3個要搜索的值。 「White Tiger」不在文件中
  2. 由於「White Tiger」不在文件中,測試應該失敗,但測試通過/我應該說我看到「綠色」,並且當我輸出實際結果爲上面的代碼清楚地表明瞭這一點(Nokogiri是真的,黃瓜是真的,白虎是假的)。

我的問題是如何做到這一點。黃瓜表結果應僅顯示文件中可用值的GREEN/PASS和不顯示文件中值的RED/FAIL。

有人可以幫助我這個。提前欣賞。

回答

1

除非發生異常,否則黃瓜不會失敗一步(這是在RSpec匹配器不滿意時發生的情況)。簡單地返回真或假是毫無意義的。

你的說法或許應該是這個樣子

if (!doc.content["#{search_string}"]) 
    raise "Expected the file to contain '#{search_string}'" 
end 
+0

感謝您的答案。 – user1126946 2012-01-06 01:58:25

+1

如果我的或未知的答案幫助您,請考慮進行投票並將其中一個標記爲已接受,謝謝! – 2012-01-06 09:04:31

0

如果要原樣使用check_email功能,可以斷言添加到您的步驟定義:

Given /^the email should have$/ do |table| 
    table.hashes.each do |hash| 
    check_email(hash["search_string"]).should be_true 
    end 
end 

你也可以只讓您的電子郵件功能返回一個字符串,並在您的步驟定義中檢查其內容:

require 'nokogiri' 

def email_contents 
    html = IO.read(filename) 
    doc = Nokogiri::HTML::DocumentFragment.parse(html) 
    return doc.content 
end 

# ... 

Given /^the email should have$/ do |table| 
    contents = email_contents 

    table.hashes.each do |hash| 
    contents.should include(hash["search_string"]) 
    end 
end 

這些都不比Jon M的方法更好或更差 - 只是另一種選擇。