Question: How to use different parameter values in an RSpec mock/stub?


How to use different parameter values in an RSpec mock/stub?

Answers 1
Added at 2016-12-31 09:12

My program downloads a zip file from the web then parses it. The relevant parsing-related code is:"") do |zip_file|
  # do stuff

In my RSpec test environment, I'd like to stub this code to parse a fake/mock file instead of the real one. Specifically, I'd like to replace the parameter value "" with "".

I tried the following approach:

allow(Zip::File).to receive(:open).and_return(""))

... but this prevents execution of code inside the block (# do stuff). I don't want the mock file contents to be returned by the method, but rahter to be assigned to the value of zip_file for further use. How can this be achieved?

nr: #1 dodano: 2016-12-31 11:12

Here's what you want to do:

mock_file ='')
allow(Zip::File).to receive(:open) { |&block| }

What you're doing here is yielding a value to the block in your original code. The problem with simply returning a scalar value is that it doesn't yield anything to your block so it won't be called. Note that I'm opening the mock file before putting in the message expectation since it would also intercept your call to and cause a nice stack overflow.

More information:'s-block

Source Show
◀ Wstecz