67
class Foo
  def bar(a, b)
  ...

Foo.should_receive( :bar )

expects bar to be called with any arguments.

Foo.should_receive( :bar ).with( :baz, :qux )

expects :baz and :qux to be passed in as the params.

How to expect the first param to equal :baz, and not care about the other params?

B Seven
  • 44,484
  • 66
  • 240
  • 385

3 Answers3

89

Use the anything matcher:

Foo.should_receive(:bar).with(:baz, anything)
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • 5
    This works. The caveat is you need one `anything` for each param. – B Seven Oct 07 '13 at 22:23
  • 13
    I am not sure whether it was added afterwards, but RSpec has any_args so that for `bar(a, b, c)` you can do `Foo.should_receive(:bar).with(:baz, any_args)` – rubyprince Jul 04 '16 at 09:10
  • Thanks @rubyprince very much, great tip! – Blue Smith Jan 26 '18 at 07:45
  • I have found anything does not work unless it is the last argument, which is frustrating. Eg. this does not work: `.with(:baz, anything, :foo)` – girlcode Apr 29 '21 at 21:40
  • I'm going to drop this here to show how you can do this with an object param: `expect(MyObjectRepository).to receive(:create).with({ filename: anything, something_else: some_variable_declared_above })` – patrickbadley Oct 14 '21 at 15:48
  • A complement: It's possible to match the type of parameter, like this: `expect(RegsiterWorker).to have_received(:perform_async).with(instance_of(Integer), "onboarding")` - In my context, the first parameter is a number which I can't handle on my spec. It enough knows it's a number` – Rafael Gomes Francisco May 22 '23 at 20:54
30

For Rspec 1.3 anything doesn't work when your method is receiving a hash as an argument, so please try with hash_including(:key => val):

Connectors::Scim::Preprocessors::Builder.
    should_receive(:build).
    with(
      hash_including(:connector => connector)
      ).
    and_return(preprocessor)
}
G. I. Joe
  • 1,585
  • 17
  • 21
24

There's another way to do this, which is the block form of receive: https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation#use-a-block-to-verify-arguments

expect(Foo).to receive(:bar) do |args|
  expect(args[0]).to eq(:baz)
end
max pleaner
  • 26,189
  • 9
  • 66
  • 118