require "rails_helper"


RSpec.describe "Preview", type: :request do
  describe "GET /preview/title" do
    it "401 unless logged in" do
      sign_out
      get "/preview/title", params: { url: "example.com" }
      expect(response).to have_http_status(:unauthorized)
    end

    it "400 when url blank" do
      sign_in_as(create(:user))
      get "/preview/title", params: { url: "" }
      expect(response).to have_http_status(:bad_request)
    end

    it "returns parsed title (stubbing URI.open)" do
      sign_in_as(create(:user))
      fake_html = "<html><head><title>  Hello  </title></head></html>"
      allow(URI).to receive(:open).and_return(StringIO.new(fake_html))

      get "/preview/title", params: { url: "example.com" }
      expect(response).to have_http_status(:ok)
      expect(json["title"]).to eq("Hello")
    end
  end
end
