简体   繁体   English

如何在 Ruby 中存根请求/响应

[英]How to stub request/response in Ruby

Using RSpec's mock/stub, how do I write a unit test for the find_by_id method?使用 RSpec 的模拟/存根,我如何为find_by_id方法编写单元测试?

I want to use RSpec, not WebMock or VCR.我想使用 RSpec,而不是 WebMock 或 VCR。 How do I create a stub for the request/response?如何为请求/响应创建存根?

class RapidApiClient
  HOST_URL = 'https://brianiswu-open-brewery-db-v1.p.rapidapi.com/breweries'
  API_KEY  = 'private_api_key'

   def request_api(url)
    Excon.get(
      url,
      headers: {
        'X-RapidAPI-Host' => HOST_URL,
        'X-RapidAPI-Key' => 'API_KEY'
      }
    )
  end

 def find_by_id(id)
    response = request_api("#{HOST_URL}/#{id}")
    return nil if response.status != 200
    JSON.parse(response.body)
 end  
end

The response is:回应是:

[
{"id":4 , "name":"Ban Brewing Company" , "brewery_type":"micro", "city":"Tulsa" , "state":"OK"}
{"id":44,"name":"Tab Brewing" "brewery_type":"micro", "city":"Birmingham", "state":"MO"}
]

You can stub the request_api method itself so that you don't have to make the HTTP request using something like this:您可以存根request_api方法本身,这样您就不必使用以下方式发出 HTTP 请求:

expect_any_instance_of(RapidApiClient)
    .to receive(:request_api)
    .and_return([
                  {"id":4 , "name":"Ban Brewing Company" , "brewery_type":"micro", "city":"Tulsa" , "state":"OK"}
                  {"id":44,"name":"Tab Brewing" "brewery_type":"micro", "city":"Birmingham", "state":"MO"}
                ])

if you want to stub the actaul request/response.如果你想存根实际请求/响应。

You can sub the get method of Excon library like this:您可以像这样子Excon库的get方法:

expect(Excon)
.to receive(:get)
.and_return(Excon::Response.new(
     :status => 200,
     :body => '[{"id":4 , "name":"Ban Brewing Company","brewery_type":"micro", "city":"Tulsa" , "state":"OK"},{"id":44,"name":"Tab Brewing" "brewery_type":"micro", "city":"Birmingham", "state":"MO"}]'
    ))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM