1

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

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论点?

4

1 回答 1

1

有一个rspec-any_ofgemall_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
于 2019-05-08T21:20:37.483 回答