A platform for community discussion. Free, open, simple.
DEV: Simplify the Amazon onebox engine
Régis Hanolc68a60a8c2ea
diff --git a/lib/onebox/engine/amazon_onebox.rb b/lib/onebox/engine/amazon_onebox.rbindex 21e91620645..4ba2f9736a4 100644--- a/lib/onebox/engine/amazon_onebox.rb+++ b/lib/onebox/engine/amazon_onebox.rb@@ -1,14 +1,10 @@# frozen_string_literal: true-require "json"-require "onebox/open_graph"-module Oneboxmodule Engineclass AmazonOneboxinclude Engineinclude LayoutSupport- include HTMLalways_httpsmatches_regexp(@@ -16,236 +12,121 @@ module Onebox)def url- if match && match[:id]- canonical_link = @raw&.at('//link[@rel="canonical"]/@href').to_s- return canonical_link if canonical_link.match?(%r{/dp/#{match[:id]}\z}i)-- id =- Addressable::URI.encode_component(match[:id], Addressable::URI::CharacterClasses::PATH)- return "https://www.amazon.#{tld}/dp/#{id}"- end+ return @url unless asin- @url- end+ canonical = @raw&.at('link[rel="canonical"]')&.[]("href").to_s+ return canonical if canonical.match?(%r{/dp/#{asin}\z}i)- def tld- @tld ||= @@matcher.match(@url)["tld"]+ "https://www.amazon.#{@@matcher.match(@url)[:tld]}/dp/#{asin}"end- def http_params- { "User-Agent" => @options[:user_agent] } if @options && @options[:user_agent]- end-- def to_html(ignore_errors = false)- unless ignore_errors- verified_data # forces a check for missing fields- return "" unless errors.empty?- end-- super()+ def to_html+ verified_data+ errors.empty? ? super : ""enddef placeholder_html- to_html(true)+ layout.to_htmlenddef verified_data@verified_data ||=- begin- result = data-- required_tags = %i[title description]- required_tags.each do |tag|- if result[tag].blank?- errors[tag] ||= []- errors[tag] << "is blank"- end- end-- result+ data.tap do |result|+ %i[title description].each { |tag| errors[tag] = ["is blank"] if result[tag].blank? }end-- @verified_dataendprivate- def match- @match ||= @url.match(%r{(?:d|g)p/(?:product/|video/detail/)?(?<id>[A-Z0-9]+)(?:/|\?|$)}mi)+ def asin+ @asin ||= @url[%r{[dg]p/(?:product/|video/detail/)?([A-Z0-9]+)(?:[/?]|$)}i, 1]enddef raw@raw ||=Nokogiri.HTML(- begin- Onebox::Helpers.fetch_response(- url,- headers: http_params,- raise_error_when_response_too_large: false,- )- rescue StandardError- nil- end,+ Onebox::Helpers.fetch_response(url, raise_error_when_response_too_large: false),)+ rescue StandardError+ @raw = Nokogiri.HTML("")end- def image- if (main_image = raw.css("#main-image")) && main_image.any?- attributes = main_image.first.attributes-- if attributes["data-a-hires"]- return attributes["data-a-hires"].to_s- elsif attributes["data-a-dynamic-image"]- return ::JSON.parse(attributes["data-a-dynamic-image"].value).keys.first+ def data+ @data ||=+ begin+ og = ::Onebox::OpenGraph.new(raw)+ description =+ og.description || text("#productDescription") ||+ raw.at("meta[name=description]")&.[]("content")++ {+ link: url,+ title: CGI.unescapeHTML(og.title.to_s),+ image: og.image || image,+ description:+ description && CGI.unescapeHTML(Onebox::Helpers.truncate(description, 250)),+ price:,+ }.merge(book_details)end- end-- if (landing_image = raw.css("#landingImage")) && landing_image.any?- attributes = landing_image.first.attributes+ end- if attributes["data-old-hires"].to_s.present?- return attributes["data-old-hires"].to_s- else- return landing_image.first["src"].to_s+ def book_details+ details =+ if raw.at("#dp.book_mobile")+ row =+ "//div[@id='productDetails_secondary_view_div']//table[@id='productDetails_techSpec_section_1']//tr[%d]//td"+ {+ title: text("h1#title"),+ isbn_asin_text: "ISBN",+ isbn_asin: text(row % 8),+ publisher: text(row % 1),+ published: text(row % 2),+ }+ elsif raw.at("#dp.ebooks_mobile")+ row = "//div[@id='detailBullets_secondary_view_div']//ul//li[%d]/span/span[2]"+ {+ title: text("#ebooksTitle"),+ isbn_asin_text: "ASIN",+ isbn_asin: text(row % 4),+ publisher: text(row % 2),+ published: text(row % 1),+ }end- end- if (ebook_image = raw.css("#ebooksImgBlkFront")) && ebook_image.any?- ::JSON.parse(ebook_image.first.attributes["data-a-dynamic-image"].value).keys.first- end- end+ return {} unless details- def price- # get item price (Amazon markup is inconsistent, deal with it)- if raw.css("#priceblock_ourprice .restOfPrice")[0] &&- raw.css("#priceblock_ourprice .restOfPrice")[0].inner_text- "#{raw.css("#priceblock_ourprice .restOfPrice")[0].inner_text}#{raw.css("#priceblock_ourprice .buyingPrice")[0].inner_text}.#{raw.css("#priceblock_ourprice .restOfPrice")[1].inner_text}"- elsif raw.css("#priceblock_dealprice") &&- (dealprice = raw.css("#priceblock_dealprice span")[0])- dealprice.inner_text- elsif !raw.css("#priceblock_ourprice").inner_text.empty?- raw.css("#priceblock_ourprice").inner_text- else- result = raw.css("#corePrice_feature_div .a-price .a-offscreen").first&.inner_text- if result.blank?- result = raw.css(".mediaMatrixListItem.a-active .a-color-price").inner_text- end+ rating =+ text("#averageCustomerReviews_feature_div .a-icon") ||+ text("#acrCustomerReviewLink .a-icon")- result- end+ details.merge(+ by_info: text("#byline, #bylineInfo"),+ rating: rating && "#{rating}, ",+ published: details[:published] && "#{details[:published]}#{", " if price}",+ )end- def multiple_authors(authors_xpath)- raw.xpath(authors_xpath).map { |a| a.inner_text.strip }.join(", ")+ def image+ landing_image = raw.at("#landingImage")++ raw.at("#main-image")&.[]("data-a-hires").presence ||+ landing_image&.[]("data-old-hires").presence || landing_image&.[]("src").presence ||+ raw+ .at("#ebooksImgBlkFront")+ &.[]("data-a-dynamic-image")+ &.then { |json| ::JSON.parse(json).keys.first }end- def data- og = ::Onebox::OpenGraph.new(raw)-- if raw.at_css("#dp.book_mobile") # printed books- title = raw.at("h1#title")&.inner_text- authors =- (- if raw.at_css("#byline_secondary_view_div")- multiple_authors(- "//div[@id='byline_secondary_view_div']//span[@class='a-text-bold']",- )- else- raw.at("#byline")&.inner_text- end- )- rating =- raw.at("#averageCustomerReviews_feature_div .a-icon")&.inner_text ||- raw.at("#cmrsArcLink .a-icon")&.inner_text-- table_xpath =- "//div[@id='productDetails_secondary_view_div']//table[@id='productDetails_techSpec_section_1']"- isbn = raw.xpath("#{table_xpath}//tr[8]//td").inner_text.strip-- # if ISBN is misplaced or absent it's hard to find out which data is- # available and where to find it so just set it all to nil- if /^\d(\-?\d){12}$/.match(isbn)- publisher = raw.xpath("#{table_xpath}//tr[1]//td").inner_text.strip- published = raw.xpath("#{table_xpath}//tr[2]//td").inner_text.strip- book_length = raw.xpath("#{table_xpath}//tr[6]//td").inner_text.strip- else- isbn = publisher = published = book_length = nil- end+ def price+ amount =+ text("#corePrice_feature_div .a-price .a-offscreen") ||+ text(".mediaMatrixListItem.a-active .a-color-price")- result = {- link: url,- title: title,- by_info: authors,- image: og.image || image,- description: raw.at("#productDescription")&.inner_text,- rating: "#{rating}#{", " if rating && (!isbn&.empty? || !price&.empty?)}",- price: price,- isbn_asin_text: "ISBN",- isbn_asin: isbn,- publisher: publisher,- published: "#{published}#{", " if published && !price&.empty?}",- }- elsif raw.at_css("#dp.ebooks_mobile") # ebooks- title = raw.at("#ebooksTitle")&.inner_text- authors =- (- if raw.at_css("#a-popover-mobile-udp-contributor-popover-id")- multiple_authors(- "//div[@id='a-popover-mobile-udp-contributor-popover-id']//span[contains(@class,'a-text-bold')]",- )- else- raw.at("#byline")&.inner_text&.strip || raw.at("#bylineInfo")&.inner_text&.strip- end- )- rating =- raw.at("#averageCustomerReviews_feature_div .a-icon")&.inner_text ||- raw.at("#cmrsArcLink .a-icon")&.inner_text ||- raw.at("#acrCustomerReviewLink .a-icon")&.inner_text-- table_xpath = "//div[@id='detailBullets_secondary_view_div']//ul"- asin = raw.xpath("#{table_xpath}//li[4]/span/span[2]").inner_text-- # if ASIN is misplaced or absent it's hard to find out which data is- # available and where to find it so just set it all to nil- if /^[0-9A-Z]{10}$/.match(asin)- publisher = raw.xpath("#{table_xpath}//li[2]/span/span[2]").inner_text- published = raw.xpath("#{table_xpath}//li[1]/span/span[2]").inner_text- else- asin = publisher = published = nil- end+ amount unless amount&.start_with?("$0")+ end- result = {- link: url,- title: title,- by_info: authors,- image: og.image || image,- description: raw.at("#productDescription")&.inner_text,- rating: "#{rating}#{", " if rating && (!asin&.empty? || !price&.empty?)}",- price: price,- isbn_asin_text: "ASIN",- isbn_asin: asin,- publisher: publisher,- published: "#{published}#{", " if published && !price&.empty?}",- }- else- title = CGI.unescapeHTML(og.title || raw.css("title").inner_text)- result = { link: url, title: title, image: og.image || image, price: price }-- result[:by_info] = raw.at("#by-line")- result[:by_info] = Onebox::Helpers.clean(result[:by_info].inner_html) if result[:by_info]-- summary = raw.at("#productDescription")-- description = og.description || summary&.inner_text&.strip- description = raw.css("meta[name=description]").first&.[]("content") if description.blank?- result[:description] = CGI.unescapeHTML(- Onebox::Helpers.truncate(description, 250),- ) if description- end-- result[:price] = nil if result[:price].start_with?("$0") || result[:price] == 0-- result+ def text(path)+ raw.at(path)&.inner_text&.strip.presenceendendenddiff --git a/spec/lib/onebox/engine/amazon_onebox_spec.rb b/spec/lib/onebox/engine/amazon_onebox_spec.rbindex f38a7bb7318..f4b3dfd4d87 100644--- a/spec/lib/onebox/engine/amazon_onebox_spec.rb+++ b/spec/lib/onebox/engine/amazon_onebox_spec.rb@@ -1,192 +1,61 @@# frozen_string_literal: trueRSpec.describe Onebox::Engine::AmazonOnebox do- describe "regular amazon page" do- before do- @link = "https://www.amazon.com/Knit-Noro-Accessories-Colorful-Little/dp/193609620X"- @uri = "https://www.amazon.com/dp/193609620X"- end-- include_context "with engines"- it_behaves_like "an engine"-- describe "works with international domains" do- def check_link(tdl, link)- onebox_cls = Onebox::Matcher.new(link).oneboxed- expect(onebox_cls).to_not be(nil)- expect(onebox_cls.new(link).url).to include("https://www.amazon.#{tdl}")- end-- it "matches canadian domains" do- check_link(- "ca",- "https://www.amazon.ca/Too-Much-Happiness-Alice-Munro-ebook/dp/B0031TZ98K/",- )- end-- it "matches german domains" do- check_link(- "de",- "https://www.amazon.de/Buddenbrooks-Verfall-einer-Familie-Roman/dp/3596294312/",- )- end-- it "matches uk domains" do- check_link("co.uk", "https://www.amazon.co.uk/Pygmalion-George-Bernard-Shaw/dp/1420925237/")- end-- it "matches japanese domains" do- check_link(- "co.jp",- "https://www.amazon.co.jp/%E9%9B%AA%E5%9B%BD-%E6%96%B0%E6%BD%AE%E6%96%87%E5%BA%AB-%E3%81%8B-1-1-%E5%B7%9D%E7%AB%AF-%E5%BA%B7%E6%88%90/dp/4101001014/",- )- end-- it "matches chinese domains" do- check_link(- "cn",- "https://www.amazon.cn/%E5%AD%99%E5%AD%90%E5%85%B5%E6%B3%95-%E5%AD%99%E8%86%91%E5%85%B5%E6%B3%95-%E5%AD%99%E6%AD%A6/dp/B0011C40FC/",- )- end-- it "matches french domains" do- check_link(- "fr",- "https://www.amazon.fr/Les-Mots-autres-%C3%A9crits-autobiographiques/dp/2070114147/",- )- end-- it "matches italian domains" do- check_link("it", "https://www.amazon.it/Tutte-poesie-Salvatore-Quasimodo/dp/8804520477/")- end-- it "matches spanish domains" do- check_link(- "es",- "https://www.amazon.es/familia-Pascual-Duarte-Camilo-Jos%C3%A9-ebook/dp/B00EJRTKTW/",- )- end-- it "matches brazilian domains" do- check_link(- "com.br",- "https://www.amazon.com.br/A-p%C3%A1tria-chuteiras-Nelson-Rodrigues-ebook/dp/B00J2B414Y/",- )- end-- it "matches indian domains" do- check_link("in", "https://www.amazon.in/Fireflies-Rabindranath-Tagore/dp/9381523169/")- end-- it "matches mexican domains" do- check_link(- "com.mx",- "https://www.amazon.com.mx/Legend-Zelda-Links-Awakening-Nintendo/dp/B07SG15148/",- )- end- end-- describe "#url" do- let(:long_url) do- "https://www.amazon.ca/gp/product/B087Z3N428?pf_rd_r=SXABADD0ZZ3NF9Q5F8TW&pf_rd_p=05378fd5-c43e-4948-99b1-a65b129fdd73&pd_rd_r=0237fb28-7f47-49f4-986a-be0c78e52863&pd_rd_w=FfIoI&pd_rd_wg=Hw4qq&ref_=pd_gw_unk"- end-- it "maintains the same http/https scheme as the requested URL" do- expect(described_class.new("https://www.amazon.fr/gp/product/B01BYD0TZM").url).to eq(- "https://www.amazon.fr/dp/B01BYD0TZM",- )-- expect(described_class.new("http://www.amazon.fr/gp/product/B01BYD0TZM").url).to eq(- "https://www.amazon.fr/dp/B01BYD0TZM",- )- end-- it "removes parameters from the URL" do- expect(described_class.new(long_url).url).not_to include("?pf_rd_r")- end- end-- describe "#to_html" do- it "includes image" do- expect(html).to include(- "https://images-na.ssl-images-amazon.com/images/I/51opYcR6kVL._SY400_.jpg",- )- end-- it "includes description" do- expect(html).to include(- "You should learn a programming language every year, as recommended by The Pragmatic Programmer.",- )- end-- it "includes price" do- expect(html).to include("$21.11")- end-- it "includes title" do- expect(html).to include(- "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",- )- end- end- end-- describe "amazon with opengraph" do- let(:link) { "https://www.amazon.com/dp/B01MFXN4Y2" }- let(:html) { described_class.new(link).to_html }-- before do- stub_request(:get, "https://www.amazon.com/dp/B01MFXN4Y2").to_return(- status: 200,- body: onebox_response("amazon-og"),- )- end-- describe "#to_html" do- it "includes image" do- expect(html).to include(- "https://images-na.ssl-images-amazon.com/images/I/51nOF2iBa6L._SX940_.jpg",- )- end-- it "includes description" do- expect(html).to include(- "CHRISTINE is the story of an aspiring newswoman caught in the midst of a personal and professional life crisis. Between unrequited love, frustration at work, a tumultuous home, and self-doubt; she begins to spiral down a dark path.",- )- end-- it "includes title" do- expect(html).to include("Watch Christine online & foobar - Amazon Video")+ describe "#url" do+ it "normalizes product URLs" do+ {+ "https://www.amazon.ca/Too-Much-Happiness-Alice-Munro-ebook/dp/B0031TZ98K/" =>+ "https://www.amazon.ca/dp/B0031TZ98K",+ "https://www.amazon.de/Buddenbrooks-Verfall-einer-Familie-Roman/dp/3596294312/" =>+ "https://www.amazon.de/dp/3596294312",+ "https://www.amazon.co.uk/Pygmalion-George-Bernard-Shaw/dp/1420925237/" =>+ "https://www.amazon.co.uk/dp/1420925237",+ "https://www.amazon.co.jp/%E9%9B%AA%E5%9B%BD-%E6%96%B0%E6%BD%AE%E6%96%87%E5%BA%AB-%E3%81%8B-1-1-%E5%B7%9D%E7%AB%AF-%E5%BA%B7%E6%88%90/dp/4101001014/" =>+ "https://www.amazon.co.jp/dp/4101001014",+ "https://www.amazon.cn/%E5%AD%99%E5%AD%90%E5%85%B5%E6%B3%95-%E5%AD%99%E8%86%91%E5%85%B5%E6%B3%95-%E5%AD%99%E6%AD%A6/dp/B0011C40FC/" =>+ "https://www.amazon.cn/dp/B0011C40FC",+ "https://www.amazon.fr/Les-Mots-autres-%C3%A9crits-autobiographiques/dp/2070114147/" =>+ "https://www.amazon.fr/dp/2070114147",+ "https://www.amazon.it/Tutte-poesie-Salvatore-Quasimodo/dp/8804520477/" =>+ "https://www.amazon.it/dp/8804520477",+ "https://www.amazon.es/familia-Pascual-Duarte-Camilo-Jos%C3%A9-ebook/dp/B00EJRTKTW/" =>+ "https://www.amazon.es/dp/B00EJRTKTW",+ "https://www.amazon.com.br/A-p%C3%A1tria-chuteiras-Nelson-Rodrigues-ebook/dp/B00J2B414Y/" =>+ "https://www.amazon.com.br/dp/B00J2B414Y",+ "https://www.amazon.in/Fireflies-Rabindranath-Tagore/dp/9381523169/" =>+ "https://www.amazon.in/dp/9381523169",+ "https://www.amazon.com.mx/Legend-Zelda-Links-Awakening-Nintendo/dp/B07SG15148/" =>+ "https://www.amazon.com.mx/dp/B07SG15148",+ "http://www.amazon.fr/gp/product/B01BYD0TZM" => "https://www.amazon.fr/dp/B01BYD0TZM",+ "https://www.amazon.ca/gp/product/B087Z3N428?pf_rd_r=SXABADD0ZZ3NF9Q5F8TW&ref_=pd_gw_unk" =>+ "https://www.amazon.ca/dp/B087Z3N428",+ }.each do |link, url|+ expect(Onebox::Matcher.new(link).oneboxed).to eq(described_class)+ expect(described_class.new(link).url).to eq(url)endendenddescribe "amazon book page" do- let(:link) { "https://www.amazon.com/dp/B00AYQNR46" }- let(:html) { described_class.new(link).to_html }-before do- stub_request(:get, "https://www.amazon.com/dp/B00AYQNR46").to_return(- status: 200,- body: onebox_response("amazon"),- )+ @link = "https://www.amazon.com/Knit-Noro-Accessories-Colorful-Little/dp/193609620X"+ @uri = "https://www.amazon.com/dp/193609620X"end- describe "#to_html" do- it "includes title and author" do- expect(html).to include(- "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",- )- expect(html).to include("Bruce Tate")- end-- it "includes ISBN" do- expect(html).to include("978-1934356593")- end+ include_context "with engines"+ it_behaves_like "an engine"- it "includes publisher" do- expect(html).to include("Pragmatic Bookshelf")- end+ it "renders the book details" do+ expect(html).to include(+ %(href="https://www.amazon.com/dp/193609620X"),+ "https://images-na.ssl-images-amazon.com/images/I/51opYcR6kVL._SY400_.jpg",+ "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",+ "Bruce Tate",+ "You should learn a programming language every year, as recommended by The Pragmatic Programmer.",+ "978-1934356593",+ "Pragmatic Bookshelf",+ "$21.11",+ )endend@@ -195,65 +64,34 @@ RSpec.describe Onebox::Engine::AmazonOnebox dolet(:html) { described_class.new(link).to_html }before do- stub_request(:get, "https://www.amazon.com/dp/193435659X").to_return(- status: 200,- body: onebox_response("amazon-ebook"),- )+ stub_request(:get, link).to_return(status: 200, body: onebox_response("amazon-ebook"))end- describe "#to_html" do- it "includes title and author" do- expect(html).to include(- "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",- )- expect(html).to include("Bruce Tate")- end-- it "includes image" do- expect(html).to include(- "https://images-na.ssl-images-amazon.com/images/I/51LZT%2BtSrTL._SX133_.jpg",- )- end-- it "includes ASIN" do- expect(html).to include("B00AYQNR46")- end-- it "includes rating" do- expect(html).to include("4.2 out of 5 stars")- end-- it "includes publisher" do- expect(html).to include("Pragmatic Bookshelf")- end+ it "renders the ebook details" do+ expect(html).to include(+ "https://images-na.ssl-images-amazon.com/images/I/51LZT%2BtSrTL._SX133_.jpg",+ "Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages (Pragmatic Programmers)",+ "Bruce Tate",+ "4.2 out of 5 stars",+ "B00AYQNR46",+ "Pragmatic Bookshelf",+ )endend- describe "non-standard response from Amazon" do- let(:link) { "https://www.amazon.com/dp/B0123ABCD3210" }- let(:onebox) { described_class.new(link) }-- before do- stub_request(:get, "https://www.amazon.com/dp/B0123ABCD3210").to_return(- status: 200,- body: onebox_response("amazon-error"),- )- end+ describe "amazon with opengraph" do+ let(:link) { "https://www.amazon.com/dp/B01MFXN4Y2" }+ let(:html) { described_class.new(link).to_html }- it "returns a blank result" do- expect(onebox.to_html).to eq("")- end+ before { stub_request(:get, link).to_return(status: 200, body: onebox_response("amazon-og")) }- it "produces a placeholder" do- expect(onebox.placeholder_html).to include(- '<aside class="onebox amazon" data-onebox-src="https://www.amazon.com/dp/B0123ABCD3210">',+ it "renders the product details" do+ expect(html).to include(+ "https://images-na.ssl-images-amazon.com/images/I/51nOF2iBa6L._SX940_.jpg",+ "Watch Christine online & foobar - Amazon Video",+ "CHRISTINE is the story of an aspiring newswoman caught in the midst of a personal and professional life crisis. Between unrequited love, frustration at work, a tumultuous home, and self-doubt; she begins to spiral down a dark path.",)end-- it "returns errors" do- onebox.to_html- expect(onebox.errors).to eq({ title: ["is blank"], description: ["is blank"] })- endenddescribe "alternate page layout response from Amazon" do@@ -261,36 +99,17 @@ RSpec.describe Onebox::Engine::AmazonOnebox dolet(:html) { described_class.new(link).to_html }before do- stub_request(:get, "https://www.amazon.com/dp/B07FQ7M16H").to_return(- status: 200,- body: onebox_response("amazon-alternate"),- )+ stub_request(:get, link).to_return(status: 200, body: onebox_response("amazon-alternate"))end- describe "#to_html" do- it "includes image" do- expect(html).to include("https://m.media-amazon.com/images/I/71y4BRqNP7L._AC_SL1500_.jpg")- end-- it "includes description" do- expect(html).to include(- "Drill Attachment for Straight Curve and Circle Cutting, Maximum 14 Gauge Steel",- )- end-- it "includes price" do- expect(html).to include("$37.99")- end-- it "includes title" do- expect(html).to include("Quality Nibbler Drill Attachment...")- end-- it "links to the canonical product page" do- expect(html).to include(- %(href="https://www.amazon.com/Lnchett-Nibbler-Quality-Attachment-Straight/dp/B07FQ7M16H"),- )- end+ it "renders the product details" do+ expect(html).to include(+ %(href="https://www.amazon.com/Lnchett-Nibbler-Quality-Attachment-Straight/dp/B07FQ7M16H"),+ "https://m.media-amazon.com/images/I/71y4BRqNP7L._AC_SL1500_.jpg",+ "Quality Nibbler Drill Attachment...",+ "Drill Attachment for Straight Curve and Circle Cutting, Maximum 14 Gauge Steel",+ "$37.99",+ )endend@@ -316,4 +135,21 @@ RSpec.describe Onebox::Engine::AmazonOnebox doexpect(html).to include("SwiftJet Car Wash Foam Gun", %(href="#{link}"), %(src="#{image}"))endend++ describe "non-standard response from Amazon" do+ let(:link) { "https://www.amazon.com/dp/B0123ABCD3210" }+ let(:onebox) { described_class.new(link) }++ before do+ stub_request(:get, link).to_return(status: 200, body: onebox_response("amazon-error"))+ end++ it "returns a blank result with errors and a placeholder" do+ expect(onebox.to_html).to eq("")+ expect(onebox.errors).to eq({ title: ["is blank"], description: ["is blank"] })+ expect(onebox.placeholder_html).to include(+ %(<aside class="onebox amazon" data-onebox-src="#{link}">),+ )+ end+ endend