Ruby 通缉:编写匿名类代码以进行模拟的最优雅的方法

Ruby 通缉:编写匿名类代码以进行模拟的最优雅的方法,ruby,mocking,minitest,Ruby,Mocking,Minitest,我在模拟Net::SFTP的一部分进行测试。通过从fixture\u path本地读取,以下内容模拟dir.entries、entry.name和entry.attributes.size: class MockedSFTP mattr_accessor :fixture_path def dir Class.new do def entries(path) MockedSFTP.fixture_path.join(path.sub(%r{^/}, '

我在模拟Net::SFTP的一部分进行测试。通过从
fixture\u path
本地读取,以下内容模拟
dir.entries
entry.name
entry.attributes.size

class MockedSFTP
  mattr_accessor :fixture_path
  def dir
    Class.new do
      def entries(path)
        MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
          OpenStruct.new(
            name: child.basename,
            attributes: OpenStruct.new(size: child.size)
          )
        end
      end
    end.new
  end
end
另一种选择是:

class MockedSFTP
  mattr_accessor :fixture_path
  def dir
    object = Object.new
    def object.entries(path)
      MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
        OpenStruct.new(
          name: child.basename,
          attributes: OpenStruct.new(size: child.size)
        )
      end
    end
    object
  end
end
两个版本都非常好用,但是,我不喜欢它们中的任何一个。
Class.new do。。。新的
很难看,我不喜欢
object=object.new。。。;对象
代码


有第三种方法写这个吗?

实际声明类怎么样

class MockedSFTP

  mattr_accessor :fixture_path

  class Dir
    def entries(path)
      MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
        OpenStruct.new(
          name: child.basename,
          attributes: OpenStruct.new(size: child.size)
        )
      end
    end
  end

  def dir
    Dir.new
  end
end

这是我的第一枪,但它更详细。我在寻找一种更“匿名”的方法。