How to stub File.read in RSpec 3 [RAILS, TDD]?


 

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 ?

data = {:name => "test" , :description => "test"}.to_json
allow(File).to receive(:read).and_return(data)

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

Advertisements

About Anatoly Spektor

My name is Anatoly Spektor (originally Anatolijs Spektors) I am Software and Web Developer. I have worked in Seneca Center for Development of Open Technology on Big Blue Button Add-on - Polling Module, Red Hat and some other places :) I am an author of the book 'Eclipse Debugging How To', Muay Thai fighter and amateur photographer ;)
This entry was posted in Programming Languages, Rails, Rspec and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s