Entering a Mock File as a File Path on Rspec

I have a question on how to use rspec to fake file input. I have the following code for the class, but I don’t know exactly why to mock the file. filepath /path/to/the/file

I did a search on Google and it usually turns out that it loads the actual file and not mock, but in fact I look at the opposite, where only the layout but not the actual file is used.

 module Service class Signing def initialize(filepath) @config = YAML.load_file(filepath) raise "Missing config file." if @config.nil? end def sign() … end private def which() … end end end 

Can I use the EOF delimiter to enter this file?

 file = <<EOF A_NAME: ABC A_ALIAS: my_alias EOF 
+4
source share
2 answers

You can YAML.load_file and return the processed YAML from your text, for example:

 yaml_text = <<-EOF A_NAME: ABC A_ALIAS: my_alias EOF yaml = YAML.load(yaml_text) filepath = "bogus_filename.yml" YAML.stub(:load_file).with(filepath).and_return(yaml) 

This does not completely exhaust the file download, but for this you will have to make assumptions about what YAML.load_file does under the covers, and this is not a good idea. Since it is safe to assume that the YAML implementation has already been tested, you can use the code above to replace the entire call with text parsing.

If you want to verify that the correct file name is passed to load_file , replace the stub with a wait:

 YAML.should_receive(:load_file).with(filepath).and_return(yaml) 
+3
source

If the idea is to attach some kind of expectation, I don't see much benefit from this approach of calling YAML.load to fake a return. YAML.load_file actually returns a hash, so instead of doing all that my suggestion would just return a hash:

 parsed_yaml = { "somekey" => { "someotherkey" => "abc" } } YAML.should_receive(:load_file).with(filepath).and_return(parsed_yaml) 

This is supposed to be a unit test, not an integration test, I think it will make more sense.

+1
source

All Articles