Rspec匹配器未使用自定义错误消息

时间:2011-04-21 02:25:57

标签: ruby-on-rails ruby 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 object dump}具有值:atttribute和value”关于我做错了什么的任何想法?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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