【问题标题】:Stubbing and mocking in Ruby rspecRuby rspec 中的存根和模拟
【发布时间】:2014-03-17 15:02:07
【问题描述】:

我想我了解这里发生的情况,但我想确认一下。

有些代码需要对 File 方法进行单元测试:

temp = File.new(uri.path)
@path = Rails.root.to_s + "/tmp/" +uri.path.split("/").last
File.open(@path, "w"){|f| f.write(temp.read)} if File.exists(temp)
temp.close

单元测试有:

file = mock(File)
File.stub(:new).and_return(file)
File.stub(:open).and_return(file)
file.stub(:close)

我猜File.stubfile.stub 之间的区别在于 File.stub 将存根 File 类上的方法,而 file.stubfile 是一个模拟 File 对象)将存根任何File 对象上的方法?

【问题讨论】:

    标签: ruby unit-testing rspec stub


    【解决方案1】:

    调用stub(:method) 将在你调用它的对象上存根方法。因此,您对File.stub(:new) 的调用将存根对 File.new(类方法)的所有调用。对 file.stub(:close) 的调用会将 所有调用 存根到 file.close 但仅在您调用存根的实例上

    如果您想存根对任何 File 实例的所有调用,您可以:

    1. 使用any_instance
    2. 或者您可以存根 File.new 以使其仅返回带有存根关闭的文件对象,就像您在中所做的那样:

      File.stub(:new).and_return(file)
      File.stub(:open).and_return(file)
      

    请注意,在案例 2 中,此后对 File.new 的每次调用都将返回相同的实例。如果这不是您想要的,您可以随时将一个块交给存根,您可以在其中为存根方法提供substitute

    【讨论】:

      【解决方案2】:

      你的理解是对的。

      File.stub(:new)
      

      在类 File 上存根调用 new

      file.stub(:close)
      

      file 对象上存根调用close

      在你的情况下,你也可以这样做

      file = mock(File, :close => nil) #this will create a mocked object that responds with nil when close is called
      

      【讨论】:

        猜你喜欢
        • 2012-07-27
        • 1970-01-01
        • 2020-08-31
        • 2019-02-16
        • 2021-12-31
        • 2013-08-04
        • 2014-09-11
        • 1970-01-01
        • 2023-03-26
        相关资源
        最近更新 更多