Fil*_*uzi 4 ruby testing rspec ruby-on-rails rspec3
我希望在引发异常的情况下先发出两次对HTTParty的调用,然后第三次调用应该返回值.
before do
allow(HTTParty).to receive(:get).exactly(2).times.with(url).and_raise(HTTParty::Error)
allow(HTTParty).to receive(:get).with(url).and_return('{}')
end
Run Code Online (Sandbox Code Playgroud)
但是一个允许覆盖另一个.如何设置存根以在前几次尝试中引发错误然后让它返回一个值?
根据此github问题中提供的信息,您还可以使用以下纯RSpec方法执行此操作.它利用了使用块定义模拟响应的最常用方法:
before do
reponse_values = [:raise, :raise, '{}']
allow(HTTParty).to receive(:get).exactly(3).times.with(url) do
v = response_values.shift
v == :raise ? raise(HTTParty::Error) : v
end
end
Run Code Online (Sandbox Code Playgroud)
在这种特定情况下,您可以使用 WebMock:
像这样的东西应该有效:
before do
stub_request(:get, url).
to_raise(SomeException).then.
to_raise(SomeException).then.
to_return(body: '{}')
end
Run Code Online (Sandbox Code Playgroud)
SomeException应该是实际的网络错误。