测试:使用自我,预期:1次接收参数:0次



我当前正在为使用Boxr Gem的代理类工作进行写作测试,该类别使用Boxr Gem将HTTP调用用于Box API。目前,我有以下方法:

class BoxApi
 ####
  def upload_file_to_box(file_path, file, box_folder_id)
    client.upload_file(file_path, self.folder(box_folder_id))
  rescue Boxr::BoxrError
    file = find_file_by_name(file).shift
    client.upload_new_version_of_file(file_path, file)
  end

我想测试upload_file_to_box执行时,client的方法upload_file与参数file_pathfolder调用。我猜这种情况下的错误是self.folder方法。

从ID中检索文件夹如下:

class BoxApi
#######
  def folder(box_folder_id)
    prepare_folder(box_folder_id)
  end
  def prepare_folder(folder_id)
    client.folder_from_id(folder_id)
  end

我认为这是错误的来源。但是,method固定返回字符串。allow(subject).to receive(:folder).with(folder_id).and_return('123')

这是完整的方法测试:

context 'success' do
  subject { BoxApi.new }
  let(:client) { Boxr::Client.new(refresh_token: nil, jwt_private_key: nil) }
  let(:file_path) {'spec/fixtures/pdfs/pdf_without_data.pdf'}
  let(:file_name) {'pdf_without_data.pdf'}
  let(:folder_id) {'123'}
  it 'Uploads file to folder on Box' do
    allow(subject).to receive(:client).and_return(client)
    allow(subject).to receive(:folder).with(folder_id).and_return('123')
    allow(client).to receive(:upload_file).with(file_path, folder_id).and_return(status: 201)

    subject.upload_file_to_box(file_path, file_name, folder_id)
    expect(client).to receive(:upload_file).with(file_path, folder_id)
  end
end

如果我将pry进入测试案例,我可以看到calling文件夹确实返回了预期字符串。

[1] pry(#<RSpec::ExampleGroups::BoxApi::UploadFileToBox::Fail>)> subject.upload_file_to_box(file_path, file_name, folder_id)
=> {:status=>201}
[2] pry(#<RSpec::ExampleGroups::BoxApi::UploadFileToBox::Fail>)> self
=> #<RSpec::ExampleGroups::BoxApi::UploadFileToBox::Fail "Uploads file to folder on Box" (./spec/clients/box_api.rb:101)>
[3] pry(#<RSpec::ExampleGroups::BoxApi::UploadFileToBox::Fail>)> subject.folder(folder_id)
=> "123"
[4] pry(#<RSpec::ExampleGroups::BoxApi::UploadFileToBox::Fail>)>

但是,当我运行测试时,我仍然会收到错误,就好像upload_file_to_box从未被调用。

Failures:
  1) BoxApi#upload_file_to_box fail Uploads file to folder on Box
     Failure/Error: expect(client).to receive(:upload_file).with(file_path, folder_id)
       (#<Boxr::Client:0x00007fea5f8b1db0 @access_token="123", @refresh_token=nil, @client_id="1234", @client_secret="345", @enterprise_id=nil, @jwt_private_key=nil, @jwt_private_key_password="1234545677", @jwt_public_key_id="12345467", @identifier=nil, @as_user_id=nil, @token_refresh_listener=nil>).upload_file("spec/fixtures/pdfs/pdf_without_data.pdf", "123")
           expected: 1 time with arguments: ("spec/fixtures/pdfs/pdf_without_data.pdf", "123")
           received: 0 times

我认为您可以从将expect(client).to receive(:upload_file).with(file_path, folder_id)放在subject.upload_file_to_box(file_path, file_name, folder_id)

上开始

相关内容

  • 没有找到相关文章

最新更新