我正在为使用外部服务的Rails项目编写规范(在本例中为Aws :: S3)。我会在upload_file
的任何实例上存根调用Aws::S3::Object
,并且能够在事后检查此类的实例是否已接到对upload_file
的调用。
到目前为止我做了什么:
allow_any_instance_of(Aws::S3::Object).to receive(:upload_file).and_return('Stubbed!')
和
expect_any_instance_of(Aws::S3::Object).to receive(:upload_file)
但不知怎的,期望不起作用(我的代码调用upload_file
但RSpec没有看到它。)
答案 0 :(得分:1)
继续前进,我建议避免使用x_any_instance_of
方法outlined in the RSpec Mocks documentation。
相反,在.new
类上隐藏对Aws::S3::Object
的调用,并让instance_double
代表在您的应用中初始化的实际对象,以便您可以进行断言在它上面。
这里有一些比较两种语法的示例代码和规范:
module Aws
module S3
class Object
def upload_file
# upload the file
end
end
end
end
class FileUploader
def self.upload
Aws::S3::Object.new.upload_file
end
end
RSpec.describe FileUploader do
describe '.upload' do
context 'using any_instance_of' do
before do
allow_any_instance_of(Aws::S3::Object).to receive(:upload_file)
end
it 'calls to upload the file on the S3 Object' do
expect_any_instance_of(Aws::S3::Object).to receive(:upload_file)
described_class.upload
end
end
context 'using an instance double' do
let(:s3_object) { instance_double('Aws::S3::Object') }
context 'stubbing a method to return the double on allow' do
before do
allow(Aws::S3::Object).to receive(:new).and_return(s3_object)
end
it 'uploads the file on the S3 Object' do
expect(s3_object).to receive(:upload_file)
described_class.upload
end
end
context 'stubbing a method to return the double on expect' do
it 'uploads the file on the S3 Object' do
expect(Aws::S3::Object).to receive(:new).and_return(s3_object)
expect(s3_object).to receive(:upload_file)
described_class.upload
end
end
end
end
end