Stub (mock) File.read in RSpec 3

 

Recently, I have been doing whole bunch of spec rewriting from RSpec 2 to Rspec 3. As a result I have found that documentation is not that straightforward, and some cases you need to really spend time and figure out yourself. So I’ll be posting some cases that I have not been able to find in docs, just as notes for myself, and hopefully it will be useful for someone else.

 

Use Case:

I have JSON file that I need to read, and I already have tests that this JSON file opens properly.  I also have a Validator that looks for certain patterns keys in this JSON file. Validator leaves separately from the main app, and I don’t want to replicate File Upload -> File Save to Cloud -> File Open in my Validator Tests, I just want on every File.read to return certain data, and it does not matter to me what exactly is being read, and if path exists or not.

How would I do it in Rspec ?

What does it give you ?

It looks for every File.read in the scope of your spec and instead of actually reading file returns ‘data‘ every time.

Cool, huh ?

:)

Anatoly

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Related Posts

Join the Discussion

Your email address will not be published. Required fields are marked *

arrow