是的,我知道最好使用webmock,但是我想知道如何在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
测试失败,因为
with
似乎试图匹配 NET::HTTP::Post 对象: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"})
如何正确搭配?
最佳答案
如果你不关心确切的实例,你可以使用 an_instance_of
方法:
http.should_receive(:request).with(an_instance_of(Net::HTTP::Post), foo: 1)
.and_return 202
关于ruby - 如何模拟 Net::HTTP::Post?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13755452/