2014-07-02 28 views
0

我目前正在研究一個使用google_drive gem填充數據庫的rake任務。寶石允許用戶訪問電子表格ws像這樣:使用rspec保存數組的響應

# Gets content of A2 cell. 
p ws[2, 1] #==> "hoge" 

,我試圖以規範的功能如下:

def get_tags(ws, row) 
    tags = [] 
    [1, 21, 22, 23, 26, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40].each do |col| 
    tags << ws[row, col] unless ws[row, col].blank? 
    end 
    tags 
end 

相當自我解釋,它被傳遞一個行,然後將列數據添加到數組中指定的每個列的tags

ws陣列組成的:

ws = [[nil, 'Good', 'Tultex', '0241', 'Men\s Blend Tee', 
      'XS - 3XL', '$3.40', '$4.50', '$4.50', '--', '--', '--', 
      'TSC', 'y', 'Adult Unisex', 'Tee Shirt', 'Short Sleeve', 
      'Crewneck', '3.2', 'Cotton/Poly (35/36)', 'Fitted', '11', 
      '0240 (ladies)', '', 'Std Fitted Crew', 'Tees and Tanks', 
      'Nicer - Fashion Fitted', 'Blend', '', '', '', 'Fashionable', 
      '', '', '']] 

因此,我需要get_tags返回此:

resultant = ['Good', 'Tee Shirt', 'Short Sleeve', 'Crew Neck', 
      'Standard', '', 'Tees and Tanks', 'Least Expensive', 
      'Regular Cotton', '', '', '', '', '', '', 'Least Expensive'] 

我的問題是,我不知道我怎麼可以規範數組接受ws所做的索引類型(ws[val, val]),因爲這通常是一個範圍索引。我試圖創建一個二維數組,但顯然不工作。也試圖通過做磕碰出來:

allow(ws).to receive(:[]) do |arg1, arg2| 
    ws[arg1][arg2] 
end 

這創造stubbiness的無限循環,所以後來我試圖存儲ws到另一個數組稱爲temp,做這個(幾乎同樣的事情):

allow(ws).to receive(:[]) do |arg1, arg2| 
    temp[arg1][arg2] 
end 

但我仍然以相同的無限循環結束。 任何建議下一步將採取什麼步驟將不勝感激!在此先感謝:)

+0

的傳遞實際的'GoogleDrive :: Worksheet'實例不是一個選項? (你可以使用[VCR](https://www.relishapp.com/vcr/vcr/docs)來記錄HTTP流量以進行快速測試) – Stefan

回答

1

如何創建它處理所需要的接口的類:

class DBStub 
    def initialize(data_store) 
    @data_store = data_store 
    end 

    def [](arg1, arg2) 
    @data_store[arg1][arg2] 
    end 
end 

ws = DBStub.new(temp) 
+0

尼斯:一個很好的,優雅的解決方案!謝謝! – davidicus

0

你期望什麼值在ws?如果你不關心的值是什麼,只是想測試他們加入你可以做

allow(ws).to receive(:[]) { rand(1000) } 
+0

對不起,我在這個問題上還不夠具體,我已經硬編碼了數據不過需要從'ws'中獲取,我在這個問題上添加了一個編輯,以表明我擁有什麼以及需要從'get_tags'返回什麼 – davidicus