LoginSignup
0
0

More than 1 year has passed since last update.

rspecにおけるstubとは

Posted at

stubについて

  • 環境設定
Ruby ver
2.7.2
Rails ver
5.2.6
Gem
active_model_serializer

stubの説明

sutbは,

  • rspecのテストで使用し、

  • あるクラスで定義したメソッドをデータベースを使用せずに使うこと

ができる。


具体例

以下のcontrollerにあるメソッドを呼び出すとする。

api_controller.rb

#データベースから一番最初のユーザーを呼び出し、ログインユーザー(current_user)とする。
class Api::V1::ApiController < ActionController::Base
  def current_user
    @current_user ||= User.first
  end  
end

呼び出し先は、articles_spec.rbだとする。

articles_spec.rb

#allow_any_instance_ofはcurrent_userメソッドの呼び出しで、current_userを強制的に返す
before do
  allow_any_instance_of(Api::V1::ApiController).to receive(:current_user).and_return(current_user)
end

上記コードを使用すれば、article_spec.rb内でスタブ化されたcurrent_userメソッドを使用できる。

参考にしたサイト

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