RSpec:使用`接收...没错..,和..,带有不同的`with`参数的AND_Return...`

hrysbysz  于 2022-09-21  发布在  Ruby
关注(0)|答案(2)|浏览(116)

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

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}]

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

at0kjp5o

at0kjp5o1#

有一个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
nuypyhwy

nuypyhwy2#

在不使用额外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

相关问题