我们有一个 RoR 应用程序 Rspec,用于使用 Webmock 测试 HTTP 请求。 在不得不对我们的遗留代码库进行一些重构之后,我意识到我们的许多测试都有不必要的 stub 。 像这个例子一样,do_a 函数已经被重构,这样我们就不会进行任何 api 调用,所以 stub_request 不再是必需的,更糟糕的是,它应该被删除。
it 'does something' do
stub_request(:get, 'http://something.com/users/123')
do_a
expect(..)
end
解决这个问题的一种方法是:
it 'does something' do
stub_something = stub_request(:get, 'http://something.com/users/123')
do_a
expect(..)
expect(stub_something).to have_been_requested.once
end
但我想通过严格模式直接强制执行此操作,如果未调用任何已声明的 stub ,测试将失败?第一个示例将自动失败。
非常感谢您的帮助
最佳答案
您想使用 expectations而不是 stub_request
:
expect(WebMock).to have_requested(:get, "http://something.com/users/123").once
# or
expect(a_request(:get, "http://something.com/users/123")).to have_been_made.once
But I'd like to enforce this directly through a strict mode where the test fails if any declared stub has not been called?
我不认为这真的是可能的,除非你做一些繁重的猴子补丁——这似乎是一个坏主意,而不是仅仅重构你的测试。
关于ruby-on-rails - 如果尚未调用,则强制 Webmock stub_request 在测试结束时引发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63915441/