RSpec `should_receive` behavior with multiple method calls

Consider the following test:

class A def print(args) puts args end end describe A do let(:a) {A.new} it "receives print" do a.should_receive(:print).with("World").and_call_original a.print("Hello") a.print("World") end end 

RSpec Documentation says:

Use the should_receive () function to set what the recipient should receive before this example completes.

So, I expected this test to pass, but it is not. It does not work with the following message:

 Failures: 1) A receives print Failure/Error: a.print("Hello") #<A:0x007feb46283190> received :print with unexpected arguments expected: ("World") got: ("Hello") 

Is this the expected behavior? Is there any way to pass this test?

I am using ruby 1.9.3p374 and rspec 2.13.1

+4
source share
4 answers

This should work:

 class A def print(args) puts args end end describe A do let(:a) {A.new} it "receives print" do a.stub(:print).with(anything()) a.should_receive(:print).with("World").and_call_original a.print("Hello") a.print("World") end end 

The test failed because you set the exact expectation: "a should receive: print with" World ", but rspec noticed that the object was receiving the print method with" Hello ", so it did not pass the test. In my solution, I allow the print method to call with any argument, but it still tracks the call with the argument "World".

+4
source

How about this?

 class A def print(args) puts args end end describe A do let(:a) {A.new} it "receives print" do a.should_receive(:print).with("World").and_call_original # it important that this is after the real expectation a.should_receive(:print).any_number_of_times a.print("Hello") a.print("World") end end 

It adds a second expectation, which you might want to avoid. However, given the @vrinek question, this solution has the advantage that it contains the correct error message (expected: 1 time, received: 0 time). Hooray!

+2
source

How to add allow(a).to receive(:print) ?

 require 'rspec' class A def print(args) puts args end end describe A do let(:a) { described_class.new } it 'receives print' do allow(a).to receive(:print) expect(a).to receive(:print).with('World') a.print('Hello') a.print('World') end end 

In principle, allow(a).to_receive(:print) allows "a" to receive a "print" message with any arguments. Thus, a.print('Hello') does not complete the check.

+1
source

should_receive not only checks that the expected method has been called, but unexpected methods are not called. Just add a specification for each call you expect:

 class A def print(args) puts args end end describe A do let(:a) {A.new} it "receives print" do a.should_receive(:print).with("World").and_call_original a.should_receive(:print).with("Hello").and_call_original a.print("Hello") a.print("World") end end 
0
source

Source: https://habr.com/ru/post/1488099/


All Articles