Stubbing for Active Storage

671 views
Skip to first unread message

Joseph Haig

unread,
Jan 21, 2021, 6:05:41 AM1/21/21
to rs...@googlegroups.com
I am migrating an app from Paperclip to Active Storage and I'd like to update the controller tests for the download links, which will redirect to the expiring url in S3. I'm not using the provided url helpers rails_blob_path and rails_blob_url because we need to have authentication (see the first warning at https://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files).

My test looks (more or less) like this:

  subject(:download_attachment) { get :download_attachment, params: { id: message.id } }
  let(:message) { create :message }
  let(:service_url) { 'https://example.com/document.pdf' }

  it 'redirects to file download link' do
    allow_any_instance_of(ActiveStorage::Blob).to receive(:service_url).and_return(service_url)
    expect(download_attachment).to redirect_to service_url
  end

but I know that `allow_any_instance_of` is discouraged (and deprecated). An alternative is

  ActiveStorage::Current.host = 'https://example.com'
  download_attachment
  expect(response.location).to match %{https://example.com}

but this also feels a bit hacky.

Neither method is actually checking that the redirect is to the correct url for the correct attachment so ideally I would like to have `allow(message.attachment.blob).to receive(:service_url).and_return(service_url)`. Obviously this isn't working as the message is getting loaded new in the controller.

Is there a way to do this? Thanks.

Regards,

Joe
Reply all
Reply to author
Forward
0 new messages