How to expect some (but not all) arguments with RSpec should_receive?

假装没事ソ 提交于 2020-04-07 02:34:40

问题


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?


回答1:


Use the anything matcher:

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



回答2:


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)
}



回答3:


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


来源:https://stackoverflow.com/questions/19233047/how-to-expect-some-but-not-all-arguments-with-rspec-should-receive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!