RSpec: 使用 `receive ... exactly ... with ... and_return ...` 和不同的 `with` 参数

RSpec: use `receive ... exactly ... with ... and_return ...` with different `with` arguments

我正在写一个期望,它检查是否使用不同的参数和 returns 不同的值调用一个方法两次。目前我只是写了两次期望:

expect(ctx[:helpers]).to receive(:sanitize_strip).with(
  %{String\n<a href="http://localhost:3000/">description</a> <br/>and newline\n<br>},
  length: nil
).and_return('String description and newline')

expect(ctx[:helpers]).to receive(:sanitize_strip).with(
  %{String\n<a href="http://localhost:3000/">description</a> <br/>and newline\n<br>},
  length: 15
).and_return('String descr...')

不知能否用receive ... exactly ... with ... and_return ...代替;类似于:

expect(ctx[:helpers]).to receive(:sanitize_strip).exactly(2).times.with(
  %{String\n<a href="http://localhost:3000/">description</a> <br/>and newline\n<br>},
  length: nil
).with(
  %{String\n<a href="http://localhost:3000/">description</a> <br/>and newline\n<br>},
  length: 15
).and_return('String descr...', 'String description and newline')

上面的代码不起作用,它引发了以下错误:

1) Types::Collection fields succeeds
   Failure/Error: context[:helpers].sanitize_strip(text, length: truncate_at)

     #<Double :helpers> received :sanitize_strip with unexpected arguments
       expected: ("String\n<a href=\"http://localhost:3000/\">description</a> <br/>and newline\n<br>", {:length=>15})
            got: ("String\n<a href=\"http://localhost:3000/\">description</a> <br/>and newline\n<br>", {:length=>nil})
     Diff:
     @@ -1,3 +1,3 @@
      ["String\n<a href=\"http://localhost:3000/\">description</a> <br/>and newline\n<br>",
     - {:length=>15}]
     + {:length=>nil}]

有没有办法将 receive ... exactly ... with ... and_return ... 与不同的 with 参数一起使用?

有一个 rspec-any_of gem 通过提供 all_of 参数匹配器允许以下语法:

expect(ctx[:helpers]).to receive(:sanitize_strip).with(
  %{String\n<a href="http://localhost:3000/">description</a> <br/>and newline\n<br>}
  all_of({length: 15}, {length: nil})
)
.and_return('String descr...', 'String description and newline')
.twice