ruby - 如何使用 rspec 删除特定文件?

标签 ruby ruby-on-rails-3 rspec stub

我查了很多资料,希望有人能回答这个问题。我正在使用以下代码来删除“存在吗?” 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”方法实际用途的文档。也许我完全找错了对象。

有人可以提供一些指导吗?

最佳答案

RSpec stub 框架还有一些不足之处,这就是其中之一。 stub!(:something).with("a thing") 确保每次调用 something 方法时它都会收到 "a thing" code> 作为输入。如果它收到除“a thing”之外的其他内容,RSpec 将停止测试并报告错误。

我认为你可以实现你想要的,你只需要稍微不同地处理这个问题。您应该在 @loader 实例上删除一个方法,而不是删除 FileTest,并且该方法通常会调用 FileTest.exists? 。希望这能证明我的意思:

class MovieLoader
  def load_file
    perform_loading if file_exists?(file_path)
  end

  def file_exists?(path)
    FileTest.exists? path
  end
end

您的测试将如下所示:

it "returns no error if file does exist" do
  @loader = MovieLoader.new
  lambda {
    @loader.stub!(:file_exists?).with(MovieLoader.data_file).and_return(true)
    @loader.load_file
  }.should_not raise_error("File Does Not Exist")
end

现在您只对加载程序的一个实例进行 stub 处理,因此其他实例将不会继承 file_exists? 的 stub 版本。如果您需要比这更细粒度,您可能需要使用 RSpec 支持的不同 stub 框架(stubba、mocha 等)。

关于ruby - 如何使用 rspec 删除特定文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9247095/

相关文章:

ruby - 将 C native 方法添加到预先存在的 Ruby 类

ruby - 中间人 - 构建时 CDN 的 Assets 路径

ruby - Ruby 解决方案中的 Project Euler #3 超时

ruby-on-rails - 当使用与有限列的关系时,包括仍然导致第二个数据库查询

ruby-on-rails-3 - Rails 3.1.1 中的静态页面和资源

ruby - Sinatra 的良好表单助手?

ruby-on-rails-3 - 抓取表格分页数据

ruby-on-rails - Capybara 和 Factorybot - 创建的数据没有出现

ruby-on-rails - 在 rails 初始化程序运行之前运行 rspec "before" block

ruby-on-rails - 未调用 RSpec Controller 测试失败方法