LoginSignup
10
0

More than 1 year has passed since last update.

Faraday 2からアダプターの扱いが変わった (Faraday::Adapter::Test::Stubs::NotFound)

Last updated at Posted at 2021-12-10

追記:

v2.0.1でfaraday-net_httpが再度追加され、デフォルトのアダプターとして使用されるようになったため、この記事で説明していたエラーは発生しなくなりました。 (@ryy さんありがとうございます)

https://github.com/lostisland/faraday/releases/tag/v2.0.1


初めに

Faraday 2がアルファリリースされており、動作を検証してみたところ以下のようなエラーが発生しました。

no stubbed request for get http://localhost:4567/  (Faraday::Adapter::Test::Stubs::NotFound)

Faradayのバージョン: v2.0.0.alpha-3

結論

UPGRADING.md (v2.0.0.alpha-3) を見る

具体的には、

  • アダプターがFaradayのcoreから外れたので、別途gemのインストールが必要
  • デフォルトアダプターが :test になっているので、自身で設定する必要がある
require 'faraday'
+ require 'faraday/net_http'

+ Faraday.default_adapter = :net_http
conn = Faraday.new(url: 'http://localhost:4567') do |f|
  f.response(:logger)
end
Gemfile
gem 'faraday', '2.0.0.alpha-3'
+ gem 'faraday-net_http', '2.0.0.alpha-2'

解説

Faraday v1で以下のようなコードを書いていました。このままFaradayのバージョンを2.0.0.alpha-3に上げてみます。

require 'faraday'

conn = Faraday.new(url: 'http://localhost:4567') do |f|
  f.response(:logger)
end

response = conn.get('/')

すると、上で記載したようにこのようなエラーが出ました。

no stubbed request for get http://localhost:4567/  (Faraday::Adapter::Test::Stubs::NotFound)

default_adapterの設定

これは以下のような変更が入ったためです。

-    #   for the default {Faraday::Connection}. Defaults to `:net_http`.
+    #   for the default {Faraday::Connection}. Defaults to `:test`.
    #   @return [Symbol] the default adapter
    # @overload default_adapter=(adapter)
    #   Updates default adapter while resetting {.default_connection}.
@@ -150,5 +150,5 @@ def method_missing(name, *args, &block)
  self.ignore_env_proxy = false
  self.root_path = File.expand_path __dir__
  self.lib_path = File.expand_path 'faraday', __dir__
-  self.default_adapter = :net_http
+  self.default_adapter = :test
end

今までは:net_httpがdefault_adapterでしたが、:testに変わっています。これにより、今までは:net_httpを特に設定せずに使っていたのですが、別途default_adapterの設定が必要になります。

require 'faraday'

+ Faraday.default_adapter = :net_http
conn = Faraday.new(url: 'http://localhost:4567') do |f|
  f.response(:logger)
end

しかしまた以下のようなエラーが出ます。

`lookup_middleware': :net_http is not registered on Faraday::Adapter (Faraday::Error)

アダプターのインストール

UPGRADING.mdにあるようにfaraday-net_httpをGemfileに追加する必要があります。これは、メンテナンスをしやすくするために、Faradayのコアからアダプターが除外されたためです。

そのため、Gemfileへの追加をし、インストールします。

Gemfile
gem 'faraday', '2.0.0.alpha-3'
+ gem 'faraday-net_http', '2.0.0.alpha-2'

そしてfaraday/net_httpをrequireすると動くようになります。

require 'faraday'
+ require 'faraday/net_http'

Faraday.default_adapter = :net_http
conn = Faraday.new(url: 'http://localhost:4567') do |f|
  f.response(:logger)
end
10
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
0