开发者

Rspec matcher is not using custom error message

开发者 https://www.devze.com 2023-02-28 06:34 出处:网络
I have a custom matcher: RSpec::Matchers.define :have_value do |attribute, expected| match do |obj| obj.send(attribute) == expected

I have a custom matcher:

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

And this is an example of how I am using it:

context "descr开发者_如何转开发iption" 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

This is running my tests correctly. But when I get an error, it's not the custom error, it is "expected {masssive object dump} to have value :atttribute and value" Any ideas as to what I"m doing wrong?


Thanks for using my code in response to your last question. Here is what you need for this example:

  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


You need to specify custom failure messages. An example from 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
0

精彩评论

暂无评论...
验证码 换一张
取 消