概要
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を利用する