[英]Stuck with Faraday in rspec
我正在嘗試使用 Faraday 和 RSpec 編寫一個調用 API 的測試。 調用在 .execute 方法中,它在生產中正常工作,但在測試中,我遇到了這個錯誤:
Failure/Error: @response ||= conn.post '/oauth/token', @params
Faraday::ConnectionFailed:
Failed to open TCP connection to :80 (Connection refused - connect(2) for nil port 80)
而測試是這樣的
it 'access_token should not be nil' do
@auth = AuthenticateService.new(params)
auth_exec = @auth.execute
access_token = auth_exec[:access_token]
expect(access_token.present?).not_to be_empty
end
我是否需要配置一些東西才能使法拉第與測試一起工作?
它實際上是在嘗試調用外部請求。 在您的情況下,有兩種解決方案:
before do
allow_any_instance_of(AuthenticateService).to receive(:execute).and_return(access_token: 'some token')
end
你可以試試 gem vcr 。 它將您的外部請求記錄到
cassette
並在規范運行時播放。
干杯!
因為在測試模式下,您確實設置了url
,所以我可以在我的 pry 控制台中重播確切的錯誤:
> conn = Faraday.new();
> conn.post '/oauth/token';
Faraday::ConnectionFailed: Connection refused - connect(2) for nil port 80
from /home/fangxing/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:879:in `initialize'
我想在你的項目中某處,為法拉第配置了一個變量url
,而你沒有在測試模式下配置它。
還有一個叫做 Webmock 的東西,它模擬 API 調用並返回一個你預定義的響應。 你應該調查一下!
我比 VCR 更喜歡它,它在處理大量數據或多個 API 調用時可能會很糟糕。
我對類似問題的解決方案:
stub_request(method, url).with(
headers: { 'Authorization' => /Basic */ }
).to_return(
status: status, body: 'stubbed response', headers: {}
)
您可以通過替換來加強驗證:
/Basic */ -> "Basic #{your_token}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.