How to check file creation using RSpec?

I have a simple FileCreator Ruby class that has 1 create method that creates an empty text file on my desktop. Using RSpec, how can I check this creation method to make sure the file was created without creating the file? Do I use RSpec::Mocks ? Can someone point me in the correct directory? Thank you enter image description here

+4
source share
3 answers

After calling file_creator.create(100) you can search the folder for all File*.txt files and make sure the counter matches. (Make sure your spec has deleted the test files after completion).

 Dir.glob(File.join(File.expand_path("~/Desktop"), "File*.txt")).length.should == 100 

Using Mocks: you can do something like this to make sure the File.open method File.open actually called (to check if the files are actually created, however, you might want to consider creating files like the first half of my answer).

 File.should_receive(:open).exactly(100).times 
+7
source

You can also try using something like FakeFS that mocks the actual file system.

+2
source

The easiest way to do this:

 FileCreator.count.should eq 100 
0
source

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


All Articles