Why rails_blob_url in the application and in the test works generates different links?

876 Views Asked by At

In ReviewsController serializers are used to display json. Like here:

 render json: @reviews, each_serializer: ReviewSerializer, root: false

The serializer uses the following attribute :image. Like this:

class ReviewSerializer < ActiveModel::Serializer
  attributes :id, :image          
  include Rails.application.routes.url_helpers

  def image
    rails_blob_url(object.image) if object.image.attached?
  end
end

A helper 'rails_blob_url' is used here.

The same helper is used in the spec_test. Like here:

run_test! do
  expect(response_body).to eq([{ id:   review.id,
                                image: rails_blob_url(review.image) }])
end

When running the test, the links to the image do not match

:image=>
    - "http://www.example.com/rails/active_storage/blobs/redirect/ey.../test_image.jpg"
    + "http://localhost/rails/active_storage/blobs/redirect/ey.../test_image.jpg"

Do you know what the problem might be? And how to fix it?

P.S.: I read this How to get rails_blob_url for the avatar attached to User Model from Userspublication?

and this rails_blob_path host: and only_path: true returns the same?, but I didn't find the answer there

2

There are 2 best solutions below

2
On

You need to set the host in url options. For tests, add

Rails.application.routes.default_url_options[:host] = 'localhost:3000'

to config/environments/test.rb

Failing that, try setting ActiveStorage::Current.host = "http://localhost:3000" before running the specs.

0
On

My problem was solved when I updated docker-compose to version 2.3.4