rspec - match arguments with code block

In rspec, I usually need to define a matcher to match arguments. I don’t want to create a match for every should_receive method. I just want to assert the arguments I care. I try to define a code block to assert my call arguments. I google it for a while and could not find an answer.

I want to do something like:

User.should_receive(:find).with(assert_that(lambda { |args
  options = args.pop
  options[:include].should == expected_include
  options[:limit].should == 100
}).and_return(:users)

After reading rspec source code, I finger out rspec should_receive argument allow code block. That’s easier than what I expect. The finial code is:

User.should_receive(:find).with do |*args|
  options = args.pop
  options[:include].should == expected_include
  options[:limit].should == 100
  true
end.and_return(:users)

remember to return true at the end if all assertions pass.


blogroll

social