2014-07-02 27 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