2012-12-17 38 views
2

使用RSpec,有沒有辦法比較兩個哈希,我不知道一些值會是什麼?我試過使用instance_of,但它似乎不工作。比較兩個具有未知值的哈希

在我的測試中,我使用POST請求創建了一個新的設備對象,並且希望確保我得到正確的JSON響應。它正在爲設備創建一個UUID(我沒有使用關係數據庫),但我顯然不知道這個值會是什麼,也不太在意。

post "/projects/1/devices.json", name: 'New Device' 

expected = {'name' => 'New Device', 'uuid' => instance_of(String), 'type' => 'Device'} 

JSON.parse(body).should == expected 

而且我得到以下錯誤:

1) DevicesController API adds a new device to a project 
    Failure/Error: JSON.parse(body).should == expected 
     expected: {"name"=>"New Device", "uuid"=>#<RSpec::Mocks::ArgumentMatchers::InstanceOf:0x5a27147d @klass=String>, "type"=>"Device"} 
      got: {"name"=>"New Device", "uuid"=>"ef773465-7cec-48fd-b2a7-f1da10d1595a", "type"=>"Device"} (using ==) 
     Diff: 
     @@ -1,4 +1,4 @@ 
     "name" => "New Device", 
     "type" => "Device", 
     -"uuid" => #<RSpec::Mocks::ArgumentMatchers::InstanceOf:0x5a27147d @klass=String> 
     +"uuid" => "ef773465-7cec-48fd-b2a7-f1da10d1595a" 
    # ./spec/api/devices_spec.rb:37:in `(root)' 

回答

3

instance_of是參數匹配:

something.should_receive(:foo).with(instance_of(String)) 

除了使用==運營商可以使用include。例如:

JSON.parse(body).should include('uuid', 'name' => 'New Device', 'type' => 'Device') 

其說,關鍵uuid必須存在與任何值和nametype應存在與指定的值。它也將允許哈希中的其他鍵。

我不知道如何通過內置匹配器實現您要求的內容。