0

How to mock this call in RSpec?

require 'open-uri'
class FileFoo < ActiveRecord::Base
  def download image_url
    open("tmp/#{file}", 'wb') do |file|
      file << open(image_url).read
    end
  end
end

Tried mocking FileFoo.open, but this did not work because I am using the downloaded file, not the return value.

Changed code to file << Kernel.open(image_url).read, and used the following:

Kernel.stub_chain(:open, :read).and_return(File.read image_fixture)

This works fine, but is there a way to mock Kernel.open().read, without calling Kernel explicitly?

2 Answers 2

2

Often times I think that a better test in this situation is not to mock specific filesystem calls, but instead stub out the filesystem with a gem like fakefs.

I talk more about it a blog post called Fake It!.

The idea is that stubbing specific filesystem calls is quite brittle, but writing to the actual filesystem is not necessarily desirable in a unit test either. Something like fakefs is a nice happy medium a lot of the time.

1

I think this is difficult because the design of the method download is poor. It is doing 2 things:

  1. Fetching the file via HTTP
  2. Saving it to disk

These separate functions should both be tested, and the first should be mocked. I don't see any reason to mock the filesystem because saving the file (which is small) is fast and easily tested.

If the method were broken into 2 methods, then:

  1. fetch with http would return the file.
  2. save file would save it.

This approach makes the mocking and testing simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.