2011-04-21 82 views
1

我有一個自定義匹配:Rspec的匹配器不使用自定義錯誤消息

RSpec::Matchers.define :have_value do |attribute, expected| 
    match do |obj| 
    obj.send(attribute) == expected 
    end 

    description do 
    "have attribute #{attribute} with value #{expected}" 
    end 
end 

這是我如何使用它的例子:

context "description" do 
     subject { create_obj_from_file(file_name) } 
     h = { 
      :attribute1 => 6, 
      :attribute2 => 3, 
      :attribute3 => "PL" } 
     } 
     h.each do |k,v| it { should have_value k, v} end 
    end 

這是正常運行我的測試。但是,當我得到一個錯誤,這不是自定義錯誤,它是「預期{masssive對象轉儲}有價值:atttribute和值」任何想法,我什麼我做錯了?

回答

1

感謝您使用響應你的最後一個問題,我的代碼以下是你需要什麼,這個例子:

failure_message_for_should do |obj| 
    "should have value #{expected} for attribute #{attribute} but got #{obj.send(attribute)}" 
    end 


    failure_message_for_should_not do |obj| 
    "should not have value #{expected} for attribute #{attribute} but got #{obj.send(attribute)}" 
    end 
+0

謝謝主席先生,檢查是郵件 :) – 2011-04-21 04:59:44

1

您需要指定自定義失敗消息從the wiki一個例子:。

RSpec::Matchers.define :be_a_multiple_of do |expected| 
    match do |actual| 
    actual % expected == 0 
    end 

    failure_message_for_should do |actual| 
    "expected that #{actual} would be a precise multiple of #{expected}" 
    end 

    failure_message_for_should_not do |actual| 
    "expected that #{actual} would not be a precise multiple of #{expected}" 
    end 

    description do 
    "be a precise multiple of #{expected}" 
    end 
end