繁体   English   中英

Rspec:存根ActiveStorage下载方法

[英]Rspec : stubbing ActiveStorage download method

我在一个使用ActiveStorage在S3上存储缓存数据的系统上工作,然后再将其用于其他用途。 在我的规范中,我想存根该文件的下载方法,并加载特定文件以进行测试。

allow(user.cached_data).to receive(:download)
                       .and_return(read_json_file('sample_data.json'))

read_json_fileFile.read然后JSON.parse数据文件的规范帮助器。)

我收到此错误:

#<ActiveStorage::Attached::One:0x00007f9304a934d8 @name="cached_data", 
@record=#<User id: 4, name: "Bob", email: "bob@email.com",
created_at: "2019-08-22 09:11:16", updated_at: "2019-08-22 09:11:16">,
@dependent=:purge_later> does not implement: download

我不明白, 文档清楚地说这个对象应该实现下载。

编辑

根据JigneshStephen的建议,我尝试了以下操作:

allow(user.cached_data.blob).to receive(:download)
                            .and_return(read_json_file('sample_data.json'))

我得到了以下错误:

Module::DelegationError:
       blob delegated to attachment, but attachment is nil

user是由FactoryBot生成的,因此我目前正在尝试将我的cached_data示例文件附加到该对象。

我的工厂是这样的:

FactoryBot.define do
  factory :user
    name { 'Robert' }
    email  { 'robert@email.com' }

    after(:build) do |user|
      user.cached_data.attach(io: File.open("spec/support/sample_data.json"), filename: 'sample.json', content_type: 'application/json')
    end
  end
end

但是,当我after buildafter build将其添加到工厂时,出现以下错误:

ActiveRecord::LockWaitTimeout:
       Mysql2::Error::TimeoutError: Lock wait timeout exceeded

也许这是另一个Stackoverflow问题。

正如其他人在评论中指出的那样,# #download是在ActiveStorage::Blob类而不是ActiveStorage::Attached::One 您可以通过以下方式下载文件:

if user.cached_data.attached?
  user.cached_data.blob.download
end

我添加了检查以确保cached_data已附加,因为blob委托该附件,如果未附加将失败。

这是#download文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM