我目前正在为使用Boxr gem进行Box API的http调用的代理类编写测试。目前,我有以下方法:
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_path
的方法folder
。我猜这种情况下的错误是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
答案 0 :(得分:1)
我认为您可以将expect(client).to receive(:upload_file).with(file_path, folder_id)
放在subject.upload_file_to_box(file_path, file_name, folder_id)
上方