Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match an argument's attribute value in rspec

Is there a way to match an argument's attribute value in rspec? Checking the documentation it looks like there's other matchers available, such as anything, an_instance_of, and hash_including - but nothing to check the value of an object's attribute.

Example - suppose I have this instance method:

class DateParser
  def parse_year(a_date)
    puts a_date.year
  end
end

Then I can write an expectation like this:

dp = DateParser.new
expect(dp).to receive(:parse_year).with(some_matcher)

What I want for some_matcher to check that parse_year is called with any object that has an attribute year that has the value 2014. Is this possible with the out-of-the-box argument matchers in rspec, or does a custom one have to be written?

like image 936
mralexlau Avatar asked Dec 06 '22 02:12

mralexlau


1 Answers

You can pass a block and set expectations about the argument(s) within the block:

describe DateParser do
  it "expects a date with year 2014" do
    expect(subject).to receive(:parse_year) do |date|
      expect(date.year).to eq(2014)
    end
    subject.parse_year(Date.new(2014,1,1))
  end
end
like image 61
Stefan Avatar answered Jan 15 '23 05:01

Stefan