7

是的,我知道最好使用 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"})

如何正确搭配?

4

3 回答 3

6

如果您不关心确切的实例,则可以使用以下an_instance_of方法:

http.should_receive(:request).with(an_instance_of(Net::HTTP::Post), foo: 1)
.and_return 202
于 2012-12-07T01:18:55.447 回答
6

这是新语法:

before do
  http = double
  allow(Net::HTTP).to receive(:start).and_yield http
  allow(http).to \
    receive(:request).with(an_instance_of(Net::HTTP::Get))
      .and_return(Net::HTTPResponse)
end

然后在示例中:

it "http" do
  allow(Net::HTTPResponse).to receive(:body)
    .and_return('the actual body of response')
  # here execute request
end

如果您需要测试外部 api 库,这非常有用。

于 2015-12-24T07:19:08.327 回答
0

以下片段对我来说很好。它模拟 DELETE 请求。

mock_net_http = double("Net:HTTP")
mock_net_http_delete = double("Net::HTTP::Delete")
allow(Net::HTTP).to receive(:new).and_return(mock_net_http)
allow(Net::HTTP::Delete).to receive(:new).and_return(mock_net_http_delete)

expect(mock_net_http_delete).to receive(:set_form_data).with(hash_including(some_param: "some-value"))
expect(mock_net_http).to receive(:request).with(mock_net_http_delete)
于 2020-09-12T08:43:55.650 回答