4
3

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 | メソッドチェーンの検証方法 ( expect_any_instance_of )

Last updated at Posted at 2015-11-27

素直な検証

Hash が to_a を呼ぶことを期待する。
このテストは成功する。

spec/hahs_to_array_spec.rb
require 'spec_helper'

describe  do
  it do
    expect_any_instance_of(Hash).to receive(:to_a)
    { name: 'John' }.to_a
  end
end

メソッドチェーンを検証できない

しかしメソッドチェーンを検証したい場合は、どうするのだろうか。

たとえば Hash.to_a.to_s と書いた時。
Hash に対して to_s を期待しても、ダメだ。

spec/hash_to_array_to_hash.rb
require 'spec_helper'

describe  do
  it do
    expect_any_instance_of(Hash).to receive(:to_s)
    { name: 'John' }.to_a.to_s
  end
end

なぜなら Hash.to_a した時点で、クラスは Array に変わっているからだ。

{ name: 'John' }.to_a.class # => Array

解決策

この場合 Array に対して to_s を期待すれば良い。

spec/hash_to_array_to_hash.rb
require 'spec_helper'

describe  do
  it do
    expect_any_instance_of(Array).to receive(:to_s)
    { name: 'John' }.to_a.to_s
  end
end

全て検証する

メソッドチェーンの全てを検証する場合は、この両方を期待すれば良い。

spec/hash_to_array_to_hash.rb
require 'spec_helper'

describe  do
  it do
    expect_any_instance_of(Hash).to receive(:to_a)
    expect_any_instance_of(Array).to receive(:to_s)
    { name: 'John' }.to_a.to_s
  end
end

環境

  • ruby 2.0.0
  • rspec-rails (2.14.2)

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?