Ruby 如何使用自定义RR通配符匹配器?

Ruby 如何使用自定义RR通配符匹配器?,ruby,rspec,rr,Ruby,Rspec,Rr,我创建了一个通配符匹配器,通过将JSON字符串解析为散列来匹配它们。这是因为JSON(反)序列化不保持顺序;如果我们有: { 'foo': 42, 'bar': 123 } 。。。然后在(反)序列化之后,我们可能会发现我们的update方法是通过以下方式调用的: { 'bar': 123, 'foo': 42 } 通配符匹配器如下所示: class RR::WildcardMatchers::MatchesJsonString attr_reader :expected_json_ha

我创建了一个通配符匹配器,通过将JSON字符串解析为散列来匹配它们。这是因为JSON(反)序列化不保持顺序;如果我们有:

{ 'foo': 42, 'bar': 123 }
。。。然后在(反)序列化之后,我们可能会发现我们的update方法是通过以下方式调用的:

{ 'bar': 123, 'foo': 42 }
通配符匹配器如下所示:

class RR::WildcardMatchers::MatchesJsonString

  attr_reader :expected_json_hash

  def initialize(expected_json_string)
    @expected_json_hash = JSON.parse(expected_json_string)
  end

  def ==(other)
    other.respond_to?(:expected_json_hash) && other.expected_json_hash == self.expected_json_hash
  end

  def wildcard_matches?(actual_json_string)
    actual_json_hash = JSON.parse(actual_json_string)
    @expected_json_hash == actual_json_hash
  end
end

module RR::Adapters::RRMethods
  def matches_json(expected_json_string)
    RR::WildcardMatchers::MatchesJsonString.new(expected_json_string)
  end
end
。。。我们使用它的方式如下:

describe 'saving manifests' do

  before do
    @manifests = [
      { :sections => [], 'title' => 'manifest1' },
      { :sections => [], 'title' => 'manifest2' }
    ]

    mock(manifest).create_or_update!(matches_json(@manifests[0].to_json)) { raise 'uh oh' }
    mock(manifest).create_or_update!(matches_json(@manifests[1].to_json))

    parser = ContentPack::ContentPackParser.new({
                                                  'manifests' => @manifests
                                                })
    @errors = parser.save
  end

  it 'updates manifests' do
    manifest.should have_received.create_or_update!(anything).twice
  end
end
这是根据《公约》进行的。但是,它不希望参数与JSON匹配,而是希望参数是
MatchesJsonString
对象:

 1) ContentPack::ContentPackParser saving manifests updates manifests
     Failure/Error: mock(Manifest).create_or_update!(matches_json(@manifests[0].to_json)) { raise 'uh oh' }
     RR::Errors::TimesCalledError:
       create_or_update!(#<RR::WildcardMatchers::MatchesJsonString:0x13540def0 @expected_json_hash={"title"=>"manifest1", "sections"=>[]}>)
       Called 0 times.
       Expected 1 times.
     # ./spec/models/content_pack/content_pack_parser_spec.rb:196
1)ContentPack::ContentPackParser保存清单更新清单
失败/错误:模拟(清单)。创建\u或\u更新!(匹配_-json(@manifests[0]。到_-json)){raise'uh-oh'}
RR::错误::TimeCalledError:
创建或更新!(#“manifest1”,“sections”=>[]}>)
打了0次电话。
预计1次。
#./spec/models/content\u pack/content\u pack\u parser\u spec.rb:196

答案是我链接的文档中有一个打字错误。这(我的重点):

。。。实际上应该是:

#wildcard_match?(other)

...

我的一位同事建议我们将我们的代码与rr gem中定义的一个匹配器进行比较,然后区别就突出了。

在发布时,我注意到总共有15个问题标有“rr”。我怀疑第一个答案可能是“不要使用rr”;-)
#wildcard_match?(other)

...