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

Foo.should_receive( :bar )

期望使用任何参数调用 bar。

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

期望 :baz 和 :qux 作为参数传入。

如何期望第一个参数等于:baz,而不关心其他参数?

4

3 回答 3

64

使用anything匹配器:

Foo.should_receive(:bar).with(:baz, anything)
于 2013-10-07T19:37:54.570 回答
21

当您的方法接收哈希作为参数时, Rspec 1.3 anything不起作用,因此请尝试使用:hash_including(:key => val)

Connectors::Scim::Preprocessors::Builder.
    should_receive(:build).
    with(
      hash_including(:connector => connector)
      ).
    and_return(preprocessor)
}
于 2017-12-01T17:49:31.563 回答
14

还有另一种方法可以做到这一点,即块形式receivehttps ://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation#use-a-block-验证参数

expect(Foo).to receive(:bar) do |args|
  expect(args[0]).to eq(:baz)
end
于 2020-03-13T15:25:16.767 回答