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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With