* Increase cache TTL for social preview images These are expensive to generate + don't change often. We can have a long cache. Ideally, they would never expire, and get auto evicted by redis when space fills up. But I don't think a `nil` ttl is possible when a default is set in the Rails config (see production.rb). So I set it to a real long value. + test to guard against it accidently being changed. * Try a cache expiration of 6.weeks as suggested by @mstruve in PR
61 lines
2.5 KiB
Ruby
61 lines
2.5 KiB
Ruby
require "rails_helper"
|
|
|
|
RSpec.describe HtmlCssToImage, type: :lib do
|
|
describe ".url" do
|
|
it "returns the url to the created image" do
|
|
stub_request(:post, /hcti.io/).
|
|
to_return(status: 200,
|
|
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
|
|
headers: { "Content-Type" => "application/json" })
|
|
|
|
expect(described_class.url(html: "test")).to eq("https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1")
|
|
end
|
|
|
|
it "returns fallback image if the request fails" do
|
|
stub_request(:post, /hcti.io/).
|
|
to_return(status: 429,
|
|
body: '{ "error": "Plan limit exceeded" }',
|
|
headers: { "Content-Type" => "application/json" })
|
|
|
|
expect(described_class.url(html: "test")).to eq described_class::FALLBACK_IMAGE
|
|
end
|
|
end
|
|
|
|
describe ".fetch_url" do
|
|
before do
|
|
allow(Rails.cache).to receive(:write)
|
|
allow(Rails.cache).to receive(:read)
|
|
end
|
|
|
|
it "caches the image url when successful" do
|
|
stub_request(:post, /hcti.io/).
|
|
to_return(status: 200,
|
|
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
|
|
headers: { "Content-Type" => "application/json" })
|
|
|
|
expect(described_class.fetch_url(html: "test")).to eq("https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1")
|
|
expect(Rails.cache).to have_received(:write).once
|
|
end
|
|
|
|
it "cache has a long expiration" do
|
|
# Images are expensive to generate, make sure we don't expire them too quickly.
|
|
stub_request(:post, /hcti.io/).
|
|
to_return(status: 200,
|
|
body: '{ "url": "https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1" }',
|
|
headers: { "Content-Type" => "application/json" })
|
|
|
|
expect(described_class.fetch_url(html: "test")).to eq("https://hcti.io/v1/image/6c52de9d-4d37-4008-80f8-67155589e1a1")
|
|
expect(Rails.cache).to have_received(:write).with(anything, anything, expires_in: HtmlCssToImage::CACHE_EXPIRATION).once
|
|
end
|
|
|
|
it "does not cache errors" do
|
|
stub_request(:post, /hcti.io/).
|
|
to_return(status: 429,
|
|
body: '{ "error": "Plan limit exceeded" }',
|
|
headers: { "Content-Type" => "application/json" })
|
|
|
|
expect(described_class.fetch_url(html: "test")).to eq described_class::FALLBACK_IMAGE
|
|
expect(Rails.cache).not_to have_received(:write)
|
|
end
|
|
end
|
|
end
|