RSpecのmockの使い方
APIクライアントを外から注入できるようにして、
モックを渡してローカル環境単体でテストできようにした例。
require 'spec_helper' class DummyService # # APIクライアントを外から指定できるようにして # 単体でテストできるようにする # def self.get_info(info_id, options = {}) api_client = options[:api_client] # || DummyApiClient res = api_client.get_info(info_id) res.body end end describe DummyService do describe :get_info do let(:api_client) { # モックの作成 _api_client = double("MockApiClient") # モックにメソッドを生やす allow(_api_client).to receive(:get_info).and_return( Struct.new(:body).new("TEST_DATA") ) _api_client } it 'モックで指定した値を返す' do info = DummyService.get_info('test', api_client: api_client) expect(info).to eq 'TEST_DATA' end end end