如何模拟Net :: HTTP :: Post? [英] How to mock Net::HTTP::Post?
本文介绍了如何模拟Net :: HTTP :: Post?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟这个方法:
Yes, I know it is best to use webmock, but I would like to know how to mock this method in RSpec:
def method_to_test
url = URI.parse uri
req = Net::HTTP::Post.new url.path
res = Net::HTTP.start(url.host, url.port) do |http|
http.request req, foo: 1
end
res
end
这是RSpec:
let( :uri ) { 'http://example.com' }
specify 'HTTP call' do
http = mock :http
Net::HTTP.stub!(:start).and_yield http
http.should_receive(:request).with(Net::HTTP::Post.new(uri), foo: 1)
.and_return 202
method_to_test.should == 202
end
测试失败,因为带的似乎试图匹配NET :: HTTP :: Post对象:
The test fails because with
seems to be trying to match the NET::HTTP::Post object:
RSpec::Mocks::MockExpectationError: (Mock :http).request(#<Net::HTTP::Post POST>, {:foo=>"1"})
expected: 1 time
received: 0 times
Mock :http received :request with unexpected arguments
expected: (#<Net::HTTP::Post POST>, {:foo=>"1"})
got: (#<Net::HTTP::Post POST>, {:foo=>"1"})
如何匹配专业版perly?
How to match properly?
推荐答案
如果您不关心确切的实例,可以使用 an_instance_of
方法:
If you don't care about the exact instance, you could use the an_instance_of
method:
http.should_receive(:request).with(an_instance_of(Net::HTTP::Post), foo: 1)
.and_return 202
这篇关于如何模拟Net :: HTTP :: Post?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文