質問

タイトルで申し訳ありません、私は今もっと良いことを思い付くのにイライラしています。

私は一般的なJudgeを持っています。この stats メソッドは、APIにGETリクエストを送信し、応答としていくつかのデータを取得することになっています。私は実際の要求を実行しないように、これをテストして統計メソッドをスタブしようとしています。これが私のテストのようなものです:

describe Judge do
  describe '.stats' do

    context 'when success' do
      subject { Judge.stats }

      it 'returns stats' do
        allow(Faraday).to receive(:get).and_return('some data')

        expect(subject.status).to eq 200
        expect(subject).to be_success
      end
    end
  end
end
.

これは私がテストしているクラスです:

class Judge

  def self.stats
    Faraday.get "some-domain-dot-com/stats"
  end

end
.

これは現在私にエラーを与えます:#stats それでは、あなたはファラデーとどのようにしてスティブしますか?私は:

のような方法を見ました
    stubs = Faraday::Adapter::Test::Stubs.new do |stub|
      stub.get('http://stats-api.com') { [200, {}, 'Lorem ipsum'] }
    end
.

しかし、私はそれを正しい方法で適用することはできません。私は何がここにありませんか?

役に立ちましたか?

解決

faraday.newはファラデーではなくFaraday :: Connectionのインスタンスを返します。だからあなたは

を使ってみることができます
allow_any_instance_of(Faraday::Connection).to receive(:get).and_return("some data")
.

Faraday :: Connection.GetはResponseオブジェクトを返すため、文字列の代わりにボディとステータスコードを返す場合があります。あなたはこのようなものを試すかもしれません:

allow_any_instance_of(Faraday::Connection).to receive(:get).and_return(
   double("response", status: 200, body: "some data")
)
.

これはあなたがfaraday.new

から戻ってきたクラスを示すレールコンソールです。
$ rails c
Loading development environment (Rails 4.1.5)
2.1.2 :001 > fara = Faraday.new
 => #<Faraday::Connection:0x0000010abcdd28 @parallel_manager=nil, @headers={"User-Agent"=>"Faraday v0.9.1"}, @params={}, @options=#<Faraday::RequestOptions (empty)>, @ssl=#<Faraday::SSLOptions (empty)>, @default_parallel_manager=nil, @builder=#<Faraday::RackBuilder:0x0000010abcd990 @handlers=[Faraday::Request::UrlEncoded, Faraday::Adapter::NetHttp]>, @url_prefix=#<URI::HTTP:0x0000010abcd378 URL:http:/>, @proxy=nil>
2.1.2 :002 > fara.class
 => Faraday::Connection
.

他のヒント

Faradayクラスには、getメソッドがありません。インスタンスのみが実行します。あなたがクラスメソッドでこれを使用しているので、あなたができることはこのようなものです:

class Judge
  def self.stats
    connection.get "some-domain-dot-com/stats"
  end

  def self.connection=(val)
    @connection = val
  end

  def self.connection
    @connection ||= Faraday.new(some stuff to build up connection)
  end
end
.

テストでは、二重を設定するだけです。

let(:connection) { double :connection, get: nil }
before do
  allow(connection).to receive(:get).with("some-domain-dot-com/stats").and_return('some data')
  Judge.connection = connection
end
.

Faraday::Adapter::Test::StubsでのFaraday does not implement: getエラーに同じ問題になりました。

のように、Faradayアダプタにstubsを設定する必要があるようです。
  stubs = Faraday::Adapter::Test::Stubs.new do |stub|
    stub.get("some-domain-dot-com/stats") { |env| [200, {}, 'egg'] }
  end

  test = Faraday.new do |builder|
    builder.adapter :test, stubs
  end

  allow(Faraday).to receive(:new).and_return(test)

  expect(Judge.stats.body).to eq "egg"
  expect(Judge.stats.status).to eq 200
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top