如何期望RSpec的一些(但不是全部)参数应该存在?

B S*_*ven 25 ruby rspec expectations

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

Foo.should_receive( :bar )
Run Code Online (Sandbox Code Playgroud)

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

Foo.should_receive( :bar ).with( :baz, :qux )
Run Code Online (Sandbox Code Playgroud)

期待:baz和:qux作为params传入.

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

Dyl*_*kow 42

使用anything匹配器:

Foo.should_receive(:bar).with(:baz, anything)
Run Code Online (Sandbox Code Playgroud)

  • 我不确定它是否是之后添加的,但是RSpec有any_args所以对于`bar(a,b,c)`你可以做`Foo.should_receive(:bar).with(:baz,any_args)` (5认同)
  • 这有效.需要注意的是,每个参数都需要一个"任何东西". (2认同)

max*_*ner 12

还有另一种方法可以做到这一点,这是块形式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
Run Code Online (Sandbox Code Playgroud)


G. *_*Joe 8

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

Connectors::Scim::Preprocessors::Builder.
    should_receive(:build).
    with(
      hash_including(:connector => connector)
      ).
    and_return(preprocessor)
}
Run Code Online (Sandbox Code Playgroud)