【问题标题】:Comparing two hashes with unknown values比较两个具有未知值的哈希
【发布时间】:2012-12-18 05:25:02
【问题描述】:

使用 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)'

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    instance_of 用于参数匹配:

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

    您可以使用include,而不是使用== 运算符。例如:

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

    这表示键 uuid 必须与任何值一起出现,并且 nametype 应该与指定的值一起出现。它还将允许哈希中的其他键。

    我不知道使用内置匹配器准确实现您所要求的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多