0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【RSpec】モックを使用したテスト

Posted at

##環境
Ruby 3.0.2
Rails 6.1.4.1

##モックを使ったテスト

spec.rb
describe 'XXXXX:XXXX' do
  #モックを作成
  let(:slack_client_mock) { double('slack client mock') }
  subject(:task) { Rake.application['XXXXX:XXXX'] }

  before do
    #chat_postMessageメソッドが呼ばれたらモックを返すように実装を書き換える
    allow(::Slack::Web::Client).to receive(:new).and_return(slack_client_mock)
    allow(slack_client_mock).to receive(:chat_postMessage).and_return(true)
  end
  
  it 'モックのテスト' do
    expect(slack_client_mock.chat_postMessage).to eq(true)
    subject
  end
end

##ポイント

  • allow(モック).to receive(:メソッド名).and_return(hogehoge)
    モックがメソッドを実行したときに何が返るかをand_returnで設定

  • モックの設定はbeforeの中に書いたほうがテストの見通しがよくなる

##参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?