【问题标题】:RSpec 2: Hash matcher with wildcards?RSpec 2:带有通配符的哈希匹配器?
【发布时间】:2014-08-26 10:06:42
【问题描述】:

我开发并计划针对一组预定义的答案测试 REST API,当然,在服务器的 JSON 响应中,诸如 URL(带有嵌入式 ID)之类的内容将与(固定的)期望字符串不匹配。

是否有一个 rspec2(我们还没有迁移到 rspec3)匹配器来比较包含字符串、Fixnums 和更多哈希的(多级)哈希与包含字符串、Fixnums、Regexps 的哈希(其中可以匹配多个String和Fixnum对象)和更多的Hashes?

示例:我想要这个 API 响应(JSON 格式),

response = { 
  id: 295180,
  url: "http://foo.bar/api/v1/foobars/295180",
  active: true,
  from: "2014-10-01T13:00:00+02:00",
  to: "2014-10-11T13:00:00+02:00",
  user: {
    id: 913049,
    url: "http://foo.bar/api/v1/users/913049",
    name: "john Doe",
    age: 29,
  }
}

要被这个比较器匹配,它可以(并且应该)包含在一个单独的文件中(例如 matchers.json_re)

expectation = { 
  id: /\d+/,
  url: /http:\/\/foo\.bar\/api\/v1\/foobars\/\d+/,
  active: /(true|false)/,
  from: /2014-\d{2}-\d{2}T13:00:00+02:00/,
  to: /.*/,
  user: {
    id: /\d/+,
    url: /http:\/\/foo\.bar\/api\/v1\/users\/\d+/,
    name: "john Doe",
    age: 29,
  }
}

有点像

response.should == hash_re(expectation)

在 rspec2 中。

或者对于 API 响应测试有完全不同的方法吗?

【问题讨论】:

  • 澄清一下:这个 API 服务器是您的被测对象还是第三方服务?
  • 已在上面阐明。不知何故,这个问题让我想起了 Rspec 的“任何东西”参数匹配器,它可以在 should_receive 调用中使用,比如 @object.should_receive(:call).with(:foo, "bar", anything()).and_return(...)
  • hash_re 来自哪里?没见过
  • phoet,这正是我想要它的原因。 :) 这只是我想如何使用该功能的一个示例(尚不存在)。

标签: ruby json api hash rspec


【解决方案1】:

没有内置的匹配器可以满足您的需求,但是您可以使用custom matcher 实现它。首先,这可以满足您的一些需求:

require 'rspec/expectations'

RSpec::Matchers.define :be_hash_matching_regexes do |expected|
  match do |actual|
    expected.all? do |key, regex|
      actual[key].to_s.match(regex)
    end
  end
end

然后允许你这样做:

response.should be_hash_matching_regexes(expectation)

此实现不会进行您所追求的深度匹配,但扩展它来做到这一点应该非常简单。

【讨论】:

    猜你喜欢
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2021-04-23
    • 2021-11-11
    • 2017-11-07
    • 2018-08-24
    相关资源
    最近更新 更多