I’ve searched far and wide and I hope someone can answer this question. I’m using the following code to stub out the ‘exists?’ method for FileTest in an rspec spec:
it "returns no error if file does exist" do
@loader = MovieLoader.new
lambda {
FileTest.stub!(:exists?).and_return(true)
@loader.load_file
}.should_not raise_error("File Does Not Exist")
end
What I really want to do is to ensure that the existence of a very specific file is stubbed out. I was hoping something like this would do the job:
it "returns no error if file does exist" do
@loader = MovieLoader.new
lambda {
FileTest.stub!(:exists?).with(MovieLoader.data_file).and_return(true)
@loader.load_file
}.should_not raise_error("File Does Not Exist")
end
However, this doesn’t seem to be working. I am having a very difficult time finding documentation on what the ‘with’ method actually does. Perhaps I’m barking up the wrong tree entirely.
Can someone please provide some guidance?
The RSpec stubbing framework leaves a bit to be desired, and this is one of those things. The
stub!(:something).with("a thing")ensures that each time thesomethingmethod is called that it receives"a thing"as the input. If it receives something other than"a thing", RSpec will stop the test and report an error.I think you can achieve what you want, you’ll just have to approach this a little differently. Instead of stubbing out
FileTest, you should be stubbing out a method on your@loaderinstance, and that method would normally callFileTest.exists?. Hopefully this demonstrates what I’m getting at:Your test would then look like:
Now you are only stubbing one instance of the loader, so other instances will not inherit the stubbed version of
file_exists?. If you need to be more fine-grained than that, you’ll probably need to use a different stubbing framework, which RSpec supports (stubba, mocha, etc).