rspec:关于预期方法参数的多个期望

时间:2019-03-19 02:35:31

标签: rspec

是否有办法处理传递给测试对象的参数,然后测试对参数的多个不同期望?像这样:

expect(foo).to receive(:bar)

subject.method_under_test

expect(args_passed_to_foo).to be hash_including(key1: "some value")
expect(args_passed_to_foo).to be hash_including(key2: /some regexp/)
expect(args_passed_to_foo.keys).not_to include(:key3)
expect(some_method(args_passed_to_foo[:key4])).to be > SOME_CONST

我知道要做上述操作的唯一方法是:

expect(foo).to receive(:bar).with(
  # ........
)

subject.method_under_test

但这不能真正处理最复杂的情​​况,而且也非常麻烦,您正在用一个expect测试很多东西,这似乎不正确。

1 个答案:

答案 0 :(得分:1)

是的,获取传递给测试对象的参数的句柄的方法是:

before do
  allow(foo).to receive(:bar)
end

it 'does something' do
  subject.method_under_test

  expect(foo).to have_received(:bar) do |args_passed_to_foo|
    expect(args_passed_to_foo).to be hash_including(key1: "some value")
    expect(args_passed_to_foo).to be hash_including(key2: /some regexp/)
    expect(args_passed_to_foo.keys).not_to include(:key3)
    expect(some_method(args_passed_to_foo[:key4])).to be > SOME_CONST    
  end
end

RSpec允许您在have_received期望之后传递块。该块将产生传递给实际调用的参数。