2012-07-31 43 views
1

我試圖在模型中存儲SFTP。這裏的模型:RSpec:stubbing 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).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 

這裏的堆棧跟蹤:

NoMethodError in 'SftpToServer should return a file stream' 
private method `open' called for #<Object:0x10c572620> 
/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: 

我GOOGLE了這一點,但我想不出爲什麼RSpec的將治療sftp.file.open作爲私有方法...

在此先感謝您的任何想法!

回答

1

因此,我想到了發生了什麼 - 我沒有將open()方法描述爲@sftp_mock對象的一部分,因此@ sftp.file.open看起來像一個私有方法。修復此需要具有@ sftp_mock.file回報@sftp_mock,以便它可以被鏈接到open()方法是這樣的:

@sftp_mock.stub!(:file) { @sftp_mock } 
@sftp_mock.should_receive(:open).with("some/pathname/filename").and_return(@file) 

我也錯過了@file聲明...完整的規範文件:

require 'spec_helper' 

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

it "should return a file stream" do 
    @file = File.new("#{RAILS_ROOT}/spec/files/express_checkout_tdr.csv", "r") 
    @sftp_mock = mock('sftp') 
    @entry = File.stubs(:reads).with("filename").returns(@file) 
    @entry_mock = mock('entry') 
    @entry_mock.stub(:name).and_return("filename") 
    @sftp_mock.stub_chain(:dir, :glob).and_yield(@entry_mock) 
    Net::SFTP.stub(:start).and_yield(@sftp_mock) 
    @sftp_mock.stub!(:file) { @sftp_mock } 
    @sftp_mock.should_receive(:open).with("some/pathname/filename").and_return(@file) 

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

end 

這個計算器等問題,幫我這一概念:Stub chain together with should_receive

而且,隨意評論,如果有更好的方式來嘲弄和存根出SFTP。這個規範例子變得有點醜陋!