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?

RSpecのallow(...).to receive(...)

Last updated at Posted at 2025-02-13

概要

特定のメソッドが呼ばれたときに、その戻り値を自由に制御できるようにするためのモック(stub)の機能。

sample1
# User.current メソッドが呼ばれたとき、常に current_user を返すようにする。
# allow(オブジェクト).to receive(:メソッド名).and_return(返り値)
allow(User).to receive(:current).and_return(current_user)

expect(...).to receive(...) との違い

  • allow(...).to receive(...)
    「こう動作してほしい」 という指定。
  • expect(...).to receive(...)
    「このメソッドが呼ばれることを期待する」 というもの。

使用例

sample2
class User
  def name
    "Alice"
  end
end

user = User.new
# name メソッドの戻り値を "Bob" に変更できる。
allow(user).to receive(:name).and_return("Bob")
# 通常、user.name を呼ぶと "Alice" を返す。
puts user.name # => "Bob"

戻り値を返さない

sample3
# .and_return()を記述しない
allow(obj).to receive(:method_name)

戻り値を複数指定する

sample4
# 1回目の呼び出し   : 1 
# 2回目の呼び出し   : 2 
# 3回目以降の呼び出し : 3 
allow(obj).to receive(:method_name).and_return(1, 2, 3)

戻り値を動的にする

sample5
# { Time.now.year - 1990 } で計算し、呼び出し時の Time.now に応じた値を返す。
allow(user).to receive(:age) { Time.now.year - 1990 }
puts user.age # => 34(2024年の場合)

例外を発生させる

sample6
# fetch_data を呼ぶと、強制的にエラーを発生。
allow(service).to receive(:fetch_data).and_raise("Test Error")
service.fetch_data # => RuntimeError: Test Error
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?