Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test file creation with RSpec?

I have a simple FileCreator Ruby class that has 1 method create which creates a blank txt file on my desktop. Using RSpec, how would I test this create method to make sure that the file was created, without having to create the file? Would I use RSpec::Mocks? Can someone please point me in the right directory? Thanks! enter image description here

like image 466
ab217 Avatar asked Feb 02 '11 02:02

ab217


People also ask

How do I run a RSpec test on a file?

Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.

What is RSpec testing?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.

What RSpec method is used to create an example?

The it Keyword. The word it is another RSpec keyword which is used to define an “Example”. An example is basically a test or a test case. Again, like describe and context, it accepts both class name and string arguments and should be used with a block argument, designated with do/end.

Is RSpec TDD or BDD?

RSpec is a Behavior-Driven Development tool for Ruby programmers. BDD is an approach to software development that combines Test-Driven Development, Domain Driven Design and Acceptance Test-Driven Planning. RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD.


2 Answers

After calling file_creator.create(100) you could search the folder for all File*.txt files and make sure the count matches. (Make sure to have your spec remove the test files after completion).

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

Using Mocks: You could do something like this to verify that the File.open method is actually being called (to test that the files actually get created, though, you may want to consider actually creating the files like the first half of my answer).

File.should_receive(:open).exactly(100).times
like image 156
Dylan Markow Avatar answered Nov 14 '22 22:11

Dylan Markow


You could also try using something like FakeFS which mocks the actual file system.

like image 33
charlesdeb Avatar answered Nov 14 '22 21:11

charlesdeb