私はBoxr gem(https://github.com/cburnette/boxr)を使ってリクエストをapi.box.comにスタブアウトするRSpecテストを書こうとしています。私は#to_rack方法 永続的なHTTPClientを持つRails gemのスタブリクエスト
stub_request(:any, %r{^https?://api.box.com}).to_rack(FakeBox)
と私のFakeBoxクラスを使用して偽のBoxクラスに行くスタブを作成しました:
require 'sinatra/base'
class FakeBox < Sinatra::Base
post /oauth2/ do
debugger
content_type :json
status 200
'{ "access_token": "<some_token>", "expires_in": 3979, "restricted_to": [],' +
'"refresh_token": "<some_refresh>",' +
'"token_type": "bearer" }'
end
end
この偽物は私がNet::HTTP.get('https://api.box.com/oauth2/token')
または直接HTTPClient.new.post(...)
を呼び出すいつでもトリガされコントローラまたはテスト方法で使用します。
def self.auth_post(uri, body)
uri = Addressable::URI.encode(uri)
res = BOX_CLIENT.post(uri, body: body)
debugger
if(res.status==200)
body_json = Oj.load(res.body)
return BoxrMash.new(body_json)
else
raise BoxrError.new(status: res.status, body: res.body, header: res.header)
end
end
BOX_CLIENTはここで定義されています:
module Boxr
Oj.default_options = {:mode => :compat }
#The root folder in Box is always identified by 0
ROOT = 0
#HTTPClient is high-performance, thread-safe, and supports persistent HTTPS connections
#http://bibwild.wordpress.com/2012/04/30/ruby-http-performance-shootout-redux/
BOX_CLIENT = HTTPClient.new
BOX_CLIENT.cookie_manager = nil
BOX_CLIENT.send_timeout = 3600 #one hour; needed for lengthy uploads
BOX_CLIENT.agent_name = "Boxr/#{Boxr::VERSION}"
BOX_CLIENT.transparent_gzip_decompression = true
#BOX_CLIENT.ssl_config.add_trust_ca("/Users/cburnette/code/ssh-keys/dev_root_ca.pem")
def self.turn_on_debugging(device=STDOUT)
BOX_CLIENT.debug_dev = device
BOX_CLIENT.transparent_gzip_decompression = false
nil
end
def self.turn_off_debugging
BOX_CLIENT.debug_dev = nil
BOX_CLIENT.transparent_gzip_decompression = true
nil
end
end
デバッガが起動されると、私はBoxr宝石自体にデバッガを入れBoxr::get_tokens(params[:code])
を呼び出すときしかし、それがトリガされていない
私が得た応答は、BOX_CLIENT.post(uri, body: body)
がサイトを訪問し、私が模擬を引き起こすと予想したときにエラーを返すことを示しています。そのブレークポイントのデバッグコンソールで、HTTPClient.new.post(uri, body: body)
と入力し、私が期待していたスタブ付きの応答を得ました。
デバッガコンソールでHTTPClient.new.class
と入力したとき、私はWebMockHTTPClientを取得しました。 BOX_CLIENT.class
- > HTTPClient。これは私の問題の原因と思われます。
私は宝石を変更できません。誰もこの問題を解決する方法を知っていますか?
に
gem 'webmock', require: false
からrequire: false
を削除しなければならなかった私の推測では、stub_requestメソッドが呼び出される前にBOX_CLIENTが定義されていることなので、多分私は、セットアップパイプラインの後半で宝石をロードするためにどちらかの方法を把握する必要がありますまたは先にスタブに電話する? –