我正在编写一个期望,该期望检查是否使用不同的参数调用了两次方法并返回了不同的值。目前我只是写了两次期望:
expect(ctx[:helpers]).to receive(:sanitize_strip).with(
%{Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>},
length: nil
).and_return('String description and newline')
expect(ctx[:helpers]).to receive(:sanitize_strip).with(
%{Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>},
length: 15
).and_return('String descr...')
我想知道我是否可以改用receive ... exactly ... with ... and_return ...
;像这样:
expect(ctx[:helpers]).to receive(:sanitize_strip).exactly(2).times.with(
%{Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>},
length: nil
).with(
%{Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<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: ("Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>", {:length=>15})
got: ("Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>", {:length=>nil})
Diff:
@@ -1,3 +1,3 @@
["Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>",
- {:length=>15}]
+ {:length=>nil}]
有没有办法使用具有不同with
参数的receive ... exactly ... with ... and_return ...
?
有一个
rspec-any_of
gem 允许通过all_of
参数匹配器来使用以下语法:
expect(ctx[:helpers]).to receive(:sanitize_strip).with(
%{Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>}
all_of({length: 15}, {length: nil})
)
.and_return('String descr...', 'String description and newline')
.twice
如果不使用额外的 gem,您可以使用each
块内的变量调用普通expect ... to receive ... with ... and_return ...
:
describe '#sanitize_strip' do
let(:html) do
%{Stringn<a href="http://localhost:3000/">description</a> <br/>and newlinen<br>}
end
let(:test_data) do
[
[[html, length: nil], 'String description and newline'],
[[html, length: 15], 'String descr...']
]
end
it 'returns sanitized strings stripped to the number of characters provided' do
test_data.each do |args, result|
expect(ctx[:helpers]).to receive(:sanitize_strip).with(*args).and_return(result)
end
# Trigger the calls to sanitize_strip
end
end