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 1 year has passed since last update.

Rspec | Make a mock against hash

Last updated at Posted at 2019-04-16

:[] 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オープンチャットもご利用ください。

Twitter

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?