Reputation: 1993
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?
Upvotes: 4
Views: 3691
Reputation: 114138
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
Upvotes: 15
Reputation: 23939
Maybe something using a double for the passed-in date?
date = double()
date.should_receive(:year)
DateParser.new.parse_year(date)
It's not clear what you mean by the date needing to be 2014. But you could add .and_return(2014)
to it to get that behavior from the double.
Upvotes: 0