如何使用 rspec 删除特定文件?
我进行了广泛的搜索,希望有人能回答这个问题。我正在使用以下代码来删除“存在吗?” rspec 规范中 FileTest 的方法:
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
我真正想做的是确保删除一个非常特定的文件的存在。我希望这样的事情能够完成这项工作:
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
但是,这似乎不起作用。我很难找到有关“with”方法实际用途的文档。也许我完全找错了对象。
有人可以提供一些指导吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
RSpec 存根框架还有一些不足之处,这就是其中之一。
stub!(:something).with("a thing")
确保每次调用something
方法时它都会收到"a thing"
code> 作为输入。如果它收到除“a thing”
以外的内容,RSpec将停止测试并报告错误。我认为你可以实现你想要的,你只需要稍微不同地处理这个问题。您应该在
@loader
实例上删除一个方法,而不是删除FileTest
,并且该方法通常会调用FileTest.exists?
。希望这能证明我的意思:您的测试将如下所示:
现在您仅存根加载程序的一个实例,因此其他实例将不会继承
file_exists?
的存根版本。如果您需要比这更细粒度,您可能需要使用 RSpec 支持的不同存根框架(stubba、mocha 等)。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 thesomething
method 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@loader
instance, 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).