Last active
June 15, 2016 22:51
-
-
Save katoy/5bf50d9d4d8a0c16bcb43a15dd119b06 to your computer and use it in GitHub Desktop.
rspec の mock の例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See | |
# http://qiita.com/jnchito/items/640f17e124ab263a54dd | |
require 'spec_helper' | |
class WeatherBot | |
def tweet_forecast | |
twitter_client.update '今日は晴れです' | |
rescue => e | |
notify(e) | |
end | |
def twitter_client | |
Twitter::REST::Client.new | |
end | |
def notify(error) | |
# (エラーの通知を行う。実装は省略) | |
end | |
def task | |
system('pwd') | |
system('ls -al') | |
end | |
end | |
describe WeatherBot do | |
it 'エラーなく予報をツイートすること' do | |
# Twitter clientのモックを作る | |
twitter_client_mock = double('Twitter client') | |
# updateメソッドが呼びだせるようにする | |
expect(twitter_client_mock).to receive(:update) | |
weather_bot = WeatherBot.new | |
# twitter_clientメソッドが呼ばれたら上で作ったモックを返すように実装を書き換える | |
expect(weather_bot).to receive(:twitter_client).and_return(twitter_client_mock) | |
expect { weather_bot.tweet_forecast }.not_to raise_error | |
end | |
it 'エラーが起きたら通知すること' do | |
twitter_client_mock = double('Twitter client') | |
# updateメソッドが呼ばれたらエラーを発生させる | |
expect(twitter_client_mock).to receive(:update).and_raise('エラーが発生しました') | |
weather_bot = WeatherBot.new | |
allow(weather_bot).to receive(:twitter_client).and_return(twitter_client_mock) | |
# notifyメソッドが呼ばれることを検証する | |
expect(weather_bot).to receive(:notify).once | |
expect(weather_bot.tweet_forecast) | |
end | |
it 'task() でコマンド (pwd, ls-al)が実行される。ls は実行されない。' do | |
weather_bot = WeatherBot.new | |
# expect(Kernel).to receive(:system).with('ls -al').and_return(true) | |
expect(weather_bot).to receive(:system).with('ls -al').and_return(true).once | |
expect(weather_bot).to receive(:system).with('pwd').and_return(true).exactly(1).times | |
expect(weather_bot).to receive(:system).with('ls').and_return(true).exactly(0).times | |
expect(weather_bot.task) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment