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 5 years have passed since last update.

メソッド内で生成されるインスタンスのメソッドをモックするには

0
Last updated at Posted at 2020-02-03

あるメソッドが、その中で他のクラスのインスタンスを生成してそのインスタンスメソッドが呼ばれることを確認したい。しかし、実際にそのメソッドを動かすとすごく時間がかかったりとか色々面倒なので呼ばれたことだけをテストしたい。

def exec_service(user)
  Service.new(user).start #このコードが呼ばれることをテストしたいが、実際に動作するのは困る
end

そこでメソッドをモックしたインスタンスを作成し、そのクラスのnewが必ずそのインスタンスを返すようにした。


example "exec_serviceを呼ぶとService.new(user).startが呼ばれる" do
    # 実際にstartが呼ばれないようにモックする
    @servise = Service::.new("user")                     # モックのServiceインスタンスを作成
    allow(@Service).to receive(:start)                   # モックのインスタンスのstartメソッドをモックして本来のメソッドが呼ばれないようにする
    allow(Service).to receive(:new).and_return(@servise) # Service.new がモックのインスタンスを返すようにする

    # 呼び出す
    exec_service("user")                                 

    # Service#startが呼ばれたことを確認
    expect(@servise).to have_received(:start).once
  end
end
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?