LoginSignup
10
6

More than 5 years have passed since last update.

Faradayを使ったプログラムをRspecでテスト(Railsでない)

Posted at

Faradayを使ったプログラムをRSpecでテストする際に、どうテストコードを書いたら良いのかわからずに詰まってしまったので、その時のメモ。

結論としては2つ。
* Faradayにはテストを意識したスタブ作成用のクラスが用意されているのでそれを使う。
* RSpecでFaradayのconnectionを取得する箇所を差し替える。

サンプル

Faradayを使う普通のrubyクラス。これがテスト対象


require "faraday"

class TestFaraday
  def get
    con = connection
    res = con.get('http://google.co.jp')
    res
  end

  private
  def connection
    Faraday.new
  end
end

次に上のクラスをテストするテストケース

require 'json'
require_relative '../test_faraday.rb'

describe 'test faraday spec' do

  let!(:test_faraday) do
    # ここでスタブの定義
    stub_con = Faraday.new do |conn|
      conn.adapter :test, Faraday::Adapter::Test::Stubs.new do |stub|
        stub.get('http://google.co.jp') do
          # 左からstatus code, response_header, response body
          [200, {}, {id: 3, foo: "bar"}.to_json ]
        end
      end
    end

    # TestFaraday内のconnectionメソッドの返却値をスタブに差し替える
    instance = TestFaraday.new
    allow(instance).to receive(:connection).and_return(stub_con)
    return instance
  end

  it 'faraday test' do
    res = test_faraday.get
    expect(res.status).to eq 200
    json = JSON.parse res.body
    expect(json['id']).to eq 3
    expect(json['foo']).to eq "bar"
  end
end

参考

公式
Faraday の スタブテスト

10
6
0

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
6