我正在写一个期望,该期望检查是否两次使用不同的参数调用了一个方法并返回了不同的值。目前,我只写了两次期望:
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
参数一起使用?
答案 0 :(得分:1)
有一个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