RSpec: 模拟 SFTP

10

我正在尝试从一个对象中存根出Net::SFTP。这是模型:

class BatchTask
  require 'net/sftp'

  def get_file_stream(host, username, password, path_to_dir, filename)
    raise ArgumentError if host.nil? or username.nil? or password.nil? or path_to_dir.nil? or filename.nil?
    file_stream = nil
    Net::SFTP.start(host, username, password) do |sftp|
      sftp.dir.glob(path_to_dir, filename) do |entry|
        # Verify the directory contents
        raise RuntimeError(true), "file: #{path_to_dir}/#{filename} not found on SFTP server" if entry.nil?
        file_stream = sftp.file.open("#{path_to_dir}/#{entry.name}")
      end
    end
    file_stream
  end

end

这是规范:

require 'spec_helper'

describe "SftpToServer" do
  let(:ftp) { BatchTask::SftpToServer.new }

 it "should return a file stream" do
    @sftp_mock = mock('sftp')
    @entry = File.stubs(:reads).with("filename").returns(@file)
    @entry_mock = mock('entry')
    @entry_mock.stub(:name).with("filename").and_return("filename")
    @sftp_mock.stub_chain(:dir, :glob).and_yield(@entry_mock)
    Net::SFTP.stub(:start).and_yield(@sftp_mock)
    @sftp_mock.stub_chain(:file, :open).with("filename").and_yield(@file)

    ftp.get_file_stream("ftp.test.com", "user", "password", "some/pathname", "filename").should be_kind_of(IO)
  end

end

以下是堆栈跟踪:

Spec::Mocks::MockExpectationError in 'SftpToServer should return a file stream'
Mock "entry" received :name with unexpected arguments
  expected: ("filename")
       got: (no args)
/Users/app/models/batch_task/sftp_to_server.rb:12:in `get_file_stream'
/Users/app/models/batch_task/sftp_to_server.rb:9:in `get_file_stream'
/Users/app/models/batch_task/sftp_to_server.rb:8:in `get_file_stream'
./spec/models/batch_task/sftp_to_server_spec.rb:15:

首先,我的方法是否正确?我想删除SFTP的功能,因为我们可以确信它已经经过了充分的测试。相反,我希望专注于确保“黑匣子”内部返回文件流。

其次,我如何正确地存根化sftp.file.open()以实现这一点?

提前感谢任何想法!

1个回答

12

首先,模拟sftp有两个好处:

  1. 你不需要编写sftp测试,只需专注于测试你所要测试的内容。
  2. 在测试中消除对网络的依赖 - 你不希望测试由于你无法控制的原因而失败。

至于错误,这是你当前的问题:

@entry_mock.stub(:name).with("filename").and_return("filename")

这里你正在为entry.name("filename")进行桩数据(stubbing),而不仅仅是entry.name

请将其更改为:

@entry_mock.stub(:name).and_return("filename")

让我知道你的进展情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接