Day21 测试写起乃 - Webmock

在写测试的时後,一定会有第三方服务或是会打向外部api的时候,如果不想让他真的去打外部api怕速度过慢的等等问题就可以使用 webmock 。

webmock 可以伪装 HTTP 来确保我们在测试时不会真的发出请求。

安装 webmock

# add to your Gemfile
group :test do
    gem "webmock"
end
# spec_helper.rb

require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)

参考范例:

在还没有禁用 api 之前会通过

    context "get github api" do
      it 'repo on GitHub' do
      uri = URI('https://api.github.com/repositories')

      response = Net::HTTP.get(uri)
        
      expect(response).to be_an_instance_of(String)
      end
    end

如果在测试之前加上

  before(:all) { WebMock.disable_net_connect! }
  after(:all) { WebMock.allow_net_connect! }
  
  context "get github api" do
    it 'repo on GitHub' do
    uri = URI('https://api.github.com/repositories')

    response = Net::HTTP.get(uri)

    expect(response).to be_an_instance_of(String)
    end
  end

此时会出现贴心的错误提示告诉你该如果撰写

 Failure/Error: response = Net::HTTP.get(uri)

 WebMock::NetConnectNotAllowedError:
   Real HTTP connections are disabled. Unregistered request: GET https://api.github.com/repositories with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Host'=>'api.github.com', 'User-Agent'=>'Ruby'}

   You can stub this request with the following snippet:

   stub_request(:get, "https://api.github.com/repositories").
     with(
       headers: {
      'Accept'=>'*/*',
      'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
      'Host'=>'api.github.com',
      'User-Agent'=>'Ruby'
       }).
     to_return(status: 200, body: "", headers: {})

这时来修改一下

  context "github api" do
    it 'repo on GitHub' do
    uri = URI('https://api.github.com/repositories')

    stub_request(:get, uri).
    with(
      headers: {
      'Accept'=>'*/*',
      'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
      'Host'=>'api.github.com',
      'User-Agent'=>'Ruby'
      }).
    to_return(status: 200, body: "", headers: {})

    response = Net::HTTP.get(uri)

    expect(response).to be_an_instance_of(String)
    end
  end

这时确实已经将 api stub 了,且测试也会通过

参考来源:
WebMock
How to Stub External Services in Tests


<<:  [Day06] 自动转型

>>:  【Day 8】梯度下降法(Gradient Descent) --- Tip 1

都是They的错(求SW实习生心里阴影面积)

故事的开头简述 知名3D绘图软件 SolarWinds 的前任 CEO KT 说是实习生违反 Sol...

什麽是CC攻击?它有哪些影响?

当一个网页访问的人数特别多的时候,打开网页就慢了,CC就是模拟多个用户(多少线程就是多少用户)不停地...

Day 17 - 人生的复杂度大概就是指数型的增加吧

Intro Complexity 可以了解程序的运作效率 graph 可以把复杂的问题抽象化,或是可...

Day 17手势识别GestureDectector

手势识别GestureDectector (一)介绍 支援一些较复杂的互动,例如缩放、双击、垂直、水...

Day27 Javascript元件库 Jquery介绍

今天要接触我们的Javascript,让网页更多动画,互动性,不是一个只有图片跟文字的死板网页,而J...