how to stub active storage urls?

Viewed 283

I'm writing a system test for an app that uses active storage. The view I'm testing includes presigned urls to objects on amazon s3. I'd obviously like to avoid sending GET requests to s3 in my tests. Instead, I'd like to "stub" active storage so that the urls for my attachments all point to one particular file on my test machine ("/test_data/placeholder.jpg"), rather than to s3.

My view code uses url_for to generate s3 urls. How can I stub url_for to return my one specific desired url?

Excerpts of my failed attempt follow.

In my view (user.jbuilder.json):

json.user_thumbnail = url_for @user.photo.variant(resize: "100x100")

In my tests:

class UserPageTest < ApplicationSystemTestCase

  test "thumbnail appears on user page" do

    User.any_instance.stubs(:photo).returns(stub(:url => "/test_data/placeholder_thumbnail.jpg") ))

    visit '/user_profile/123'
  end
end

When I run the test I get this error:

2021-11-04 20:26:40 -0400 Rack app ("GET /user/123.json" - (127.0.0.1)): #<Minitest::Assertion: unexpected invocation: #<Mock:0x7ff448c52af8>.to_model()
1 Answers

In the end I accomplished this by monkey patching activestorage inside my tests. I redirect to different placeholder files depending on the class of the object I'm dealing with.

ActiveStorage::Blobs::RedirectController.class_eval do 
  def show
    case @blob.attachments.first.record.class.name
    when "Video"
      redirect_to "/test_data/video.mp4"
    when "Photo"
      redirect_to "/test_data/photo.png"
    else
      raise StandardError.new "unhandled redirection in ActiveStorage::Blobs::RedirectController monkey patch"
    end
  end

#  include ActiveStorage::SetBlob

#  def show
#    expires_in ActiveStorage.service_urls_expire_in
#    redirect_to @blob.url(disposition: params[:disposition])
#  end

end


ActiveStorage::Representations::RedirectController.class_eval do 
  def show
    case @blob.attachments.first.record.class.name
    when "Video"
      redirect_to "/test_data/video.mp4"
    when "Photo"
      redirect_to "/test_data/photo.png"
    else
      raise StandardError.new "unhandled redirection in ActiveStorage::Blobs::RedirectController monkey patch"
    end
  end
end
Related