Just do IT

思うは招く

Minitest でヘルパーをつくる

Web APIからデータを取得する箇所をテストするとき、webmock を使ってスタブ登録したものをモデルテストやシステムテストで使い回したかった。

RSpec だと spec/support ディレクトリをつくり、api_helper.rb などのファイルを生成して設定できる。

RSpecでヘルパーを作成する方法 | ウェブ系ウシジマくんのテックブログ

「同じことを Minitest だとどう書けばいいのかな〜?」と思ってたら、ほぼ同じだったので手順をメモする。

前提

手順

#supportsディレクトリをつくる
mkdir test/supports

#stub_helper.rb ファイルをつくる(名前は適当)
touch test/supports/stub_helper.rb

stub_helper.rb

module StubHelper
  def stub_amazon!
    json = File.read("#{Rails.root}/test/fixtures/amazon.json")
    stub_request(:post, "https://webservices.amazon.co.jp/paapi5/getitems")
      .to_return(status: 200, body: json)
  end
end

補足:

  • moduleを定義する
  • test/fixtures/amazon.json ファイルを作って、あらかじめAPIレスポンスを記述してある
  • stub_request は webmock の機能

test_helper.rb

ENV['RAILS_ENV'] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
require "webmock/minitest" #追記
require "supports/stub_helper" #追記

WebMock.allow_net_connect! #追記

class ActiveSupport::TestCase
  # Run tests in parallel with specified workers
  parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
  include StubHelper #追記
end

補足:

  • require "supports/stub_helper"をしないと読み込めないので注意
  • include StubHelperでテスト内のどこからでも使えるようになる

あとはモデルテストなり、システムテストなり、使いたいところでstub_amazon!を記述すればスタブ登録したものが使える。