🖥

Rspec | Make a mock against hash

に公開

:[] Create a mock against :[] .

Example

 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 

result

 Mock Hash Test should eq "Over written!" 1 examples, 0 failures 

problem

However, in this way, the verification against b: and c: that are not mocking is angry. and_call_original problem is solved by using and_call_original .

Example

 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 

result

 Mock Hash Test should eq "Over written!" should eq 3 should eq 2 3 examples, 0 failures 

Supplement

In this case, "Make later" has higher priority for mocks. So and_return you reverse the lines of and_return and and_call_original , the verification will fail.

reference

environment

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

Original by

Rspec | ハッシュに対してのモックを作る

About

About this translattion

チャットメンバー募集

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

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-16

Discussion