2012-11-05 59 views
0

我已經爲RR創建了一個匹配JSON字符串的通配符匹配器,通過將它們解析爲哈希值。這是因爲JSON(de)序列化不能保持順序;如果我們有:如何使用自定義RR通配符匹配器?

{ 'foo': 42, 'bar': 123 } 

...然後之後(德)序列化,我們可能會發現,我們的更新方法被調用:

{ '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 

這符合RR documentation。然而,代替mock()期待匹配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 
+0

發佈時,我注意到總共有15個問題用'rr'標記。我懷疑第一個答案可能是「不使用rr」;-) –

回答

0

答案是,有文檔中一個錯字,而我聯繫。這(我的重點):

#wildcard_matches?(other) 

wildcard_matches? is the method that actually checks the argument against the expectation. It should return true if other is considered to match, false otherwise. In the case of DivisibleBy, wildcard_matches? reads: 

...實際上應:

#wildcard_match?(other) 

... 

我的一位同事的建議,我們比較我們的代碼與在RR寶石定義的匹配器之一,然後差異顯而易見。