コピペコードで快適生活

明日使えるソースを自分のために

RSpecで既存のクラスをモックに差し替える

本来はDependencyInjectionでやるべきかもだけど。 そうもいかないケースもあるわけで。

# 既存クラス
let(:api_client) { ::MyApp::ApiClient }
let(:api_response) { double('api_response', status: 200) }

# post_xxxメソッドを上書きして、api_responseを返す
allow(api_client).to receive(:post_xxx).and_return(api_response)

# post_xxxメソッドを上書きして、例外をraiseする
allow(api_client).to receive(:post_xxx).and_raise(::MyApp::MyApp::BadRequest)