1
2

More than 3 years have passed since last update.

WebMockを使って外部API接続をスタブ化する

Posted at

概要

APIはJavaで実装して、Javaから返ってきたjsonをRailsで受け取ってRails側でそのjsonデータを表示するという流れにしたく、Railsの実装をしている時のテストや、いちいちJavaを起動させなくていいようにスタブ化したのが目的です。

Rails開発でWebMockを使ってAPIアクセスをスタブ化するからのコードを引っ張ってきただけなので、リンク先の解説みた方が断然わかりやすいです。

実際のコード

api_stub.rb
module ApiStub
  require 'webmock'

  WebMock.enable!
  # アプリケーションコードに`call_get_api`という名称の外部API呼び出し実装を含むメソッドがあることして、ここで同名のメソッドを作成してstub登録します。
  def call_get_api
    WebMock.stub_request(:any, "http://www.example.com/").to_return(
        body: File.read("#{Rails.root}/test/fixtures/stub_api_response.json"),
        status: 200,
        headers: { 'Content-Type' =>  'application/json' })
    super # アプリケーションコードの実装を呼び出す
  end
end
api_module.rb
module ApiModule
  require_relative 'api_stub'
  prepend ApiStub if ENV["APIMODE"] == "mock" && Rails.env.development?

  def call_get_api
    # ここに本来の外部API呼び出しの実装が入る
  end
end
api_client.rb
class ApiClient
  require_relative 'api_module'
  include ApiModule
end
web_controller.rb
class WebController < ApplicationController

  require './lib/externals/api_client'
  require 'net/http'

  def fetch
    client = ApiClient.new
    client.call_get_api
    res = Net::HTTP.get("www.example.com", "/")
    @result = JSON.parse(res)
  end
end

脱線 スタブとモックの違い

スタブは受信メッセージのテストのために使うためのもの。
モックは送信メッセージのテストのために使うもの。

参照

Rails開発でWebMockを使ってAPIアクセスをスタブ化する
Ruby on RailsでWebMockを利用する

1
2
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
1
2