7
5

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 | ハッシュに対してのモックを作る

Last updated at Posted at 2016-04-27

:[] に対してモックを作れば良い。

describe 'Mock Hash Test' do
  let(:hash) { { a: 1, b: 2, c: 3} }

  before do
    allow(hash).to receive(:[]).with(:a).and_return('Over written!')
  end

  it { expect(hash[:a]).to eq 'Over written!' }
end

結果

Mock Hash Test
  should eq "Over written!"

1 examples, 0 failures

問題点

ただし、このやり方だと、モックを作っていない b:c: に対しての検証は怒られる。
and_call_original を使えば問題は解決だ。

describe 'Mock Hash Test' do
  let(:hash) { { a: 1, b: 2, c: 3} }

  before do
    allow(hash).to receive(:[]).and_call_original
    allow(hash).to receive(:[]).with(:a).and_return('Over written!')
  end

  it { expect(hash[:a]).to eq 'Over written!' }
  it { expect(hash[:b]).to eq 2 }
  it { expect(hash[:c]).to eq 3 }
end

結果

Mock Hash Test
  should eq "Over written!"
  should eq 3
  should eq 2

3 examples, 0 failures

補足

この場合、モックは「後から作られた方」が優先順位が高い。
なので and_returnand_call_original の行を逆にすると、検証は失敗する。

参考

環境

  • rspec (3.4.0)
    • rspec-core (3.4.4)
    • rspec-mocks (3.4.1)
    • rspec-rails (3.4.2)

チャットメンバー募集

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

メンター受付

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?