我开发并计划根据一组预定义的答案测试REST,当然,在服务器的JSON响应中,像URL(嵌入I)这样的东西将与(固定的)期望字符串不匹配。
是否有rspec2 (我们还没有迁移到rspec3 )匹配器来比较包含String、Fixnum和更多散列的(多级)哈希和包含String、Fixnum、Regexps (可以匹配多个字符串和Fixnum对象)和更多哈希的哈希?
示例:我需要这个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响应测试,是否有完全不同的方法?
发布于 2014-07-06 07:39:52
有一个内置的匹配器,它可以做你想做的事情,但是你可以用定制匹配器来实现它。对于初学者来说,这做了一些您想要的事情:
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)这个实现没有完成您所追求的深度匹配,但是扩展它应该是非常简单的。
https://stackoverflow.com/questions/24584940
复制相似问题